myBatis

一,初識mybatis

1.聲明對應表的實體類

package com.mybatis.bean;
public class Student {
    private String id;
    private String name;
    private int age;
    public Student(String id,String name,int age){
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

2.聲明映射文件表StudentMapper.xml

<?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:實體類全路徑名
         id:爲實體類與表的映射取一個唯一的編碼
     -->
    <resultMap type="com.mybatis.bean.Student" id="studentMap">
        <!-- id標籤:映射主鍵屬性
             property:實體類的屬性名
             column:表的字段名
         -->
        <id property="id" column="id"/>

        <!-- result標籤:映射非主鍵的屬性 -->
        <result property="name" column="name"/>

        <result property="age" column="age"/>
    </resultMap>
    <!-- 插入語句 
        parameterType:參數類型
    -->
    <insert id="add" parameterType="com.mybatis.bean.Student">
        insert into student(id,name,age) values(#{id},#{name},#{age});
    </insert>
</mapper>

3.Dao文件

public class StudentDao {

    public void add(Student student){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        sqlSession.insert("studentNameSpace.add",student);
        sqlSession.commit();
    }
}

4.MyBatisUtil文件

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();
        }
    }
}

5.配置mabatis連接數據庫的文件

<?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>
    <environments default="mysql_development">
        <environment id="mysql_development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/> 
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb4"/>    
                <property name="username" value="root"/>    
                <property name="password" value="123"/> 
            </dataSource>
        </environment>

    </environments>

    <mappers>
        <mapper resource="com/mybatis/bean/StudentMapper.xml"></mapper>
    </mappers>
</configuration>

6.測試

public static void main(String[] args) {
        //測試數據庫配置文件是否正確
        Connection conn = MyBatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"連接成功":"連接失敗");
        //測試插入一條數據
        StudentDao dao = new StudentDao();
        dao.add(new Student("0001","daMing",20));
    }

二,myBatist的增刪改查

1.studentMapper.xml文件的配置

<!-- 插入語句 
        parameterType:參數類型
    -->
    <insert id="add" parameterType="com.mybatis.bean.Student">
        insert into student(id,name,age) values(#{id},#{name},#{age});
    </insert>
    <!-- 
        resultMap:解決bean類和表字段不一致導致的映射問題
      -->
     <select id="add" parameterType="int" resultMap="studentMap">
        select s_id,s_name,s_age from student where s_id = #{id};
     </select>
    <!--查詢語句 
        parameterType:請求參數類型
        resultType:返回值類型
     -->
     <select id="findById" parameterType="string" resultType="com.mybatis.bean.Student">
        select id,name,age from student where id = #{id};
     </select>

     <!-- 查詢所有
         如果返回結果爲list,那麼resultType只需要寫list裏面的類型 
      -->
      <select id="findAll" resultType="com.mybatis.bean.Student">
        select id,name,age from student;
     </select>


     <!-- 更新操作 -->

     <update id="update" parameterType="com.mybatis.bean.Student">
        update student set age = #{age},name = #{name} where id = #{id};
     </update>
     <!--刪除-->
     <delete id="deleteById" parameterType="string">
        delete from student where id = #{id};
     </delete>
     <!-- 多參數查詢
        map:封裝多個查詢參數
      -->
     <select id="findByLimit" parameterType="map" resultMap="studentMap">
        select id,name,age from student limit #{start},#{size};
     </select>

2.dao文件

    //添加學生
    public void add(Student student){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        sqlSession.insert("studentNameSpace.add",student);
        sqlSession.commit();
    }
    //根據id查詢學生
    public Student findById(String id){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            Student student = sqlSession.selectOne("studentNameSpace.findById",id);
            sqlSession.commit();
            return student;
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.toString());
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession();
        }
        return null;
    }
    //查詢多個學生
    public List<Student> findAll(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            List<Student> students = sqlSession.selectList("studentNameSpace.findAll");
            sqlSession.commit();
            return students;
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.toString());
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession();
        }
        return null;
    }
    //更新學生
    public void update(Student student){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            sqlSession.update("studentNameSpace.update",student);
            sqlSession.commit();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.toString());
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }
    //刪除學生
    public void deleteById(String id){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            sqlSession.delete("studentNameSpace.deleteById",id);
            sqlSession.commit();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.toString());
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }
    //分頁查詢
    public List<Student> findByLimit(int start,int size){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            Map<String,Integer> map = new HashMap<String, Integer>();
            map.put("start", start);
            map.put("size", size);
            List<Student> students = sqlSession.selectList("studentNameSpace.findByLimit",map);
            sqlSession.commit();
            return students;
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.toString());
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession();
        }
        return null;
    }

3.測試


        StudentDao dao = new StudentDao();
//      dao.add(new Student("0002","xiaoLong",10));
//      dao.add(new Student("0003","哈哈",10));
//      dao.add(new Student("0004","呵呵",10));

//      Student student = dao.findById("0001");
//      System.out.println(student.getName()+":"+student.getAge());

        /**
        List<Student> students = dao.findAll();
        for (Student student : students) {
            System.out.println(student.getName()+":"+student.getAge());
        }*/

//      dao.update(new Student("0003","hehe",10));

        dao.deleteById("0004");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章