java框架之MyBatis(2)-進階&整合Spring&逆向工程

進階內容

準備

jdbc.url=jdbc:mysql://192.168.208.192:3306/test?characterEncoding=utf-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
jdbc.properties
log4j.rootLogger = debug,stdout,E

### 輸出信息到控制擡 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 輸出DEBUG 級別以上的日誌到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 輸出ERROR 級別以上的日誌到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
log4j.properties
<?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="jdbc.properties"/>

    <!--別名掃描-->
    <typeAliases>
        <package name="com.zze.mybatis.pojo" />
    </typeAliases>

    <!-- 和 spring 整合後 environments配置將廢除-->
    <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>
    </environments>

    <!-- 加載映射文件 -->
    <mappers>
        <package name="com.zze.mybatis.mapper"/>
    </mappers>
</configuration>
mybatis/SqlMapConfig.xml
package com.zze.mybatis.pojo;

import java.util.Date;

public class User {
    private Integer id;
    private String name;
    private Date birthday;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
com.zze.mybatis.pojo.User
package com.zze.mybatis.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.InputStream;

public class SqlSessionFactoryUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        // 建立 SqlSessionFactoryBuilder 對象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 建立核心配置文件的輸入流
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis/SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 建立 Session 工廠
        sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
    }

    /**
     * 打開一個 Session
     *
     * @return SqlSession 實例
     */
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * 打開一個 Session
     *
     * @param autoCommit 是否自動提交事務
     * @return SqlSession 實例
     */
    public static SqlSession openSession(Boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }
}
com.zze.mybatis.util.SqlSessionFactoryUtil
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zze.mybatis</groupId>
    <artifactId>mybatis_test2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.11.0.GA</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml

傳遞被包裝的pojo

package com.zze.mybatis.pojo;

public class QueryVO {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
com.zze.mybatis.pojo.QueryVO
<?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.zze.mybatis.mapper.UserMapper">
    <select id="getByQueryVO" parameterType="queryvo" resultType="user">
        select id,name,birthday from user where name like '%${user.name}%'
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml
package com.zze.mybatis.mapper;

import com.zze.mybatis.pojo.QueryVO;
import com.zze.mybatis.pojo.User;

public interface UserMapper {
    User getByQueryVO(QueryVO queryVO);
}
com.zze.mybatis.mapper.UserMapper
@Test
public void test() {
    SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    QueryVO queryVO = new QueryVO();
    User user = new User();
    user.setName("張");
    queryVO.setUser(user);
    User user1 = mapper.getByQueryVO(queryVO);
    System.out.println(user1);
  /*
  ==>  Preparing: select name,age,birthday,uuid from user where name like '%張%'
   */
}
test

標籤使用

字段映射-resultMap

若是表字段名與 pojo 屬性名不一致,則可經過 resultMap 標籤配置表字段與 pojo 屬性的映射關係:java

<?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.zze.mybatis.mapper.UserMapper">
    <resultMap id="userMap" type="user">
        <!--
        id 配置對應主鍵字段
            property:屬性名
            column:字段名
        -->
        <id property="id" column="uid"/>
        <!--
        result 配置普通屬性字段
            property:屬性名
            column:字段名
        -->
        <result property="name" column="username"/>
        <!--
        非關聯查詢時
        屬性名與字段名相同的 result 映射能夠省略不寫
        -->
        <!--<result property="birthday" column="birthday"/>-->
    </resultMap>

    <select id="getAll" resultMap="userMap">
        select id uid,name username,birthday from user;
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml
package com.zze.mybatis.mapper;

import com.zze.mybatis.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getAll();
}
com.zze.mybatis.mapper.UserMapper
package com.zze.mybatis.test;

import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class MyBatisTest {
    private UserMapper userMapper;

    @Before
    public void init() {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void test() {
        List<User> all = userMapper.getAll();
        for (User user : all) {
            System.out.println(user);
        }
        /*
        ==>  Preparing: select id uid,name username,birthday from user;
         */
    }
}
test

動態sql-where&if

當 sql 條件須要動態拼接時,可使用 where 和 if 標籤:mysql

<?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.zze.mybatis.mapper.UserMapper">
    <select id="getByUser" resultType="user" parameterType="user">
        select id,name,birthday from user
        <where>
            <if test="name!=null and name!=''">
                name like '%${name}%'
            </if>
        </where>
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml
package com.zze.mybatis.mapper;

import com.zze.mybatis.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getByUser(User user);
}
com.zze.mybatis.mapper.UserMapper
package com.zze.mybatis.test;

import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class MyBatisTest {
    private UserMapper userMapper;

    @Before
    public void init() {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void test() {
        User user = new User();
        user.setName("張");
        List<User> userList1 = userMapper.getByUser(user);
        userList1.forEach(u-> System.out.println(u));
        /*
        ==>  Preparing: select id,name,birthday from user WHERE name like '%張%'
         */
        user.setName(null);
        List<User> userList2 = userMapper.getByUser(user);
        userList2.forEach(u-> System.out.println(u));
        /*
        ==>  Preparing: select id,name,birthday from user
         */
    }
}
test

sql片斷-sql&include

當一段 sql 要被頻繁在多處使用時,能夠將這段 sql 單獨抽取出來:spring

<?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.zze.mybatis.mapper.UserMapper">
    <sql id="userAllField">
      id,name,birthday
    </sql>
    <select id="getAll" resultType="user">
        select
        <include refid="userAllField"/>
        from user
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml
package com.zze.mybatis.mapper;

import com.zze.mybatis.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getAll();
}
com.zze.mybatis.mapper.UserMapper
package com.zze.mybatis.test;

import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class MyBatisTest {
    private UserMapper userMapper;

    @Before
    public void init() {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void test() {
        List<User> userList = userMapper.getAll();
        userList.forEach(u-> System.out.println(u));
        /*
        ==>  Preparing: select id,name,birthday from user
         */
    }
}
test

循環-foreach

編寫 sql 時也能夠經過傳入集合來動態拼裝條件:sql

package com.zze.mybatis.pojo;

import java.util.List;

public class QueryVO {
    private List<Integer> idList;

    public List<Integer> getIdList() {
        return idList;
    }

    public void setIdList(List<Integer> idList) {
        this.idList = idList;
    }
}
com.zze.mybatis.pojo.QueryVO
<?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.zze.mybatis.mapper.UserMapper">
    <select id="getByIdList" resultType="user" parameterType="queryvo">
        select * from user
        <where>
            <foreach collection="idList" open="id in (" close=")" separator="," item="id">
              #{id}
            </foreach>
        </where>
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml
package com.zze.mybatis.mapper;

import com.zze.mybatis.pojo.QueryVO;
import com.zze.mybatis.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getByIdList(QueryVO queryVO);
}
com.zze.mybatis.mapper.UserMapper
package com.zze.mybatis.test;

import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.QueryVO;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class MyBatisTest {
    private UserMapper userMapper;

    @Before
    public void init() {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void test() {
        QueryVO queryVO = new QueryVO();
        queryVO.setIdList(Arrays.asList(1, 2, 3));
        List<User> userList = userMapper.getByIdList(queryVO);
        userList.forEach(u-> System.out.println(u));
        /*
        ==>  Preparing: select * from user WHERE id in ( ? , ? , ? )
        ==> Parameters: 1(Integer), 2(Integer), 3(Integer)
         */
    }
}
test

要注意的是 mybatis 不支持直接傳入集合,但咱們能夠如上示例將它放在包裝類中傳入。數據庫

關聯查詢

一對一

新建與用戶關聯的訂單表和 pojo,配置映射文件:apache

package com.zze.mybatis.pojo;

import java.util.Date;

public class Order {
    private Integer id;
    private Integer uId;
    private Double totalPrice;
    private Date createDate;
    /*
    Order 一對一關聯 User
     */
    private User user;

    public Integer getId() {
        return id;
    }

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

    public Integer getuId() {
        return uId;
    }

    public void setuId(Integer uId) {
        this.uId = uId;
    }

    public Double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", uId=" + uId +
                ", TotalPrice=" + totalPrice +
                ", createDate=" + createDate +
                ", user=" + user +
                '}';
    }
}
com.zze.mybatis.pojo.Order
<?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.zze.mybatis.mapper.OrderMapper">
    <resultMap id="orderMap" type="order">
        <!--
        注意:
                在關聯查詢時,每一個映射字段都需配置,不可省略。
        -->
        <id property="id" column="oid"/>
        <result property="uId" column="uid"/>
        <result property="totalPrice" column="totalPrice"/>
        <result property="createDate" column="createdate"/>
        <!--
        經過 association 配置一對一關係
        -->
        <association property="user" javaType="user">
            <id property="id" column="uid"/>
            <result property="name" column="name"/>
            <result property="birthday" column="birthday"/>
        </association>
    </resultMap>

    <select id="getAll" resultMap="orderMap">
      select o1.id oid,o1.uid,totalPrice,createdate,name,birthday from `order` o1 left join `user` u1 on o1.uid = u1.id;
    </select>
</mapper>
com/zze/mybatis/mapper/OrderMapper.xml
package com.zze.mybatis.test;

