接着上一篇博客,基于上次的开发环境此篇文章我们通过mybatis对t_group表进行CRUD操作
一、使用MyBatis对t_group表执行CRUD操作——基于XML的实现
1、在sql映射文件GroupMapper.xml添加以下内容
insert into t_group (group_name,description) values (#{groupName},#{description})
2、使用Junit编写单元测试用例
2.1添加操作
public class TestMyBatis2 extends TestCase { private SqlSessionFactory sqlSessionFactory; private Reader reader; @Override protected void setUp() throws Exception { try { reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } public void testAddGroup(){ SqlSession session = null; try{ session = sqlSessionFactory.openSession(); String statement = "com.zlt.mybatis.model.Group.addGroup"; Group data = new Group(); data.setGroupName("游侠组"); data.setDescription("游便大江南北"); session.insert(statement,data); }finally{ if(null != session) session.close(); } }
运行程序,没有错误,但是表中并没有添加此记录,造成此现象说明mybatis进行CRU操作时默认的是手动提交事务.
在session.insert(statement,data);添加以下内容
session.commit();//手动提交事务
在sql映射文件GroupMapper.xml添加以下内容
update t_group set group_name =#{groupName},description=#{description} where id = #{id}
单元测试:
public void testUpdateGroup(){ SqlSession session = null; try{ session = sqlSessionFactory.openSession(); String statement = "com.zlt.mybatis.model.Group.updateGroup"; Group data = new Group(); data.setId(3); data.setGroupName("特工组"); data.setDescription("进行特殊任务"); session.update(statement,data); session.commit(); }finally{ if(null != session) session.close(); } }
在sql映射文件GroupMapper.xml文件中添加以下内容
delete from t_group where id =#{id}
单元测试
public void testDeleteGroup(){ SqlSession session = null; try{ session = sqlSessionFactory.openSession(); String statement = "com.zlt.mybatis.model.Group.deleteGroupByID"; Group data = new Group(); data.setId(3); data.setGroupName("特工组"); data.setDescription("进行特殊、高效的任务"); session.update(statement,data); session.commit(); }finally{ if(null != session) session.close(); } }
在sql映射文件GroupMapper.xml添加以下内容
单元测试:
public void testQueryAllGroup(){ SqlSession session = null; try{ session = sqlSessionFactory.openSession(); String statement = "com.zlt.mybatis.model.Group.selectGroups"; Listgroups = session.selectList(statement); for (Group g : groups) { System.out.println("ID:" + g.getId() + "name:" + g.getGroupName() + "description:" + g.getDescription()); } }finally{ if(null != session) session.close(); } }
运行结果: