基於MybatisUtil工具類,完成CURD操作
阿新 • • 發佈:2018-12-04
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<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); 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方法建立 */ privateMybatisUtil(){} /** * 獲取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<Student> 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<Student> 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()); } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="loaderman.Student"> <resultMap type="loaderman.Student" id="studentMap"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sal" column="sal"/> </resultMap> <!-- 增加學生 --> <insert id="add" parameterType="loaderman.Student"> insert into students(id,name,sal) values(#{id},#{name},#{sal}) </insert> <!-- 根據ID查詢學生 如果引數不是一個實體的話,只是一個普通變數,例如:int,double,String 這裡的#{中間的變數名可以隨便寫},不過提倡就用方法的形參 --> <select id="findById" parameterType="int" resultType="loaderman.Student"> select id,name,sal from students where id = #{id} </select> <!-- 查詢所有學生 理論上resultType要寫List<Student> 但這裡只需書寫List中的型別即可,即只需書寫Student的全路徑名 --> <select id="findAll" resultType="loaderman.Student"> select id,name,sal from students </select> <!-- 更新學生 --> <update id="update" parameterType="loaderman.Student"> update students set name=#{name},sal=#{sal} where id=#{id} </update> <!-- 刪除學生 --> <delete id="delete" parameterType="loaderman.Student"> delete from students where id = #{id} </delete> <!-- <insert id="delete" parameterType="cn.itcast.javaee.mybatis.app09.Student"> delete from students where id = #{id} </insert> --> <!-- 注意:這個insert/update/delete標籤只是一個模板,在做操作時,其實是以SQL語句為核心的 即在做增/刪/時,insert/update/delete標籤可通用, 但做查詢時只能用select標籤 我們提倡什麼操作就用什麼標籤 --> </mapper>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="studentNamespace"> <!-- 當實體屬性與表字段名不相同的時候,必須書寫以下程式碼 當實體屬性與表字段名相同的時候,以下程式碼可選 --> <resultMap type="loaderman.Student" id="studentMap"> <id property="id" column="students_id"/> <result property="name" column="students_name"/> <result property="sal" column="students_sal"/> </resultMap> <!-- 增加學生 --> <insert id="add" parameterType="loaderman.Student"> insert into students(students_id,students_name,students_sal) values(#{id},#{name},#{sal}) </insert> <!-- 根據ID查詢學生 mybatis會將查詢出來的表記錄和studentMap這個id所對應的對映結果相互匹配 --> <select id="findById" parameterType="int" resultMap="studentMap"> select students_id,students_name,students_sal from students where students_id = #{xxxxxxxxxxxxxxxxxx} </select> </mapper>
db.properties
mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://127.0.0.1:3306/loaderman mysql.username=root mysql.password=root oracle.driver=oracle.jdbc.driver.OracleDriver oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl oracle.username=scott oracle.password=tiger
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 載入類路徑下的屬性檔案 -->
<properties resource="db.properties"/>
<!-- 設定類型別名 -->
<typeAliases>
<typeAlias type="loaderman.Student" alias="student"/>
</typeAliases>
<!-- 設定一個預設的連線環境資訊 -->
<environments default="mysql_developer">
<!-- 連線環境資訊,取一個任意唯一的名字 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事務管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用連線池方式來獲取連線 -->
<dataSource type="pooled">
<!-- 配置與資料庫互動的4個必要屬性 -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
<!-- 連線環境資訊,取一個任意唯一的名字 -->
<environment id="oracle_developer">
<!-- mybatis使用jdbc事務管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用連線池方式來獲取連線 -->
<dataSource type="pooled">
<!-- 配置與資料庫互動的4個必要屬性 -->
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</dataSource>
</environment>
</environments>
<!-- 載入對映檔案-->
<mappers>
<mapper resource="loaderman/StudentMapper.xml"/>
</mappers>
</configuration>