import com.zze.mybatis.mapper.OrderMapper;
import com.zze.mybatis.pojo.Order;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class OrderTest {

    private OrderMapper orderMapper;

    @Before
    public void init() {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        orderMapper = sqlSession.getMapper(OrderMapper.class);
    }

    @Test
    public void test() {
        List<Order> orderList = orderMapper.getAll();
        orderList.forEach(o -> System.out.println(o));

        /*
        ==>  Preparing: select o1.id oid,o1.uid,totalPrice,createdate,name,birthday from `order` o1 left join `user` u1 on o1.uid = u1.id;

        Order{id=1, uId=1, TotalPrice=324.0, createDate=Thu Mar 21 11:10:20 CST 2019, user=User{id=1, name='張三', birthday=Thu Jan 01 00:00:00 CST 1998}}
        Order{id=3, uId=1, TotalPrice=543.0, createDate=Mon Mar 18 11:11:05 CST 2019, user=User{id=1, name='張三', birthday=Thu Jan 01 00:00:00 CST 1998}}
        Order{id=2, uId=3, TotalPrice=23.0, createDate=Fri Mar 01 06:04:07 CST 2019, user=User{id=3, name='李四', birthday=Thu Jan 01 00:00:00 CST 1998}}
         */
    }
}
test

一對多

修改用戶的 pojo 關聯訂單,配置映射文件:api

package com.zze.mybatis.pojo;

import java.util.Date;
import java.util.List;

public class User {
    private Integer id;
    private String name;
    private Date birthday;

    /*
    User 一對多關聯 Order
     */
    private List<Order> orders;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public List<Order> getOrders() {
        return orders;
    }

    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
com.zze.mybatis.pojo.User
<?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.zze.mybatis.mapper.UserMapper">
    <resultMap id="userMap" type="user">
        <id property="id" column="uId"/>
        <result property="name" column="name"/>
        <result property="birthday" column="birthday"/>
        <!--
        使用 collection 標籤創建一對多關係
            注意,這裏使用的是 ofType,而一對一關聯時使用的是 javaType
        -->
        <collection property="orders" ofType="order">
            <id property="id" column="oId"/>
            <result property="totalPrice" column="totalPrice"/>
            <result property="createDate" column="createDate"/>
            <result property="uId" column="uId"/>
        </collection>
    </resultMap>

    <select id="getAll" resultMap="userMap">
        select u1.id uId,o1.id oId,totalPrice,createdate,name,birthday from `user` u1 left join `order` o1 on u1.id=o1.uid;
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml

MyBatis與Spring整合

整合思路

  1. SqlSessionFactory 對象應該交給 Spring 管理並做爲單例存在。
  2. 傳統 dao 的開發方式中,應該從 Spring 容器中獲取 SqlSession 對象。
  3. Mapper 動態代理開發方式中,應該從 Spring 容器中直接得到 Mapper 對象。
  4. 數據庫的鏈接及鏈接池、事務都交給 Spring 管理。

準備

一、建立一個 maven java 工程,引入相關依賴:session

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zze.mybatis</groupId>
    <artifactId>mybatis_spring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!--spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!--mybatis 整合 spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--mysql 驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--阿里巴巴數據源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--日誌-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml

二、引入 mybatis 核心配置文件:mybatis

<?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>
   
</configuration>
config/SqlMapConfig.xml

三、引入 jdbc 鏈接信息屬性文件:app

jdbc.url=jdbc:mysql://192.168.208.192:3306/test?characterEncoding=utf-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
config/jdbc.properties

四、引入 log4j 屬性文件:

log4j.rootLogger = debug,stdout,E

### 輸出信息到控制擡 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 輸出DEBUG 級別以上的日誌到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 輸出ERROR 級別以上的日誌到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
log4j.properties

五、引入 spring 核心配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!--讀取屬性文件-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <!--鏈接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 配置初始化大小、最小、最大 -->
        <property name="maxActive" value="20"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <!-- 配置獲取鏈接等待超時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
    </bean>
    <!--配置 SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置核心配置文件路徑-->
        <property name="configLocation" value="classpath:config/SqlMapConfig.xml"/>
        <!--配置別名掃描包-->
        <property name="typeAliasesPackage" value="com.zze.mybatis.pojo"/>
    </bean>
</beans>
config/applicationContext.xml

六、建立測試用 pojo 及其映射文件:

package com.zze.mybatis.pojo;

import java.util.Date;

public class User {
    private Integer id;
    private String name;
    private String gender;
    private Date birthday;
    private String address;

    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 String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}
com.zze.mybatis.pojo.User
<?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>
    <mappers>
        <mapper resource="config/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
config/mapper/UserMapper.xml

七、建立 dao 接口:

package com.zze.mybatis.dao;

import com.zze.mybatis.pojo.User;

import java.util.List;

public interface UserDao {
    List<User> getAll();
}
com.zze.mybatis.dao.UserDao

傳統dao開發

一、在 mybatis 核心配置文件中引入映射文件:

<?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>
    <mappers>
        <mapper resource="config/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
config/SqlMapConfig.xml

二、編寫 dao 接口實現類:

package com.zze.mybatis.dao.impl;

import com.zze.mybatis.dao.UserDao;
import com.zze.mybatis.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    @Override
    public List<User> getAll() {
        SqlSession sqlSession = super.getSqlSession();
        List<User> userList = sqlSession.selectList("user.getAll");
        // 注意,這裏 SqlSession 的實例的建立與銷燬已經交給 Spring 管理,不用手動關閉,不然會異常
        return userList;
    }
}
com.zze.mybatis.dao.impl.UserDaoImpl

三、修改 Spring 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!--讀取屬性文件-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <!--鏈接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 配置初始化大小、最小、最大 -->
        <property name="maxActive" value="20"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <!-- 配置獲取鏈接等待超時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
    </bean>
    <!--配置 SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置核心配置文件路徑-->
        <property name="configLocation" value="classpath:config/SqlMapConfig.xml"/>
        <!--配置別名掃描包-->
        <property name="typeAliasesPackage" value="com.zze.mybatis.pojo"/>
    </bean>

    <bean id="userDao" class="com.zze.mybatis.dao.impl.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>
config/applicationContext.xml

四、測試:

package com.zze.mybatis.test;

import com.zze.mybatis.dao.UserDao;
import com.zze.mybatis.pojo.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class UserDaoTest {

    private ApplicationContext applicationContext;
    @Before
    public void init(){
        applicationContext = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");
    }
    @Test
    public void test(){
        UserDao userDao = applicationContext.getBean(UserDao.class);
        List<User> userList = userDao.getAll();
        userList.forEach(u-> System.out.println(u));
        /*
        ==>  Preparing: select id,name,gender,birthday,address from user;
         */
    }
}
com.zze.mybatis.test.UserDaoTest

動態代理開發

一、修改 UserDao 爲 UserMapper:

package com.zze.mybatis.mapper;

import com.zze.mybatis.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getAll();
}
com.zze.mybatis.mapper.UserMapper

二、將映射文件放入 mapper 同一目錄,並指定 namespace 爲 mapper 類全路徑:

<?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.zze.mybatis.mapper.UserMapper">
    <select id="getAll" resultType="user">
        select id,name,gender,birthday,address from user;
    </select>
</mapper>
com/zze/mybatis/mapper/UserMapper.xml

三、修改 Spring 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!--讀取屬性文件-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <!--鏈接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 配置初始化大小、最小、最大 -->
        <property name="maxActive" value="20"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <!-- 配置獲取鏈接等待超時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
    </bean>
    <!--配置 SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置核心配置文件路徑-->
        <property name="configLocation" value="classpath:config/SqlMapConfig.xml"/>
        <!--配置別名掃描包-->
        <property name="typeAliasesPackage" value="com.zze.mybatis.pojo"/>
    </bean>

    <!--動態代理配置方式一:配置單個接口-->
    <!--
    <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
    <bean parent="baseMapper">
        <property name="mapperInterface" value="com.zze.mybatis.mapper.UserMapper"/>
    </bean>
    -->
    <!--動態代理配置方式二:配置 mapper 包掃描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zze.mybatis.mapper"/>
    </bean>
</beans>
config/applicationContext.xml

四、測試:

package com.zze.mybatis.test;

import com.zze.mybatis.dao.UserDao;
import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class UserMapperTest {

    private ApplicationContext applicationContext;
    @Before
    public void init(){
        applicationContext = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");
    }
    @Test
    public void test(){
        UserMapper userMapper = applicationContext.getBean(UserMapper.class);
        List<User> userList = userMapper.getAll();
        userList.forEach(u-> System.out.println(u));
        /*
        ==>  Preparing: select id,name,gender,birthday,address from user;
         */
    }
}
com.zze.mybatis.test.UserMapperTest

逆向工程

建立maven逆向工程

一、建立 maven java 工程,引入以下依賴:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zze</groupId>
    <artifactId>mybaits_generator</artifactId>
    <version>Lasted</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
</project>
pom.xml

二、引入逆向生成配置文件:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 能夠用於加載配置項或者配置文件,在整個配置文件中就可使用${propertyKey}的方式來引用配置項
    resource:配置資源加載地址,使用resource,MBG從classpath開始找,好比com/myproject/generatorConfig.properties
    url:配置資源加載地質,使用URL的方式,好比file:///C:/myfolder/generatorConfig.properties.
    注意,兩個屬性只能選址一個;

    另外,若是使用了mybatis-generator-maven-plugin,那麼在pom.xml中定義的properties均可以直接在generatorConfig.xml中使用
    <properties resource="" url="" />
    -->

    <!-- 在MBG工做的時候,須要額外加載的依賴包
       location屬性指明加載jar/zip包的全路徑
   <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />
     -->

    <!--
        context:生成一組對象的環境
        id:必選,上下文id,用於在生成錯誤時提示
        defaultModelType:指定生成對象的樣式
            1,conditional:相似hierarchical;
            2,flat:全部內容(主鍵,blob)等所有生成在一個對象中;
            3,hierarchical:主鍵生成一個XXKey對象(key class),Blob等單獨生成一個對象,其餘簡單屬性在一個對象中(record class)
        targetRuntime:
            1,MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample;
            2,MyBatis3Simple:相似MyBatis3,只是不生成XXXBySample;
        introspectedColumnImpl:類全限定名,用於擴展MBG
    -->
    <context id="mybatisGenerator">
        <!--
            自動識別數據庫關鍵字,默認false,若是設置爲true,根據SqlReservedWords中定義的關鍵字列表;
            通常保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋
        -->
        <property name="autoDelimitKeywords" value="false"/>
        <!-- 生成的Java文件的編碼 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代碼 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代碼 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

        <!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,好比ORACLE就是雙引號,MYSQL默認是`反引號; -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>


        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--數據庫鏈接的信息:驅動類、鏈接地址、用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?
                                serverTimezone=CTT&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <!-- java類型處理器
        用於處理DB中的類型到Java中的類型,默認使用JavaTypeResolverDefaultImpl;
        注意一點,默認會先嚐試使用Integer,Long,Short等來對應DECIMAL和 NUMERIC數據類型;
        -->
        <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
            <!--
                true:使用BigDecimal對應DECIMAL和 NUMERIC數據類型
                false:默認,
                    scale>0;length>18:使用BigDecimal;
                    scale=0;length[10,18]:使用Long;
                    scale=0;length[5,9]:使用Integer;
                    scale=0;length<5:使用Short;
             -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- java模型建立器,是必需要的元素
        負責:1,key類(見context的defaultModelType);2,java類;3,查詢類
        targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制;
        targetProject:目標項目,指定一個存在的目錄下,生成的內容會放到指定目錄中,若是目錄不存在,MBG不會自動建目錄
        -->
        <javaModelGenerator targetPackage="com.zze.mybatis.pojo"
                            targetProject="mybatis_spring/src/main/java">
            <!--  for MyBatis3/MyBatis3Simple
            自動爲每個生成的類建立一個構造方法,構造方法包含了全部的field;而不是使用setter;
            -->
            <property name="constructorBased" value="false"/>

            <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
            <property name="enableSubPackages" value="true"/>

            <!-- for MyBatis3 / MyBatis3Simple
                是否建立一個不可變的類,若是爲true,
                那麼MBG會建立一個沒有setter方法的類,取而代之的是相似constructorBased的類
             -->
            <property name="immutable" value="false"/>

            <!-- 設置一個根對象,
                若是設置了這個根對象,那麼生成的keyClass或者recordClass會繼承這個類;在Table的rootClass屬性中能夠覆蓋該選項
                注意:若是在key class或者record class中有root class相同的屬性,MBG就不會從新生成這些屬性了,包括:
                    1,屬性名相同,類型相同,有相同的getter/setter方法;
             -->
            <!-- <property name="rootClass" value="com.zze.mybatis.pojo.BaseDomain"/>-->

            <!-- 設置是否在getter方法中,對String類型字段調用trim()方法 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成SQL map的XML文件生成器,
             注意,在Mybatis3以後,咱們可使用mapper.xml文件+Mapper接口(或者不用mapper接口),
                 或者只使用Mapper接口+Annotation,因此,若是 javaClientGenerator配置中配置了須要生成XML的話,這個元素就必須配置
             targetPackage/targetProject:同javaModelGenerator
        -->
        <sqlMapGenerator targetPackage="com.zze.mybatis.mapper"
                         targetProject="mybatis_spring/src/main/resources">
            <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 對於mybatis來講,即生成Mapper接口,注意,若是沒有配置該元素,那麼默認不會生成Mapper接口
            targetPackage/targetProject:同javaModelGenerator
            type:選擇怎麼生成mapper接口(在MyBatis3/MyBatis3Simple下):
                1,ANNOTATEDMAPPER:會生成使用Mapper接口+Annotation的方式建立(SQL生成在annotation中),不會生成對應的XML;
                2,MIXEDMAPPER:使用混合配置,會生成Mapper接口,並適當添加合適的Annotation,可是XML會生成在XML中;
                3,XMLMAPPER:會生成Mapper接口,接口徹底依賴XML;
            注意,若是context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
        -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.zze.mybatis.mapper"
                             targetProject="mybatis_spring/src/main/java">
            <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
            <property name="enableSubPackages" value="true"/>

            <!-- 能夠爲全部生成的接口添加一個父接口,可是MBG只負責生成,不負責檢查-->
            <!--<property name="rootInterface" value=""/>-->

        </javaClientGenerator>
        <!-- 選擇一個table來生成相關文件,能夠有一個或多個table,必需要有table元素
            選擇的table會生成一下文件:
            1,SQL map文件
            2,生成一個主鍵類;
            3,除了BLOB和主鍵的其餘字段的類;
            4,包含BLOB的類;
            5,一個用戶生成動態查詢的條件類(selectByExample, deleteByExample),可選;
            6,Mapper接口(可選)

            tableName(必要):要生成對象的表名;
            注意:大小寫敏感問題。正常狀況下,MBG會自動的去識別數據庫標識符的大小寫敏感度,在通常狀況下,MBG會
                根據設置的schema,catalog或tablename去查詢數據表,按照下面的流程:
                1,若是schema,catalog或tablename中有空格,那麼設置的是什麼格式,就精確的使用指定的大小寫格式去查詢;
                2,不然,若是數據庫的標識符使用大寫的,那麼MBG自動把表名變成大寫再查找;
                3,不然,若是數據庫的標識符使用小寫的,那麼MBG自動把表名變成小寫再查找;
                4,不然,使用指定的大小寫格式查詢;
            另外的,若是在建立表的時候,使用的""把數據庫對象規定大小寫,就算數據庫標識符是使用的大寫,在這種狀況下也會使用給定的大小寫來建立表名;
            這個時候,請設置delimitIdentifiers="true"便可保留大小寫格式;

            可選:
            1,schema:數據庫的schema;
            2,catalog:數據庫的catalog;
            3,alias:爲數據表設置的別名,若是設置了alias,那麼生成的全部的SELECT SQL語句中,列名會變成:alias_actualColumnName
            4,domainObjectName:生成的domain類的名字,若是不設置,直接使用表名做爲domain類的名字;能夠設置爲somepck.domainName,那麼會自動把domainName類再放到somepck包裏面;
            5,enableInsert(默認true):指定是否生成insert語句;
            6,enableSelectByPrimaryKey(默認true):指定是否生成按照主鍵查詢對象的語句(就是getById或get);
            7,enableSelectByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢語句;
            8,enableUpdateByPrimaryKey(默認true):指定是否生成按照主鍵修改對象的語句(即update);
            9,enableDeleteByPrimaryKey(默認true):指定是否生成按照主鍵刪除對象的語句(即delete);
            10,enableDeleteByExample(默認true):MyBatis3Simple爲false,指定是否生成動態刪除語句;
            11,enableCountByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢);
            12,enableUpdateByExample(默認true):MyBatis3Simple爲false,指定是否生成動態修改語句(只修改對象中不爲空的屬性);
            13,modelType:參考context元素的defaultModelType,至關於覆蓋;
            14,delimitIdentifiers:參考tableName的解釋,注意,默認的delimitIdentifiers是雙引號,若是相似MYSQL這樣的數據庫,使用的是`(反引號,那麼還須要設置context的beginningDelimiter和endingDelimiter屬性)
            15,delimitAllColumns:設置是否全部生成的SQL中的列名都使用標識符引發來。默認爲false,delimitIdentifiers參考context的屬性

            注意,table裏面不少參數都是對javaModelGenerator,context等元素的默認屬性的一個複寫;
         -->
        <table tableName="user" domainObjectName="User">
            <!-- 參考 javaModelGenerator 的 constructorBased屬性-->
            <property name="constructorBased" value="false"/>

            <!-- 默認爲false,若是設置爲true,在生成的SQL中,table名字不會加上catalog或schema; -->
            <property name="ignoreQualifiersAtRuntime" value="false"/>

            <!-- 參考 javaModelGenerator 的 immutable 屬性 -->
            <property name="immutable" value="false"/>
            <!-- 指定是否只生成domain類,若是設置爲true,只生成domain類,若是還配置了sqlMapGenerator,那麼在mapper XML文件中,只生成resultMap元素 -->
            <property name="modelOnly" value="false"/>

            <!-- 參考 javaModelGenerator 的 rootClass 屬性
            <property name="rootClass" value=""/>
             -->

            <!-- 參考javaClientGenerator 的  rootInterface 屬性
            <property name="rootInterface" value=""/>
            -->

            <!-- 若是設置了runtimeCatalog,那麼在生成的SQL中,使用該指定的catalog,而不是table元素上的catalog
            <property name="runtimeCatalog" value=""/>
            -->

            <!-- 若是設置了runtimeSchema,那麼在生成的SQL中,使用該指定的schema,而不是table元素上的schema
            <property name="runtimeSchema" value=""/>
            -->

            <!-- 若是設置了runtimeTableName,那麼在生成的SQL中,使用該指定的tablename,而不是table元素上的tablename
            <property name="runtimeTableName" value=""/>
            -->

            <!-- 注意,該屬性只針對MyBatis3Simple有用;
                若是選擇的runtime是MyBatis3Simple,那麼會生成一個SelectAll方法,若是指定了selectAllOrderByClause,那麼會在該SQL中添加指定的這個order條件;
             -->
            <property name="selectAllOrderByClause" value="age desc,username asc"/>

            <!-- 若是設置爲true,生成的model類會直接使用column自己的名字,而不會再使用駝峯命名方法,好比BORN_DATE,生成的屬性名字就是BORN_DATE,而不會是bornDate -->
            <property name="useActualColumnNames" value="false"/>


            <!-- generatedKey用於生成生成主鍵的方法,
                若是設置了該元素,MBG會在生成的<insert>元素中生成一條正確的<selectKey>元素,該元素可選
                column:主鍵的列名;
                sqlStatement:要生成的selectKey語句,有如下可選項:
                    Cloudscape:至關於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL()
                    DB2       :至關於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL()
                    DB2_MF    :至關於selectKey的SQL爲:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
                    Derby     :至關於selectKey的SQL爲:VALUES IDENTITY_VAL_LOCAL()
                    HSQLDB    :至關於selectKey的SQL爲:CALL IDENTITY()
                    Informix  :至關於selectKey的SQL爲:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
                    MySql     :至關於selectKey的SQL爲:SELECT LAST_INSERT_ID()
                    SqlServer :至關於selectKey的SQL爲:SELECT SCOPE_IDENTITY()
                    SYBASE    :至關於selectKey的SQL爲:SELECT @@IDENTITY
                    JDBC      :至關於在生成的insert元素上添加useGeneratedKeys="true"和keyProperty屬性
            <generatedKey column="" sqlStatement=""/>
             -->

            <!--
                該元素會在根據表中列名計算對象屬性名以前先重命名列名,很是適合用於表中的列都有公用的前綴字符串的時候,
                好比列名爲:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等;
                那麼就能夠設置searchString爲"^CUST_",並使用空白替換,那麼生成的Customer對象中的屬性名稱就不是
                custId,custName等,而是先被替換爲ID,NAME,EMAIL,而後變成屬性:id,name,email;

                注意,MBG是使用java.util.regex.Matcher.replaceAll來替換searchString和replaceString的,
                若是使用了columnOverride元素,該屬性無效;

            <columnRenamingRule searchString="" replaceString=""/>
             -->


            <!-- 用來修改表中某個列的屬性,MBG會使用修改後的列來生成domain的屬性;
                column:要從新設置的列名;
                注意,一個table元素中能夠有多個columnOverride元素
                property : 使用property屬性來指定列要生成的屬性名稱
                javaType : 用於指定生成的domain的屬性類型,使用類型的全限定名
                jdbcType : 用於指定該列的JDBC類型
                typeHandler : 用於指定該列使用到的TypeHandler,若是要指定,配置類型處理器的全限定名
                delimitedColumnName : 參考table元素的delimitAllColumns配置,默認爲false
                注意,mybatis中,不會生成到mybatis-config.xml中的typeHandler
                只會生成相似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的參數描述
             -->
            <columnOverride column="name" property="name"/>

            <!-- ignoreColumn設置一個MGB忽略的列,若是設置了改列,那麼在生成的domain中,生成的SQL中,都不會有該列出現
               column:指定要忽略的列的名字;
               delimitedColumnName:參考table元素的delimitAllColumns配置,默認爲false

               注意,一個table元素中能夠有多個ignoreColumn元素
            <ignoreColumn column="deptId" delimitedColumnName=""/>
            -->
        </table>

    </context>
