mybatis的Helloworld

mybatis筆記

1.mybatis的第一個helloworld

1建數據表

使用mysql數據庫

DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `last_name` varchar(255) DEFAULT NULL,
 `gender` char(1) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1', 'sujinran', '女', '[email protected]');


2導maven依賴包

在pom.xml中導入mybatis需要的依賴包

  <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!--日誌-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

mybatis的映射文件找不到解決方法如下:

 <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
        <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>

3javaBean類

com.demo.bean.Employee 實體類

package com.demo.bean;
    public class Employee {
        private Integer id; //編號
        private String lastName; //姓名
        private String email; //郵箱
        private String gender; //性別
        public Employee(Integer id, String lastName, String email, String gender) {
            this. id = id;
            this. lastName = lastName;
            this. email = email;
            this. gender = gender;
        }
        public Employee() {
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this. id = id;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this. lastName = lastName;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this. email = email;
        }
        public String getGender() {
            return gender;
        }
        public void setGender(String gender) {
            this. gender = gender;
        }
        @Override
        public String toString() {
            return "Employee [id=" + id + ", lastName=" + lastName + ", email="
                    + email + ", gender=" + gender + "]";
        }
    }

4mybatis 配置文件

mybatis-config.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>
    <!--
    1、 mybatis可以使用properties來引入外部properties配置文件的內容;
    resource:引入類路徑下的資源
    url:引入網絡路徑或者磁盤路徑下的資源
    -->
    <properties resource="dbconfig.properties"></properties>
    <!--
    2、 settings包含很多重要的設置項
    setting:用來設置每一個設置項
    name:設置項名
    value:設置項取值
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 3、 typeAliases:別名處理器:可以爲我們的java類型起別名
    別名不區分大小寫
    -->
    <typeAliases>
        <!-- 1、 typeAlias:爲某個java類型起別名
        type:指定要起別名的類型全類名;默認別名就是類名小寫; employee
        alias:指定新的別名
        -->
        <!-- <typeAlias type="com.atguigu.mybatis.bean.Employee" alias="emp"/> -->
        <!-- 2、 package:爲某個包下的所有類批量起別名
        name:指定包名(爲當前包以及下面所有的後代包的每一個類都起一個默認別名
       (類名小寫),)
        -->
        <package name="com.demo.bean"/>
        <!-- 3、批量起別名的情況下,使用@Alias註解爲某個類型指定新的別名 -->
    </typeAliases>
    <!--
    4、 environments:環境們, mybatis可以配置多種環境 ,default指定使用某種環境。可以
   達到快速切換環境。
    environment:配置一個具體的環境信息;必須有兩個標籤; id代表當前環境的唯一標識
    transactionManager:事務管理器;
    type:事務管理器的類
   型;JDBC(JdbcTransactionFactory)|MANAGED(ManagedTransactionFactory)
    自定義事務管理器:實現TransactionFactory接口.type指定爲全類名
    dataSource:數據源;
    type:數據源類型;UNPOOLED(UnpooledDataSourceFactory)
    |POOLED(PooledDataSourceFactory)
    |JNDI(JndiDataSourceFactory)
    自定義數據源:實現DataSourceFactory接口, type是全類名
    -->
    <environments default="dev_mysql">
        <environment id="dev_mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 5、 databaseIdProvider:支持多數據庫廠商的;
    type="DB_VENDOR": VendorDatabaseIdProvider
    作用就是得到數據庫廠商的標識(驅動getDatabaseProductName()), mybatis就能根據
   數據庫廠商標識來執行不同的sql;
    MySQL, Oracle, SQL Server,xxxx
    -->
    <databaseIdProvider type="DB_VENDOR">
        <!-- 爲不同的數據庫廠商起別名 -->
        <property name="MySQL" value="mysql"/>
    </databaseIdProvider>
    <!-- 將我們寫好的sql映射文件(EmployeeMapper.xml)一定要註冊到全局配置文件(mybatisconfig.xml)中 -->
    <!-- 6、 mappers:將sql映射註冊到全局配置中 -->
    <mappers>
        <!--
        mapper:註冊一個sql映射
        註冊配置文件
        resource:引用類路徑下的sql映射文件
        mybatis/mapper/EmployeeMapper.xml
        url:引用網路路徑或者磁盤路徑下的sql映射文件
        file:///var/mappers/AuthorMapper.xml
        註冊接口
        class:引用(註冊)接口,
        1、有sql映射文件,映射文件名必須和接口同名,並且放在與接口同一目錄
       下;
        2、沒有sql映射文件,所有的sql都是利用註解寫在接口上;
        推薦:
        比較重要的,複雜的Dao接口我們來寫sql映射文件
        不重要,簡單的Dao接口爲了開發快速可以使用註解;
        -->
        <!--註冊xml-->
        <!-- <mapper resource="mybatis/mapper/EmployeeMapper.xml"/> -->
        <!--註冊接口:必須接口和映射文件同名同包-->
        <!-- <mapper class="com.atguigu.mybatis.dao.EmployeeMapperAnnotation"/> -->
        <!-- 批量註冊:必須接口和映射文件同名同包 -->
        <package name="com.demo.dao"/>
    </mappers>
</configuration>

5數據庫配置文件

dbconfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456

6mapper接口及映射文件

com.demo.dao.EmployeeMapper

package com.demo.dao;

import com.demo.bean.Employee;

public interface EmployeeMapper {
    public Employee getEmpById(Integer id); //查詢

    public Long addEmp(Employee employee); //增加

    public boolean updateEmp(Employee employee); //更新

    public void deleteEmpById(Integer id); //刪除
}

com/demo/dao/EmployeeMapper.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="com.demo.dao.EmployeeMapper">
    <!--
    public Employee getEmpById(Integer id);
    namespace:名稱空間;指定爲接口的全類名
    id:唯一標識
    resultType:返回值類型
    #{id}:從傳遞過來的參數中取出id值
    last_name lastName :起別名
    -->
    <select id="getEmpById" resultType="com.demo.bean.Employee">
        select id,last_name,email,gender from tbl_employee where id = #{id}
    </select>
    <!--
   public void addEmp(Employee employee);
    parameterType:參數類型,可以省略,
   獲取自增主鍵的值:
    mysql支持自增主鍵,自增主鍵值的獲取, mybatis也是利用statement.getGenreatedKeys();
    useGeneratedKeys="true";使用自增主鍵獲取主鍵值策略
    keyProperty;指定對應的主鍵屬性,也就是mybatis獲取到主鍵值以後,將這個值封裝給
   javaBean的哪個屬性
   -->
    <insert id="addEmp" parameterType="com.demo.bean.Employee"
            useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
        insert into tbl_employee(last_name,email,gender)
        values(#{lastName},#{email},#{gender})
    </insert>
    <!-- public void updateEmp(Employee employee); -->
    <update id="updateEmp">
        update tbl_employee
        set last_name=#{lastName},email=#{email},gender=#{gender}
        where id=#{id}
    </update>
    <!-- public void deleteEmpById(Integer id); -->
    <delete id="deleteEmpById">
        delete from tbl_employee where id=#{id}
    </delete>
</mapper>

7測試

MyBatisTest

import com.demo.bean.Employee;
import com.demo.dao.EmployeeMapper;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 1、根據xml配置文件(全局配置文件)創建一個SqlSessionFactory對象 有數據源一些運行
     * 環境信息
     * 2、 sql映射文件;配置了每一個sql,以及sql的封裝規則等。
     * 3、將sql映射文件註冊在全局配置文件中
     * 4、寫代碼:
     * 1)、根據全局配置文件得到SqlSessionFactory;
     * 2)、使用sqlSession工廠,獲取到sqlSession對象使用他來執行增刪改查
     * 一個sqlSession就是代表和數據庫的一次會話,用完關閉
     * 3)、使用sql的唯一標誌來告訴MyBatis執行哪個sql。 sql都是保存在sql映射文件中的。
     *
     * @throws IOException
     */
    //************************************************************************************
//                                  查詢測試
    //************************************************************************************
    @Test
    public void test01() throws IOException {
        // 1、獲取sqlSessionFactory對象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        // 2、獲取sqlSession對象
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            // 3、獲取接口的實現類對象
            //會爲接口自動的創建一個代理對象,代理對象去執行增刪改查方法
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            Employee employee = mapper.getEmpById(1);
            System.out.println(mapper.getClass());
            System.out.println(employee);
        } finally {
            openSession.close();
        }
    }

    /**
     * 測試增刪改
     * 1、 mybatis允許增刪改直接定義以下類型返回值
     * Integer、 Long、 Boolean、 void
     * 2、我們需要手動提交數據
     * sqlSessionFactory.openSession();===》手動提交
     * sqlSessionFactory.openSession(true);===》自動提交
     *
     * @throws IOException
     */

    //************************************************************************************
//                                  添加測試
    //************************************************************************************
    @Test
    public void test02() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //1、獲取到的SqlSession不會自動提交數據
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            /**
             * 測試添加
             */
            Employee employee = new Employee(null, "jerry4", null, "1");
            mapper.addEmp(employee);
            System.out.println(employee.getId());
            //2、手動提交數據
            openSession.commit();
        } finally {
            openSession.close();
        }
    }
    //************************************************************************************
