Spring MVC+MyBatis+Spring+maven Integration

Keywords: Mybatis MySQL xml Java

Links to the original text: https://my.oschina.net/u/1590001/blog/268237

1. First step. Deploy mybatis;

1.1 Download myBatis

MyBits predecessor is iBitis, which is a semi-automated ORM framework relative to Hibernate. Because of the strict performance requirements of the boss, I had to abandon my dear hibernate to learn and use mybatis. Before that, I was not familiar with mybatis. If there are any mistakes, please correct them. I hope it will be helpful for my classmates who want to learn mybitis.
Given that my test database is mysql, my colleagues now install mysql, then prepare the MySQL driver and download mybitis( http://code.google.com/p/mybatis/).  

I used maven. I wrote it directly in the pom file.


        <!-- db -->
        <!-- join mysql Driver dependency packages -->

2. New Data Table

CREATE TABLE `t_test` (
  `id` int(11) NOT NULL,
  `userName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)

-- ----------------------------
-- Records of t_test
-- ----------------------------
INSERT INTO `t_test` VALUES ('1', '2');

3. use mybatis-generator Automatically generate code

Create a configuration file, such as conf.xml, where the name of the file is named by itself. There is no special requirement for naming. You can refer to the configuration file in the doc document. My name is as follows

<?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">
    <!-- Database Driven Package Location -->
    <!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> -->
    <classPathEntry location="E:\data\.m2\repository\mysql\mysql-connector-java\5.1.25\mysql-connector-java-5.1.25.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
            <property name="suppressAllComments" value="true" />
        <!-- Database Links URL,User name, password -->
         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/c_sai" userId="root" password=""> 
        <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->
            <property name="forceBigDecimals" value="false" />
        <!-- Package name and location of the generated model -->
        <javaModelGenerator targetPackage="com.test.model" targetProject="F:\source">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        <!-- Generated mapping file package name and location -->
        <sqlMapGenerator targetPackage="com.test.mapping" targetProject="F:\source">
            <property name="enableSubPackages" value="true" />
        <!-- generate DAO The package name and location of -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.dao" targetProject="F:\source">
            <property name="enableSubPackages" value="true" />
        <!-- To generate those tables(change tableName and domainObjectName Can) -->
        <table tableName="t_test" domainObjectName="TTest" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> 

Executing jar files

E:\data\Users\Administrator\Downloads\generator> java -jar mybatis-generator-cor
e-1.3.2.jar -configfile  generator.xml -overwrite
MyBatis Generator finished successfully.

The generated code is as follows

package com.test.model;

public class TTest {
    private Integer id;

    private String username;

    public Integer getId() {
        return id;

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

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();


package com.test.dao;

import com.test.model.TTest;

public interface TTestMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TTest record);

    int insertSelective(TTest record);

    TTest selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(TTest record);

    int updateByPrimaryKey(TTest record);


XML is as follows

<?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.test.dao.TTestMapper" >
  <resultMap id="BaseResultMap" type="com.test.model.TTest" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="userName" property="username" jdbcType="VARCHAR" />
  <sql id="Base_Column_List" >
    id, userName
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    <include refid="Base_Column_List" />
    from t_test
    where id = #{id,jdbcType=INTEGER}
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_test
    where id = #{id,jdbcType=INTEGER}
  <insert id="insert" parameterType="com.test.model.TTest" >
    insert into t_test (id, userName)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR})
  <insert id="insertSelective" parameterType="com.test.model.TTest" >
    insert into t_test
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
      <if test="username != null" >
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
      <if test="username != null" >
  <update id="updateByPrimaryKeySelective" parameterType="com.test.model.TTest" >
    update t_test
    <set >
      <if test="username != null" >
        userName = #{username,jdbcType=VARCHAR},
    where id = #{id,jdbcType=INTEGER}
  <update id="updateByPrimaryKey" parameterType="com.test.model.TTest" >
    update t_test
    set userName = #{username,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}


Write mybatis configuration file


<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE configuration  
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://" />
                <property name="username" value="root" />
                <property name="password" value="" />
         <mapper resource="com\test\mapping\TTestMapper.xml" />

Writing test classes

package com.jefry;

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

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 com.test.model.TTest;

public class Test {
    static String resource = "mybatis-config.xml";

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // User.selectUser in User Corresponding UserMapper.xml Document label<mapper
            // namespace="com.test.dao.TTestMapper"> namespace Value
            // selectUser Corresponding UserMapper.xml Document label<select id="selectUser"
            // parameterType="int" resultType="com.jefry.User">in id value
            TTest tt = session.selectOne("com.test.dao.TTestMapper.selectByPrimaryKey", 1);
            System.out.println("tt.getName()=" + tt.getUsername());
        } finally {





So far mybatis has been deployed successfully.











Reproduced in: https://my.oschina.net/u/1590001/blog/268237

Posted by nihal on Mon, 30 Sep 2019 16:43:19 -0700