</generatorConfiguration>
generatorConfig.xml

三、引入日誌文件:

log4j.rootLogger = debug,stdout

### 輸出信息到控制擡 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 輸出DEBUG 級別以上的日誌到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 輸出ERROR 級別以上的日誌到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
log4j.properties

四、引入可執行 java 類:

import org.apache.ibatis.io.Resources;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("all")
public class Generator {
    public void generator() throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        /**指向逆向工程配置文件*/
        File configFile = Resources.getResourceAsFile("generatorConfig.xml");
        ConfigurationParser parser = new ConfigurationParser(warnings);
        Configuration config = parser.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                callback, warnings);
        myBatisGenerator.generate(null);
    }

    public static void main(String[] args) throws Exception {
        try {
            Generator generatorSqlmap = new Generator();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Generator

五、在‘generatorConfig.xml’中完成相關配置,執行 Generator 便可。

使用

package com.zze.mybaits.test;

import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.pojo.UserExample;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class UserMapperTest {

    private ApplicationContext applicationContext;
    private UserMapper userMapper;

    @Before
    public void init() {
        applicationContext = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");
        userMapper = applicationContext.getBean(UserMapper.class);
    }

    @Test
    public void testSelectByPrimaryKey() {
        User user = userMapper.selectByPrimaryKey(2);
        System.out.println(user);
        /*
        ==>  Preparing: select id, name, gender, birthday, address from user where id = ?
        ==>  Parameters: 2(Integer)
         */
    }

    /**
     * 指定條件查詢返回列表
     */
    @Test
    public void testSelectByExample() {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andNameLike("%郭%");
        List<User> userList = userMapper.selectByExample(userExample);
        userList.forEach(u -> System.out.println(u));
        /*
        ==>  Preparing: select id, name, gender, birthday, address from user WHERE ( name like ? )
        ==>  Parameters: %郭%(String)
         */
    }

    /**
     * 新增非空字段
     */
    @Test
    public void testInsertSelective() throws ParseException {
        userMapper.insertSelective(new User(null, "郭德綱", "男", new SimpleDateFormat("yyyy-MM-dd").parse("1997-1-1"), null));
        /*
        ==>  Preparing: insert into user ( name, gender, birthday ) values ( ?, ?, ? )
        ==>  Parameters: 郭德綱(String), 男(String), 1997-01-01(Date)
         */
    }

    /**
     * 新增所有
     */
    @Test
    public void testInsert() throws ParseException {
        userMapper.insert(new User(null, "郭德綱", "男", new SimpleDateFormat("yyyy-MM-dd").parse("1997-1-1"), null));
        /*
        ==>  Preparing: insert into user (id, name, gender, birthday, address) values (?, ?, ?, ?, ?)
        ==>  Parameters: null, 郭德綱(String), 男(String), 1997-01-01(Date), null
         */
    }

    /**
     * 修改非空字段
     */
    @Test
    public void testUpdateByPrimaryKeySelective() {
        userMapper.updateByPrimaryKeySelective(new User(1, "周華健", "男", null, null));
        /*
        ==>  Preparing: update user SET name = ?, gender = ? where id = ?
        ==>  Parameters: 周華健(String), 男(String), 1(Integer)
         */
    }

    /**
     * 修改所有
     */
    @Test
    public void testUpdateByPrimaryKey() {
        userMapper.updateByPrimaryKey(new User(1, "周華健", "男", null, null));
        /*
        ==>  Preparing: update user set name = ?, gender = ?, birthday = ?, address = ? where id = ?
        ==>  Parameters: 周華健(String), 男(String), null, null, 1(Integer)
         */
    }

    /**
     * 指定條件批量刪除
     */
    @Test
    public void testDeleteByExample() {
        UserExample userExample = new UserExample();
        // 刪除名字中包含郭字的記錄
        userExample.createCriteria().andNameLike("%郭%");
        userMapper.deleteByExample(userExample);
        /*
        ==>  Preparing: delete from user WHERE ( name like ? )
        ==>  Parameters: %郭%(String)
         */
    }

    /**
     * 根據主鍵刪除
     */
    @Test
    public void testDeleteByPrimaryKey() {
        userMapper.deleteByPrimaryKey(10);
        /*
        ==>  Preparing: delete from user where id = ?
        ==>  Parameters: 10(Integer)
         */
    }

    /**
     * 條件查詢記錄條數
     */
    @Test
    public void testCountByExample() {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andNameLike("%周%");
        long l = userMapper.countByExample(userExample);
        System.out.println(l);
        /*
        ==>  Preparing: select count(*) from user WHERE ( name like ? )
        ==>  Parameters: %周%(String)
         */
    }
}
相關文章
相關標籤/搜索