//                                  修改測試
    //************************************************************************************
    @Test
    public void test03() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //1、獲取到的SqlSession不會自動提交數據
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            /**
             * 測試修改
             */
            Employee employee = new Employee(1, "Tom", "[email protected]", "0");
            boolean updateEmp = mapper.updateEmp(employee);
            System.out.println(updateEmp);

            //2、手動提交數據
            openSession.commit();
        } finally {
            openSession.close();
        }
    }
    //************************************************************************************
//                                  刪除測試
    //************************************************************************************
    @Test
    public void test04() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //1、獲取到的SqlSession不會自動提交數據
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            /**
             * 測試刪除
             */
            mapper.deleteEmpById(2);

            //2、手動提交數據
            openSession.commit();
        } finally {
            openSession.close();
        }
    }




}




哈哈~~~~~~~~第一個mybatis的helloworld練習結束了

2.mybatis的映射文件

mybatis操作數據庫都編寫在映射文件中,再對外提供映射文件的接口給服務層調用,因此映射文件非常重要

1.映射文件參數處理

1.建數據庫表

使用mysql數據庫

DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `last_name` varchar(255) DEFAULT NULL,
 `gender` char(1) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1', 'sujinran', '女', '[email protected]');



2.導包(maven)

在pom.xml中導入mybatis需要的依賴包

  <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!--日誌-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

mybatis的映射文件找不到解決方法如下:

 <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
        <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>


3.javabean類

com.demo.bean.Employee 實體類

package com.demo.bean;
    public class Employee {
        private Integer id; //編號
        private String lastName; //姓名
        private String email; //郵箱
        private String gender; //性別
        public Employee(Integer id, String lastName, String email, String gender) {
            this. id = id;
            this. lastName = lastName;
            this. email = email;
            this. gender = gender;
        }
        public Employee() {
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this. id = id;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this. lastName = lastName;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this. email = email;
        }
        public String getGender() {
            return gender;
        }
        public void setGender(String gender) {
            this. gender = gender;
        }
        @Override
        public String toString() {
            return "Employee [id=" + id + ", lastName=" + lastName + ", email="
                    + email + ", gender=" + gender + "]";
        }
    }

4.mybatis 配置文件

mybatis-config.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>
    <!--
    1、 mybatis可以使用properties來引入外部properties配置文件的內容;
    resource:引入類路徑下的資源
    url:引入網絡路徑或者磁盤路徑下的資源
    -->
    <properties resource="dbconfig.properties"></properties>
    <!--
    2、 settings包含很多重要的設置項
    setting:用來設置每一個設置項
    name:設置項名
    value:設置項取值
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 3、 typeAliases:別名處理器:可以爲我們的java類型起別名
    別名不區分大小寫
    -->
    <typeAliases>
        <!-- 1、 typeAlias:爲某個java類型起別名
        type:指定要起別名的類型全類名;默認別名就是類名小寫; employee
        alias:指定新的別名
        -->
        <!-- <typeAlias type="com.atguigu.mybatis.bean.Employee" alias="emp"/> -->
        <!-- 2、 package:爲某個包下的所有類批量起別名
        name:指定包名(爲當前包以及下面所有的後代包的每一個類都起一個默認別名
       (類名小寫),)
        -->
        <package name="com.demo.bean"/>
        <!-- 3、批量起別名的情況下,使用@Alias註解爲某個類型指定新的別名 -->
    </typeAliases>
    <!--
    4、 environments:環境們, mybatis可以配置多種環境 ,default指定使用某種環境。可以
   達到快速切換環境。
    environment:配置一個具體的環境信息;必須有兩個標籤; id代表當前環境的唯一標識
    transactionManager:事務管理器;
    type:事務管理器的類
   型;JDBC(JdbcTransactionFactory)|MANAGED(ManagedTransactionFactory)
    自定義事務管理器:實現TransactionFactory接口.type指定爲全類名
    dataSource:數據源;
    type:數據源類型;UNPOOLED(UnpooledDataSourceFactory)
    |POOLED(PooledDataSourceFactory)
    |JNDI(JndiDataSourceFactory)
    自定義數據源:實現DataSourceFactory接口, type是全類名
    -->
    <environments default="dev_mysql">
        <environment id="dev_mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 5、 databaseIdProvider:支持多數據庫廠商的;
    type="DB_VENDOR": VendorDatabaseIdProvider
    作用就是得到數據庫廠商的標識(驅動getDatabaseProductName()), mybatis就能根據
   數據庫廠商標識來執行不同的sql;
    MySQL, Oracle, SQL Server,xxxx
    -->
    <databaseIdProvider type="DB_VENDOR">
        <!-- 爲不同的數據庫廠商起別名 -->
        <property name="MySQL" value="mysql"/>
    </databaseIdProvider>
    <!-- 將我們寫好的sql映射文件(EmployeeMapper.xml)一定要註冊到全局配置文件(mybatisconfig.xml)中 -->
    <!-- 6、 mappers:將sql映射註冊到全局配置中 -->
    <mappers>
        <!--
        mapper:註冊一個sql映射
        註冊配置文件
        resource:引用類路徑下的sql映射文件
        mybatis/mapper/EmployeeMapper.xml
        url:引用網路路徑或者磁盤路徑下的sql映射文件
        file:///var/mappers/AuthorMapper.xml
        註冊接口
        class:引用(註冊)接口,
        1、有sql映射文件,映射文件名必須和接口同名,並且放在與接口同一目錄
       下;
        2、沒有sql映射文件,所有的sql都是利用註解寫在接口上;
        推薦:
        比較重要的,複雜的Dao接口我們來寫sql映射文件
        不重要,簡單的Dao接口爲了開發快速可以使用註解;
        -->
        <!--註冊xml-->
        <!-- <mapper resource="mybatis/mapper/EmployeeMapper.xml"/> -->
        <!--註冊接口:必須接口和映射文件同名同包-->
        <!-- <mapper class="com.atguigu.mybatis.dao.EmployeeMapperAnnotation"/> -->
        <!-- 批量註冊:必須接口和映射文件同名同包 -->
        <package name="com.demo.dao"/>
    </mappers>
