Mybatis Mapper動態代理(示例)

Mybatis Mapper動態代理(示例)

1.創建工程

2.在文件中創建lib文件夾,並引入相關jar包

3.創建數據表

4.創建與表對應的關係映射(domain包)

package com.helong.domain;
import lombok.setter;
import lombok.getter;

@Setter@Getter
public class Customer {
    private Integer custId;
    private String custName;
    private String custProfession;
    private String custPhone;
    private String email;    

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custProfession='" + custProfession + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

 

5.創建資源文件夾,並引入相關配置文件

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=xxxxxx

 SqlMappingConfig.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"/>

    <!--配置sql打印-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--開啓駝峯命名法-->
        <!--開啓駝峯映射,爲自定義的SQL語句服務-->
        <!--設置啓用數據庫字段下劃線映射到java對象的駝峯式命名屬性,默認是false-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--定義別名-->
    <typeAliases>
        <!--單個別名定義-->
        <!--<typeAlias alias="Customer" type="com.helong.domain.Customer"/>-->
        <!--批量定義別名, 別名爲類名-->
        <package name="com.helong.domain"/>
    </typeAliases>



    <!-- spring整合後 environments配置將廢除 使用spring中的連接池 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事務管理 -->
            <transactionManager type="JDBC" />
            <!-- 數據庫連接池 -->
            <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>

        <environment id="test">
            <!-- 使用jdbc事務管理 -->
            <transactionManager type="JDBC" />
            <!-- 數據庫連接池 -->
            <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>

    <!--定義數據庫廠商-->
    <databaseIdProvider type="DB_VENDOR">
        <property name="MySQL" value="mysql"/>
        <property name="DB2" value="db2"/>
        <property name="Oracle" value="oracle" />
        <property name="SQL Server" value="sqlserver"/>
    </databaseIdProvider>

    <!--加載映射文件-->
    <mappers>
        <!-- <mapper resource="com/helong/domain/Customer.xml"></mapper>-->
        <!--
        1.名稱必須得要和接口名稱一致
        2.必須得要和mapper接口在同一目錄
        -->
        <!--<mapper class="com.helong.mapper.CustomerMapper"/>-->
        <package name="com.helong.mapper"/>
    </mappers>
</configuration>

6.創建表所對應的Mapper類以及其所對應的xml文件(mapper包中)

示例:

CustomerMapper接口:

package com.helong.mapper;

import com.helong.domain.Customer;
import org.apache.ibatis.annotations.Param;

import java.util.Map;

public interface CustomerMapper {
    public Customer getCustomerWithID1(@Param("id") Integer id, @Param("name") String name);
    public Customer getCustomerWithID2(Map<String, Object> map);
    public Customer getCustomerWithID3(Customer customer);
}

 CustomerMapper.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.helong.mapper.CustomerMapper">

	<!--查詢用戶 ID-->
	<select id="getCustomerWithID1"  resultType="Customer" >
		select * from `customer` where cust_id = #{id} and cust_name=#{name}
	</select>

	<!--查詢用戶 ID-->
	<select id="getCustomerWithID2"  resultType="Customer"  databaseId="mysql">
		select * from `customer` where cust_id = #{id} and cust_name=#{name}
	</select>

	<!--查詢用戶 ID-->
	<select id="getCustomerWithID3"  resultType="Customer"  databaseId="mysql">
		select * from `customer` where cust_id = #{custId} and cust_name=#{custName}
	</select>

</mapper>


 7.創建MybatisUtils工具(utils),便於操作數據庫

package com.helong.utils;

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.InputStream;

public class MybatisUtils {
    public static final SqlSessionFactory sessionFactory;
    static {
        //1.sqlSessionFactoryBuilder 加載配置文件
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.讀取配置文件
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("SqlMappingConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.獲取session工廠
        sessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
    }

    public static SqlSession openSession(){
        return sessionFactory.openSession();
    }

}

8.創建測試類(test包)

package com.helong.test;

import com.helong.domain.Customer;
import com.helong.mapper.CustomerMapper;
import com.helong.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;

public class MyTest {

    @Test
    public void test1(){
        SqlSession sqlSession = MybatisUtils.openSession();
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        Customer customer = mapper.getCustomerWithID1(13, "何鑫林");
        System.out.println(customer);
        sqlSession.close();
    }

    @Test
    public void test2(){
        SqlSession sqlSession = MybatisUtils.openSession();
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        HashMap<String, Object> customerHashMap = new HashMap<>();
        customerHashMap.put("id",14);
        customerHashMap.put("name","XX");
        Customer customer = mapper.getCustomerWithID2(customerHashMap);
        System.out.println(customer);
        sqlSession.close();
    }

    @Test
    public void test3(){
        SqlSession sqlSession = MybatisUtils.openSession();
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        Customer customer = new Customer();
        customer.setCustId(13);
        customer.setCustName("何鑫林");
        Customer customer1 = mapper.getCustomerWithID3(customer);
        System.out.println(customer1);
        sqlSession.close();
    }


}

 

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