Mybatis中的CRUD
Mybatis中的CRUD
Mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 从配置文件获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
接口
public interface UserMapper {
List<User> selectAll();
User selectById(int id);
int insertUser(User user);
int updateUser(User user);
int deleteById(int id);
}
实现映射
<?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">
<!--namespace 绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.base.dao.UserMapper">
<!--id对应方法名-->
<select id="selectAll" resultType="com.base.entity.User">
select * from user;
</select>
<select id="selectById" resultType="com.base.entity.User" parameterType="int">
select * from user where id = #{id};
</select>
<insert id="insertUser" parameterType="com.base.entity.User">
insert into `user`(`name`,`pwd`) values (#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.base.entity.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>
测试类
public class UserMapperTest {
@Test
public void test01() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectAll();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test02() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void test03() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int demo02 = mapper.insertUser(new User(4, "demo02", "123456"));
sqlSession.commit();
sqlSession.close();
test01();
}
@Test
public void test04() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int newDemo01 = mapper.updateUser(new User(6, "newDemo01", "123456"));
sqlSession.commit();
sqlSession.close();
test01();
}
@Test
public void test05() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteById(8);
sqlSession.commit();
sqlSession.close();
test01();
}
}