</configuration>

5.數據庫配置文件

dbconfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456

6.mapper接口及映射文件

com.demo.dao.EmployeeMapper

package com.demo.dao;

import com.demo.bean.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.Map;

public interface EmployeeMapper {
    // 查詢
    //單個參數處理
    public Employee getEmpById(Integer id);

    //多個參數處理
    public Employee getEmpByIdAndLastName(@Param("id") Integer id, @Param("lastName") String lastName);

    //如果多個參數不是業務模型中的數據,沒有對應的pojo,不經常使用,爲了方便,我們也可以傳入map
    public Employee getEmpByMap(Map<String, Object> map);

}

com/demo/dao/EmployeeMapper.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="com.demo.dao.EmployeeMapper">
    <!--
    單個參數處理
    -->
    <select id="getEmpById" resultType="com.demo.bean.Employee">
        select id,last_name,email,gender from tbl_employee where id = #{id}
    </select>
    <!--多個參數處理-->
    <!-- public Employee getEmpByIdAndLastName(Integer id,String lastName);-->
    <select id="getEmpByIdAndLastName" resultType="com.demo.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
    </select>
    <!--多個參數不是業務模型中的數據,沒有對應的pojo-->
    <!-- public Employee getEmpByMap(Map<String, Object> map); -->
    <select id="getEmpByMap" resultType="com.demo.bean.Employee">
        select * from tbl_employee where id=#{id} and last_name=#{lastName}
    </select>
</mapper>

7.測試

import com.demo.bean.Employee;
import com.demo.dao.EmployeeMapper;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MyBatisTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources. getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
    //*********************************************************************************
//                                單個參數處理
    //*********************************************************************************
    @Test
    public void test01() throws IOException {
        // 1、獲取sqlSessionFactory對象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        // 2、獲取sqlSession對象
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            // 3、獲取接口的實現類對象
            //會爲接口自動的創建一個代理對象,代理對象去執行增刪改查方法
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper. class);
            Employee employee = mapper.getEmpById(1);
            System. out.println(employee);
        } finally {
            openSession.close();
        }
    }
    //*********************************************************************************
                                //    多個參數處理
    //*********************************************************************************
    @Test
    public void test02() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //1、獲取到的SqlSession不會自動提交數據
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper. class);
            Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
            System. out.println(employee);
        } finally {
            openSession.close();
        }
    }
    //*********************************************************************************
//                      多個參數不是業務模型中的數據,沒有對應的pojo
    //*********************************************************************************
    @Test
    public void test03() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //1、獲取到的SqlSession不會自動提交數據
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper. class);
            Map<String, Object> map = new HashMap<>();
            map.put("id", 1);
            map.put("lastName", "Tom");
            map.put("tableName", "tbl_employee");
            Employee employee = mapper.getEmpByMap(map);
            System. out.println(employee);
        } finally {
            openSession.close();
        }
    }
}











發佈了40 篇原創文章 · 獲贊 27 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章