mybatis从入门到精通(二) 增删查改
一丶前言
"增删查改"是后台开发的常用操作, 因此, 学习mybatis或者其他orm框架有必要统一学习一下"增删查改".
二丶准备开发环境
使用"mybatis从入门到精通(一) 入门"准备的开发环境
三丶查 -- <select/>
UserMapper.java
User selectUser(@Param("userId") int userId);
UserMapper.xml
<select id="selectUser" resultMap="UserMap"> select * from user where user_id = #{userId} </select>
MybatisTests.java
@Test public void selectTest(){ // 查询 User user=userMapper.selectUser(1); sqlSession.commit(); System.out.println("name: "+user.getUserName()+", age: "+user.getAge()); Assert.assertEquals(new Integer(1), user.getUserId()); }
四丶增 -- <insert/>
UserMapper.java
void insertUser(@Param("user") User user);
UserMapper.xml
<insert id="insertUser"> insert into user(user_id, user_name, age, country) values (#{user.userId}, #{user.userName}, #{user.age}, #{user.country}) </insert>
MybatisTests.java
@Test public void insertTest(){ // 插入 User user=createTestUser(); userMapper.insertUser(user); sqlSession.commit(); // 需要提交, 数据库才会有数据 User user_=userMapper.selectUser(9); Assert.assertEquals(true, user_!=null); Assert.assertEquals(new Integer(9), user_.getUserId()); System.out.println(user_.getUserName()); }
五丶改 -- <update/>
UserMapper.java
void updateUserNameById(@Param("userId") int userId, @Param("userName") String userName);
UserMapper.xml
<update id="updateUserNameById"> update user set user_name=#{userName} where user_id=#{userId} </update>
MybatisTests.java
@Test public void updateTest(){ User user=userMapper.selectUser(9); if(user==null){ user=createTestUser(); userMapper.insertUser(user); sqlSession.commit(); // 需要提交, 数据库才会有数据 } //修改 userMapper.updateUserNameById(9, "update_name"); sqlSession.commit(); User user_=userMapper.selectUser(9); Assert.assertEquals("update_name", user_.getUserName()); }
六丶删 -- <delete/>
UserMapper.java
void deleteUserById(@Param("userId") int userId);
UserMapper.xml
<update id="deleteUserById"> delete from user where user_id=#{userId} </update>
MybatisTests.java
@Test public void deleteTest(){ User user=userMapper.selectUser(9); if(user==null){ user=createTestUser(); userMapper.insertUser(user); sqlSession.commit(); // 需要提交, 数据库才会有数据 } //删除 userMapper.deleteUserById(9); sqlSession.commit(); User user_=userMapper.selectUser(9); Assert.assertEquals(null, user_); }
完整源码, 点此查看
学习资料:
mybatis官方文档
原文地址:https://www.cnblogs.com/timfruit/p/11161570.html
时间: 2024-10-11 13:59:27