博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybaits入门
阅读量:6577 次
发布时间:2019-06-24

本文共 10797 字,大约阅读时间需要 35 分钟。

1.回顾jdbc开发 orm概述

  orm是一种解决持久层对象关系映射的规则,而不是一种具体技术。jdbc/dbutils/springdao,hibernate/springorm,mybaits同属于ORM解决方案之一。

2.mybaits

  mybatis基于jdbc,兼顾难易度和速度。

3.mybatis快速入门

  导入lib包

  在src目录下配置mybatis.cfg.xml

  实体类

  配置映射文件StudentMapper.xml

INSERT INTO students(id,name,sal) values(1,"haha",7000)
INSERT INTO students(id,name,sal) values(#{id},#{name},#{sal})

  获取连接

public class MybatisUtil {    private static ThreadLocal
threadLocal = new ThreadLocal
(); private static SqlSessionFactory sqlSessionFactory; //加载位于mybatis.xml配置文件 static{ try { Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { throw new RuntimeException(e); } } public static SqlSession getSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession == null){ sqlSession = sqlSessionFactory.openSession(); //将session与当前线程绑定在一起 threadLocal.set(sqlSession); } return sqlSession; } //关闭当前sqlsession,与当前线程分离 public static void closeSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession!=null){ sqlSession.close(); //分离,目的是为了尽早垃圾回收 threadLocal.remove(); } }}

  dao

public void add1() throws Exception{        SqlSession sqlSession = null;        try {            sqlSession = MybatisUtil.getSqlSession();            //默认事务开始,读取StudentMapper.xml映射文件中的sql语句            int i = sqlSession.insert("studentNamespace.add1");            sqlSession.commit();            System.out.println("本次操作影响了"+i+"行");        }catch (Exception e){            sqlSession.rollback();            throw e;        }finally {            MybatisUtil.closeSqlSession();        }    }    public void add2(Student student) throws Exception{        SqlSession sqlSession = null;        try {            sqlSession = MybatisUtil.getSqlSession();            //默认事务开始,读取StudentMapper.xml映射文件中的sql语句            sqlSession.insert("studentNamespace.add2",student);            sqlSession.commit();        }catch (Exception e){            sqlSession.rollback();            throw e;        }finally {            MybatisUtil.closeSqlSession();        }    }

4.mybatis工作流程

1)通过Reader对象读取src目录下的mybatis.cfg.xml配置文件(该文本的位置和名字可任意)

2)通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象

3)从当前线程中获取SqlSession对象

4)事务开始,在mybatis中默认

5)通过SqlSession对象读取StudentMapper.xml映射文件中的操作编号,从而读取sql语句

6)事务提交,必写

7)关闭SqlSession对象,并且分开当前线程与SqlSession对象,让GC尽早回收

5基于MybatisUtil工具类,完成CURD操作

  映射配置文件

INSERT INTO students(id,name, sal) VALUES(#{id},#{name},#{sal})
UPDATE students SET name=#{name},sal=#{sal} WHERE id=#{id}
DELETE FROM students WHERE ID=#{id}

  dao

public void add(Student student) throws Exception{        SqlSession sqlSession = null;        try {            sqlSession = MybatisUtil.getSqlSession();            sqlSession.insert(Student.class.getName()+".add",student);            sqlSession.commit();        }catch (Exception e){            sqlSession.rollback();            throw e;        }finally {            MybatisUtil.closeSqlSession();        }    }    private Student findById(int id) {        Student student= null;        SqlSession sqlSession = null;        try {            sqlSession = MybatisUtil.getSqlSession();            student = sqlSession.selectOne(Student.class.getName() + ".findById", id);            sqlSession.commit();        }catch (Exception e){            sqlSession.rollback();            throw e;        }finally {            MybatisUtil.closeSqlSession();        }        return student;    }    private List
findAll() { List
students = new ArrayList<>(); SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); students = sqlSession.selectList(Student.class.getName() + ".findAll"); sqlSession.commit(); }catch (Exception e){ sqlSession.rollback(); throw e; }finally { MybatisUtil.closeSqlSession(); } return students; } private void update(Student student) { SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); sqlSession.update(Student.class.getName()+".update",student); sqlSession.commit(); }catch (Exception e){ sqlSession.rollback(); throw e; }finally { MybatisUtil.closeSqlSession(); } } private void delete(Student student) { SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); sqlSession.delete(Student.class.getName()+".delete",student); sqlSession.commit(); }catch (Exception e){ sqlSession.rollback(); throw e; }finally { MybatisUtil.closeSqlSession(); } }

