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


}

 

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