insert into tb_students(stu_num, stu_name, stu_mybatis 设">
赞
踩
目录
mapper中在添加数据时返回id值,useGeneratedKeys="true"表示需要回填生成的主键(即返回数据),keyProperty="stuID"表示回填的字段赋值给的属性
<insert id="insertStudent" parameterType="entity.Student" useGeneratedKeys="true" keyProperty="stuID"> insert into tb_students(stu_num, stu_name, stu_gender, stu_age) values (#{stuNum}, #{stuName}, #{stuGender}, #{stuAge}) </insert>
测试: 虽然添加时id=0,但是添加后自动将生成的主键赋值给stuID属性,而不是0
- public void insertStudent() {
- try {
- //加载mybatis配置文件
- InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
-
- SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
- //会话工厂
- SqlSessionFactory factory = builder.build(is);
-
- //与数据库的连接即mybatis的操作对象,会话
- SqlSession sqlSession = factory.openSession();
-
- StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
-
- Student student=new Student(0,"Y8025","悟空","女",20);
- int i=studentDAO.insertStudent(student);
- // 手动提交事务
- sqlSession.commit();
- if (i==1){
- System.out.println("添加成功");
- System.out.println(student);
- }else {
- System.out.println("添加失败");
- }
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- public class mybatisUtils {
- private static SqlSessionFactory factory;
- private static final ThreadLocal<SqlSession> local=new ThreadLocal<>();
-
- static {
- try {
- //加载mybatis配置文件
- InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
-
- SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
- //会话工厂
- factory = builder.build(is);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public static SqlSessionFactory getFactory(){
- return factory;
- }
-
- public static SqlSession getSqlSession(boolean isAutoCommit){
- SqlSession sqlSession=local.get();
- if (sqlSession==null){
- sqlSession= factory.openSession(isAutoCommit);
- local.set(sqlSession);
- }
- return sqlSession;
- }
-
- public static <T>T getMapper(Class<T> c){
- SqlSession sqlSession=getSqlSession(true);
- return sqlSession.getMapper(c);
- }
- }
SqlSession对象
- 通过getMapper(DAO.class)方法获取mapper(DAO接口的实例)
- 事务管理
SqlSession sqlSession = factory.openSession();创建SqlSession对象如果不声明默认为false非自动提交
- 每获取SqlSession对象时,就默认开启了事务,然后进行操作
- 操作完成后需要手动提交sqlSession.commit();
- 在catch中添加sqlSession.rollback();,出现异常回滚
- public void insertStudent() {
-
- //与数据库的连接即mybatis的操作对象,会话
- SqlSession sqlSession = mybatisUtils.getSqlSession();
-
- try {
- StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
-
- Student student=new Student(0,"Y8025","悟空","女",20);
- int i=studentDAO.insertStudent(student);
- //手动提交事务
- sqlSession.commit();
- if (i==1){
- System.out.println("添加成功");
- System.out.println(student);
- }else {
- System.out.println("添加失败");
- }
- } catch (Exception e) {
- sqlSession.rollback();
- e.printStackTrace();
- }
-
- }
SqlSession sqlSession = factory.openSession(true);创建SqlSession对象声明为true自动提交
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。