三、MyBaits增删改查
1. UserMapper接口
public interface UserMapper {
public List<User> getList();
public User getById(Integer id);
public Integer insertOne(User user);
public Integer updateById(User user);
public Integer deleteById(Integer id);
}
2. UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zx.mapper.UserMapper">
<select id="getList" resultType="User">
select * from `user`;
</select>
<select id="getById" parameterType="int" resultType="User">
select * from `user` where id = #{id};
</select>
<insert id="insertOne" parameterType="User">
insert into `user`(name,pwd) values (#{name},#{pwd});
</insert>
<update id="updateById" parameterType="User">
update `user` set name=#{name},pwd=#{pwd} where id = #{id};
</update>
<delete id="deleteById" parameterType="int">
delete from `user` where id = #{id};
</delete>
</mapper>
3. 测试类
public class UserTest {
@Test
public void getList(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.getList();
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getById(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void insertOne(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setName("zl");
user.setPwd("654321");
Integer row = userMapper.insertOne(user);
if (row > 0) {
System.out.println("插入成功");
}
//必须提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateById(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer row = userMapper.updateById(new User(4,"z6","123456"));
if (row > 0) {
System.out.println("修改成功");
}
//必须提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteById(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer row = userMapper.deleteById(4);
if (row > 0) {
System.out.println("删除成功");
}
//必须提交事务
sqlSession.commit();
sqlSession.close();
}
}