6.分页查询(mysql,oracle)

  映射配置文件

mysql

oracle

  dao

public List
findAllWithFy(int start,int size){ List
students = new ArrayList<>(); SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); Map
map = new LinkedHashMap<>(); map.put("start",start); map.put("size",size); students = sqlSession.selectList(Student.class.getName()+".findAllWithFy",map); sqlSession.commit(); return students; }catch (Exception e){ sqlSession.rollback(); throw e; }finally { MybatisUtil.closeSqlSession(); } }

7.动态SQL操作之查询

  映射配置文件

  dao

public List
findAll(Integer id ,String name,Double sal){ List
students = new ArrayList<>(); SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); Map
map = new LinkedHashMap<>(); map.put("pid",id); map.put("pname",name); map.put("psal",sal); students = sqlSession.selectList(Student.class.getName()+".findAll",map); sqlSession.commit(); return students; }catch (Exception e){ sqlSession.rollback(); throw new RuntimeException(e); }finally { MybatisUtil.closeSqlSession(); } }

8.动态SQL操作之更新

  映射配置文件

UPDATE STUDENTS
name = #{pname},
sal = #{psal},
WHERE id = #{pid}

  dao

public void update(Student student){        SqlSession sqlSession = null;        try {            sqlSession = MybatisUtil.getSqlSession();            Map
map = new LinkedHashMap<>(); map.put("pid",student.getId()); map.put("pname",student.getName()); map.put("psal",student.getSal()); sqlSession.update(Student.class.getName()+".update",map); sqlSession.commit(); }catch (Exception e){ sqlSession.rollback(); throw new RuntimeException(e); }finally { MybatisUtil.closeSqlSession(); } }

9.动态SQL操作之删除

  映射配置文件

DELETE FROM students WHERE ID IN
#{ids}

  dao

public void deleteAll(int... ids)throws Exception{        SqlSession sqlSession = null;        try {            sqlSession = MybatisUtil.getSqlSession();            sqlSession.delete(Student.class.getName()+".deleteAll",ids);            sqlSession.commit();        }catch (Exception e){            sqlSession.rollback();            throw new RuntimeException(e);        }finally {            MybatisUtil.closeSqlSession();        }    }

10.动态SQL操作之插入

  映射配置文件

id,
name,
sal,
#{id},
#{name},
#{sal},
INSERT INTO students(
) values (
)

  dao

public void deleteList(List
ids)throws Exception{ SqlSession sqlSession = null; try { sqlSession = MybatisUtil.getSqlSession(); sqlSession.delete(Student.class.getName()+".deleteList",ids); sqlSession.commit(); }catch (Exception e){ sqlSession.rollback(); throw new RuntimeException(e); }finally { MybatisUtil.closeSqlSession(); } }

 

转载于:https://www.cnblogs.com/juaner767/p/5750700.html

你可能感兴趣的文章
delete select 表
查看>>
2. composer的简单操作
查看>>
maven setting
查看>>
二叉树中和为某一值的路径
查看>>
Android 应用语言设置的实现
查看>>
SqlSessionTemplate探究
查看>>
nagios监控插件 nagios_oracle_health+check_linux_stats.pl
查看>>
linux下用mail发送邮件
查看>>
linux入门学习分享系列之一
查看>>
深度解析Istio系列之安全模块篇
查看>>
配置管理小报111016:在bugzilla中输入新的bug,点"确认"时提示"请替这个bug输入一句摘要"?...
查看>>
Linux 系统 审计
查看>>
uPortal 5.2.1特性及定制清单
查看>>
基于TP5的微信的公众号获取登录用户信息
查看>>
大数据系列8:Sqoop – HADOOP和RDBMS数据交换
查看>>
2011年国外最受欢迎的15个科学网站
查看>>
如何做一名优秀的程序员?——职业生涯规划
查看>>
Java NIO系列教程(一) Java NIO 概述
查看>>
uliweb中ORM关系属性初始化延迟处理调整
查看>>
win下执行exec()权限问题
查看>>