基於MybatisUtil工具類,完成CURD操作


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方法創建
     */
    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<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.loaderman.javaee.mybatis.app.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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM