MyBatis crud操作
Posted 纸上得来终觉浅,绝知此事要躬行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis crud操作相关的知识,希望对你有一定的参考价值。
Test2.java
package com.mycom.mybatis_1.crud; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.Test; import com.mycom.mybatis_1.bean.User; import com.mycom.mybatis_1.util.MyBatisUtils; public class Test2 { @Test public void testAdd(){ SqlSessionFactory factory = MyBatisUtils.getFactory(); //默认是手动提交的 SqlSession session = factory.openSession(); String statement = "com.mycom.mybatis_1.bean.userMapper.addUser"; int ins = session.insert(statement, new User(-1,"KK",23, "男")); //提交 session.commit(); session.close(); System.out.println(ins); } @Test public void testUpd(){ SqlSessionFactory factory = MyBatisUtils.getFactory(); //默认是手动提交的 // SqlSession session = factory.openSession(); // // String statement = "com.mycom.mybatis_1.bean.userMapper.updUser"; // int ins = session.update(statement, new User(4,"KK444",27)); // //提交 // session.commit(); //默认是自动提交的 SqlSession session = factory.openSession(true); String statement = "com.mycom.mybatis_1.bean.userMapper.updUser"; int upd = session.update(statement, new User(4,"KK444",28, "男")); session.close(); System.out.println(upd); } @Test public void testDel(){ SqlSessionFactory factory = MyBatisUtils.getFactory(); //默认是自动提交的 SqlSession session = factory.openSession(true); String statement = "com.mycom.mybatis_1.bean.userMapper.delUser"; int del = session.delete(statement, 4); session.close(); System.out.println(del); } @Test public void testgetUser(){ SqlSessionFactory factory = MyBatisUtils.getFactory(); //默认是自动提交的 SqlSession session = factory.openSession(true); String statement = "com.mycom.mybatis_1.bean.userMapper.getUser"; User user = session.selectOne(statement, 1); session.close(); System.out.println(user); } @Test public void testgetAll(){ SqlSessionFactory factory = MyBatisUtils.getFactory(); //默认是自动提交的 SqlSession session = factory.openSession(true); String statement = "com.mycom.mybatis_1.bean.userMapper.getAllUsers"; List<User> list = session.selectList(statement); session.close(); System.out.println(list); } }
MyBatisUtils.java
package com.mycom.mybatis_1.util; import java.io.InputStream; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.mycom.mybatis_1.select.Test1; public class MyBatisUtils { public static SqlSessionFactory getFactory(){ String resource = "conf.xml"; InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); return factory; } }
以上是关于MyBatis crud操作的主要内容,如果未能解决你的问题,请参考以下文章
mybatis实现CRUD操作和优化代码及调试(mysql数据库)
MyBatis学习总结——使用MyBatis对表执行CRUD操作