1. 程式人生 > >5.mybatis的CURD操作

5.mybatis的CURD操作

bind org 設置 bold final del alias println 1.0

5.mybatis的CURD操作

1.導包(使用maven創建工程,導包只需要配置pom.xml即可,此處導入jackson是為測試查詢打印結果)

<?xml version="1.0" encoding="UTF-8"?>

<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>jar</packaging> <name>Mybatis01</name> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <groupId>Mybatis01</groupId> <artifactId>Mybatis01</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--junit依賴--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!--mybatis依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!--jackson2.1.0依賴--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> </dependency> <!--mysql驅動依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.43</version> </dependency> </dependencies> </project>

2.配置mybatis核心文件mybatis.xml

<?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"></properties>

    <settings>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="useColumnLabel" value="true"/>
    </settings>

    <!-- 配置對應的javabean的路徑,應用別名-->
    <typeAliases>
      <typeAlias alias="Person" type="entity.Person"/>
    </typeAliases>

    <!-- 配置數據庫的連接信息 -->
    <environments default
="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <!--使用連接池方式獲取連接--> <dataSource type="POOLED"> <!--配置數據庫連接的信息--> <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> </environments> <!-- 配置映射類xml文件的路徑 --> <mappers> <mapper resource="mappers/PersonMapper.xml"/> </mappers> </configuration>

3.創建sqlSession的工具類

package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * 工具類
 * Created by Administrator on 2017/8/6.
 */
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
     *
     * @return sqlSession
     */
    public static SqlSession getSqlSession() {
        //從當前線程中獲取sqlsession對象
        SqlSession sqlSession = threadLocal.get();
        //如果sqlSession對象為空則從sqlSessionFacety中從新獲取
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            //將sqlSession與當前線程進行綁定
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 關閉SqlSession與當前線程分開
     */
    public static void closeSqlSession() {
        //從當前線程中獲取sqlSession
        SqlSession sqlSession = threadLocal.get();
        //如果sqlSession不為空則關閉它,並且分離線程:如不分離線程,則會數據庫操作會越來越慢
        if (sqlSession != null) {
            sqlSession.close();
            threadLocal.remove();//讓GC盡快回收,釋放內存
        }
    }
}

3.1測試工具類

import util.MybatisUtil;

import java.sql.Connection;

/**
 * Created by Administrator on 2017/8/6.
 * 測試獲取qlSession
 */
public class test1 {
    public static void main(String[] args) {
        Connection conn = MybatisUtil.getSqlSession().getConnection();
        System.out.println(conn != null?"連接成功!":"連接失敗!");
    }
}

4.創建javabean,註意:一定要寫無參的構造函數,

防止後面要使用帶參的構造函數會覆蓋,會出現mybatis無法創建JavaBean導致查詢失敗

5.配置Mapper.xml文件,並將配置文件的路徑配置加到mybatis.xml中

package entity;

/**
 * Created by Administrator on 2017/8/5.
 * Person的實體類
 */
public class Person {
    private Integer id;
    private String name;
    private Integer age;
    private String remark;

    /*mybatis對應的javabean中必須得有一個默認無參的構造函數,
    * 如果我們自定義了有參的構造函數時,會將其覆蓋,執行查詢時,
    *mybatis無法將參數存入,所以要將其顯性的寫出來
    */
    public Person () {

    }

    //全參數的構造函數
    public Person (Integer id, String name, Integer age,String  remark) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.remark = remark;
    }

    //不含id的構造函數
    public Person (String name, Integer age,String  remark) {
        super();
        this.name = name;
        this.age = age;
        this.remark = remark;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
}

6.書寫JavaBean的Dao類

package dao;

import entity.Person;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.session.SqlSession;
import util.MybatisUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/6.
 */
public class PersonDao {
    //*****************************************急速入門********************************************
    //增加一條信息
    public Integer addPerson (Person person){
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Integer i = sqlSession.insert("Person.addPerson",person);
            sqlSession.commit();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    //根據id刪除人員信息
    public Integer deletePersonById (int id) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Integer i = sqlSession.delete("Person.deletePersonById",id);
            sqlSession.commit();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    //根據id修改一個人的信息
   public Integer updatePersonById (Person person) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Integer i = sqlSession.update("Person.updatePersonById",person);
            sqlSession.commit();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    //通過id獲取person
    public Person getPersonById (int id) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Person person = sqlSession.selectOne("Person.getPersonById",id);
            return person;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    //根據分頁查詢
    public List<Person> getPersonList (Integer start, Integer limit) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("start", start);
            map.put("limit", limit);
            List<Person> li = sqlSession.selectList("Person.getPersonList",map);
            return li;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    //*****************************************動態CRUD,mybatis相較於hibernate的優勢********************************************
    /**
     * 根據三個條件中的任意一個或多個進行動態查詢
     * @param name
     * @param age
     * @param remark
     * @return
     */
    public List<Person> getPersonLList2 (String name, Integer age, String remark) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name",name);
            map.put("age",age);
            map.put("remark",remark);
            List<Person> li = sqlSession.selectList("Person.getPersonList2",map);
            return li;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<Person>();
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    public Integer updatePerson1 (Person person) {
        try{
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Integer i = sqlSession.update("Person.updatePerson1",person);
            sqlSession.commit();
            return i;
        }catch (Exception e) {
            e.printStackTrace();
            return -1;
        }finally {
           MybatisUtil.closeSqlSession();
        }
    }
    public Integer deletePerson1 (int... id) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Integer i = sqlSession.delete("Person.deldetPerson1",id);
            sqlSession.commit();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
    public Integer addPerson1 (Person person) {
        try {
            SqlSession sqlSession = MybatisUtil.getSqlSession();
             Integer i = sqlSession.insert("Person.addPerson1",person);
             sqlSession.commit();
             return i;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }finally {
            MybatisUtil.closeSqlSession();
        }
    }
}

7.測試(其他測試類以此類推)

import util.MybatisUtil;

import java.sql.Connection;

/**
 * Created by Administrator on 2017/8/6.
 * 測試獲取qlSession
 */
public class test1 {
    public static void main(String[] args) {
        Connection conn = MybatisUtil.getSqlSession().getConnection();
        System.out.println(conn != null?"連接成功!":"連接失敗!");
    }
}

8.項目文件結構

技術分享

package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
* 工具類
* Created by Administrator on 2017/8/6.
*/
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
*
* @return sqlSession
*/
public static SqlSession getSqlSession() {
//從當前線程中獲取sqlsession對象
SqlSession sqlSession = threadLocal.get();
//如果sqlSession對象為空則從sqlSessionFacety中從新獲取
if (sqlSession == null) {
sqlSession = sqlSessionFactory.openSession();
//將sqlSession與當前線程進行綁定
threadLocal.set(sqlSession);
}
return sqlSession;
}

/**
* 關閉SqlSession與當前線程分開
*/
public static void closeSqlSession() {
//從當前線程中獲取sqlSession
SqlSession sqlSession = threadLocal.get();
//如果sqlSession不為空則關閉它,並且分離線程:如不分離線程,則會數據庫操作會越來越慢
if (sqlSession != null) {
sqlSession.close();
threadLocal.remove();//讓GC盡快回收,釋放內存
}
}
}

5.mybatis的CURD操作