博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于MybatisUtil工具类,完成CURD操作
阅读量:4679 次
发布时间:2019-06-09

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

package loaderman;import java.io.IOException;import java.io.Reader;import java.sql.Connection;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;/** * 工具类 */public class MybatisUtil {    private static ThreadLocal
threadLocal = new ThreadLocal
(); private static SqlSessionFactory sqlSessionFactory; /** * 加载位于src/mybatis.xml配置文件 */ static{ try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 禁止外界通过new方法创建 */ private MybatisUtil(){} /** * 获取SqlSession */ public static SqlSession getSqlSession(){ //从当前线程中获取SqlSession对象 SqlSession sqlSession = threadLocal.get(); //如果SqlSession对象为空 if(sqlSession == null){ //在SqlSessionFactory非空的情况下,获取SqlSession对象 sqlSession = sqlSessionFactory.openSession(); //将SqlSession对象与当前线程绑定在一起 threadLocal.set(sqlSession); } //返回SqlSession对象 return sqlSession; } /** * 关闭SqlSession与当前线程分开 */ public static void closeSqlSession(){ //从当前线程中获取SqlSession对象 SqlSession sqlSession = threadLocal.get(); //如果SqlSession对象非空 if(sqlSession != null){ //关闭SqlSession对象 sqlSession.close(); //分开当前线程与SqlSession对象的关系,目的是让GC尽早回收 threadLocal.remove(); } } /** * 测试 */ public static void main(String[] args) { Connection conn = MybatisUtil.getSqlSession().getConnection(); System.out.println(conn!=null?"连接成功":"连接失败"); }}
package loaderman;/** * 学生 */public class Student {    private Integer id;//编号    private String name;//姓名    private Double sal;//薪水    public Student(){}    public Student(Integer id, String name, Double sal) {        this.id = id;        this.name = name;        this.sal = sal;    }    public Integer getId() {        System.out.println("getId()");        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        System.out.println("getName()");        return name;    }    public void setName(String name) {        this.name = name;    }    public Double getSal() {        System.out.println("getSal()");        return sal;    }    public void setSal(Double sal) {        this.sal = sal;    }}
package loaderman;import java.util.List;import org.apache.ibatis.session.SqlSession;/** * 持久层 * @author AdminTC */public class StudentDao1 {    /**     * 增加学生     */    public void add(Student student) throws Exception{        SqlSession sqlSession = null;        try{            sqlSession = MybatisUtil.getSqlSession();            sqlSession.insert("loaderman.Student.add",student);            sqlSession.commit();        }catch(Exception e){            e.printStackTrace();            sqlSession.rollback();            throw e;        }finally{            MybatisUtil.closeSqlSession();        }    }    /**     * 根据ID查询学生     */    public Student findById(int id) throws Exception{        SqlSession sqlSession = null;        try{            sqlSession = MybatisUtil.getSqlSession();            Student student = sqlSession.selectOne("loaderman.Student.findById",id);            sqlSession.commit();            return student;        }catch(Exception e){            e.printStackTrace();            sqlSession.rollback();            throw e;        }finally{            MybatisUtil.closeSqlSession();        }    }    /**     * 查询所有学生     */    public List
findAll() throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList("loaderman.Student.findAll"); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 更新学生 */ public void update(Student student) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.update("loaderman.Student.update",student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } /** * 删除学生 */ public void delete(Student student) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.delete(Student.class.getName()+".delete",student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception{ StudentDao1 dao = new StudentDao1();// dao.add(new Student(1,"哈哈",7000D));// dao.add(new Student(2,"呵呵",8000D));// dao.add(new Student(3,"班长",9000D));// dao.add(new Student(4,"键状高",10000D));// Student student = dao.findById(4); List
studentList = dao.findAll(); for(Student student : studentList){ System.out.print(student.getId()+":"+student.getName()+":"+student.getSal()); System.out.println(); } //Student student = dao.findById(3); //student.setName("靓班长"); //dao.update(student);// Student student = dao.findById(3);// System.out.print(student.getId()+":"+student.getName()+":"+student.getSal()); //dao.delete(student); }}
package loaderman;import org.apache.ibatis.session.SqlSession;/** * 持久层 */public class StudentDao2 {    /**     * 增加学生     */    public void add(Student student) throws Exception{        SqlSession sqlSession = null;        try{            sqlSession = MybatisUtil.getSqlSession();            sqlSession.insert("loaderman.Student.add",student);            sqlSession.commit();        }catch(Exception e){            e.printStackTrace();            sqlSession.rollback();            throw e;        }finally{            MybatisUtil.closeSqlSession();        }    }    /**     * 根据ID查询学生     */    public Student findById(int id) throws Exception{        SqlSession sqlSession = null;        try{            sqlSession = MybatisUtil.getSqlSession();            Student student = sqlSession.selectOne("loaderman.Student.findById",id);            sqlSession.commit();            return student;        }catch(Exception e){            e.printStackTrace();            sqlSession.rollback();            throw e;        }finally{            MybatisUtil.closeSqlSession();        }    }    public static void main(String[] args) throws Exception{        StudentDao2 dao = new StudentDao2();        //dao.add(new Student(1,"班长",7000D));        Student student = dao.findById(1);        if(student == null){            System.out.println("YES");        }        System.out.println(student.getId()+":"+student.getName()+":"+student.getSal());    }}
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}
insert into students(students_id,students_name,students_sal) values(#{id},#{name},#{sal})

db.properties

mysql.driver=com.mysql.jdbc.Drivermysql.url=jdbc:mysql://127.0.0.1:3306/loadermanmysql.username=rootmysql.password=rootoracle.driver=oracle.jdbc.driver.OracleDriveroracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcloracle.username=scottoracle.password=tiger

 

转载于:https://www.cnblogs.com/loaderman/p/10064414.html

你可能感兴趣的文章
POJ 2823 Sliding Window
查看>>
element-UI el-table二次封装
查看>>
Quartz.net Cron表达式
查看>>
类名.class
查看>>
vue组件
查看>>
Tensorflow without a phd master 1——Jetson nano初体验5
查看>>
[Lua]内存泄漏与垃圾回收
查看>>
linux 多进程绑定问题
查看>>
HTML5语义化标签
查看>>
【Java】基础篇-LinkedList
查看>>
006 输入和输出
查看>>
Python3.5.2中的变量介绍
查看>>
请比较throw 合throws的区别
查看>>
Python3 的列表
查看>>
javaee 第14周
查看>>
iOS上的MapKit
查看>>
「提离职」算正确的加薪姿势么?
查看>>
最简单的C# Windows服务程序
查看>>
Linux下配置VNC
查看>>
hbase权威指南学习笔记--架构--存储
查看>>