- Mybatis 实现单表的crud操作,只需要添加对应的 sql 映射即可。
<mapper namespace="cn.wh.mapper.RoleMapper"> <!-- 根据id查询 --> <select id="findById" parameterType="int" resultType="cn.wh.vo.Role"> select * from t_role where id = #{id} </select> <!-- 添加 添加成功,将返回受影响行数 占位符中 是自定义类型的属性名 自定义要提供get方法 useGeneratedKeys 设置为true,表示主键自增 --> <insert id="save" useGeneratedKeys="true" parameterType="cn.wh.vo.Role"> insert into t_role(name) values(#{name}) </insert> <!-- 删除数据 --> <delete id="delete" parameterType="int"> delete from t_role where id=#{id} </delete> <!-- 更新 --> <update id="update" parameterType="cn.wh.vo.Role"> update t_role set name=#{name} where id=#{id} </update> <!-- 查询所有 --> <select id="findAll" resultType="cn.wh.vo.Role"> select * from t_role </select> </mapper>
- 工具类:
/** * Mybatis的工具类 */ public class MybatisUtil { private static SqlSessionFactory sessionFactory=null; private static ThreadLocal<SqlSession> session = new ThreadLocal<SqlSession>(); static{ try { Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } /** * 获取SQLSession * @return */ public static SqlSession getSqlSession(){ if(session.get()==null){ //如果设置true,那么获得session时,告知 自动提交事务 session.set(sessionFactory.openSession(true)); } return session.get(); } /** * 释放资源 */ public static void close(){ if(session.get()!=null){ session.get().close(); session.set(null); } } }
- 测试类:
public class RoleDaoTest { private SqlSession session=null; @Before public void setUp(){ session = MybatisUtil.getSqlSession(); } @After public void tearDown(){ MybatisUtil.close(); } //查询所有 @Test public void testFindAll(){ List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findAll"); for(Role role:list){ System.out.println(role.getId()+"----"+role.getName()); } } //保存数据 @Test public void testSave(){ Role role = new Role(); role.setName("黄金会员"); int result = session.insert("cn.wh.mapper.RoleMapper.save",role); //session.commit();手动提交事务,如果不手动提交事务,那么在获取session时,设置自动提交事务 if(result>0){ System.out.println("保存成功"); } } //更新数据 @Test public void testUpdate(){ Role role = (Role)session.selectOne("cn.wh.mapper.RoleMapper.findById", 4); role.setName("砖石会员"); int result = session.update("cn.wh.mapper.RoleMapper.update",role); //session.commit();手动提交事务,如果不手动提交事务,那么在获取session时,设置自动提交事务 if(result>0){ System.out.println("修改成功"); } } //删除数据 @Test public void testDelete(){ int result = session.delete("cn.wh.mapper.RoleMapper.delete",4); //session.commit();手动提交事务,如果不手动提交事务,那么在获取session时,设置自动提交事务 if(result>0){ System.out.println("删除成功"); } } }