MyBatis日常笔记记录03--插入语句以及工具类的编写
mybatis实现插入语句
package org.example; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.example.domain.Student; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestMyBatis { public static void main(String[] args) throws IOException { //访问mybatis读取student数据 //1.定义mybatis主配置文件的名称,从类路径的根开始 String config = "mybatis.xml"; //2.读取这个config表示的文件 InputStream in = Resources.getResourceAsStream(config); //3.创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //4.创建SqlSessionFactory对象 SqlSessionFactory factory = builder.build(in); //5.【重要】获取SqlSession对象,从SqlSessionFactory中获取SqlSession SqlSession sqlSession = factory.openSession(); //6.【重要】指定要执行的sql语句的标识。 sql映射文件中namespace + "." + 标签的id值 String sqlId = "org.example.dao.StudentDao.insertStudent"; //7.执行sql语句,通过sqlId找到语句
student.setId(1003);
student.setName("张飞");
student.setEmail("zhengfei@163.com");
student.setage(21); int nums = sqlSession.insert(sqlId,student);
//mybatis默认不是自动提交事务的,所以在insert, update , delet后要手动提交事务
sqlSession.commit();
//8.输出结果 System.out.println("执行insert的结果:"+nums); //9.关闭SqlSession的对象 sqlSession.close(); } }
说明:1.openSession() :无参数,获取是非自动提交事务的SqlSession对象
2.openSession(boolean) : openSession(true) 获取自动提交事务的SqlSession。
openSession(false) 非自动提交事务的SqlSession对象
工具类
package org.example.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MyBatisUtils { private static SqlSessionFactory factory = null; static { String config = "mybatis.xml"; //需要和你的项目的文件名一致 try { InputStream in = Resources.getResourceAsStream(config); //创建SqlSessionFactory对象,使用SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); } } //获取SqlSession的方法 public static SqlSession getSqlSession(){ SqlSession sqlSession = null; if(factory != null){ sqlSession = factory.openSession(); } return sqlSession; } }