Spring integration of Mybatis taste

  For beginners, record the process of learning to integrate the two frameworks. There are also many pits that have been stepped on and problems that have not been solved. Record them first. Awaiting resolution.

Without further ado, let's get started. First on the pom.xml configuration file.

This is my pom.xml

<?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>Sping_Mybatis</groupId>
    <artifactId>spring_mybatis_test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency><!-- Spring's simple encapsulation of the test framework -->
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.0.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- datasource-->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.8</version>
        </dependency>

        <!-- Mybatis3.4.1 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!-- spring integration mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!-- Spring-4.2.0 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

</project>

  Paste a picture of the project directory

Let's look at the configuration of mybatisConfig.xml

  The data source is in the spring configuration file, and the automatic scan Mapper is configured in the spring file. Therefore, there is no need to write the content in <mappers> again.

<?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>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <typeAliases>
        <typeAlias type="com.lpp.test.entity.Car" alias="car"/>
    </typeAliases>
    <!--<mappers>
        <mapper url="config/sqlMapper/CarMapper.xml"/>
    </mappers>-->
</configuration>

  At this point, let's look at the configuration of spring_mybatis.xml. There is a problem that has not been solved for the time being. After putting jdbc.properties in the resource directory, the introduction fails in the spring configuration. When configuring the data source, the variable is invalid, and the problem has not been solved for the time being, so let's put it here first. Wait for it to come back later. The configuration is very simple, that is, test use.

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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:component-scan base-package="com.lpp.test"/>
    <!--<context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>-->
    <!--Configure data source-->
    <bean id="dataSource"
          class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
          p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/test"
          p:username="root"
          p:password=""
    /><!--${driverClasss}${jdbcUrl}${username}com.mysql.jdbc.Driver-->

    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:config/mybatisConfig.xml"
          p:mapperLocations="classpath:config/sqlMapper/*.xml"/>
    <!--The SQLSessionTemplate provided by spring is used here-->
    <bean class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"/>
    </bean>

    <!-- Scanning directly uses mapper interface class to operate dao, and directly incorporates IOC container management-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:sqlSessionFactory-ref="sqlSessionFactory"
          p:basePackage="com.lpp.test.dao">
    </bean>
</beans>

  Next is the configuration of Mapper.xml. The effects of the three configurations are almost the same, but the writing methods are not the same. Compared with the carMapper interface, we know that there are three methods.

<?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.lpp.test.dao.carMapper">
    <select id="findCarbyId" parameterType="int" resultType="Car">
        SELECT id,car_name AS carName,maxSpeed FROM t_car WHERE id = #{id}
    </select>
    <select id="findCarbyIdAndName" resultType="Car">
        SELECT * FROM t_car WHERE id = #{id} AND car_name = #{car_name};
    </select>
    <select id="findCarbyIdAndSpeed" resultType="Car">
        SELECT * FROM t_car WHERE id = #{id} AND maxSpeed = #{maxSpeed};
    </select>
</mapper>

  carMapper interface

package com.lpp.test.dao;

import com.lpp.test.entity.Car;
import org.apache.ibatis.annotations.Param;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lpp
 * Date: 2018-04-17
 * Time: 19:44
 */
public interface carMapper {
    public Car findCarbyId(int id);
    public Car findCarbyIdAndName(@Param("id") int id, @Param("car_name") String car_name);
    public Car findCarbyIdAndSpeed(Car car);
}

  

  Paste the configuration of log4j.properties

# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  Entity car.java under entity

package com.lpp.test.entity;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lpp
 * Date: 2018-04-16
 * Time: 11:06
 */
public class Car {
    int id;
    String carName;
    int maxSpeed;

    public Car() {
    }

    public Car(int id, String carName, int maxSpeed) {
        this.id = id;
        this.carName = carName;
        this.maxSpeed = maxSpeed;
    }

    public int getId() {
        return id;
    }


    public String getCarName() {
        return carName;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

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

    public void setName(String car_name) {
        this.carName = carName;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", name='" + carName + '\'' +
                ", maxSpeed=" + maxSpeed ​​+
                '}';
    }
}

  Finally, the test method, I created a test method and a main method test, the codes are as follows.

test method

package com.lpp.test.dao;

import com.lpp.test.entity.Car;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lpp
 * Date: 2018-04-27
 * Time: 17:36
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/spring-mybatis.xml")
public class carMapperTest {
    @Autowired
    carMapper carMapper;
    @Test
    public void findCarbyIdAndName() {
        Car car = carMapper.findCarbyIdAndName(1,"aodi");
        System.out.println(car);
    }
}

  main method

package com.lpp.test.main;

import com.lpp.test.dao.carMapper;
import com.lpp.test.entity.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lpp
 * Date: 2018-04-25
 * Time: 17:44
 */
public class testMain {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("config/spring-mybatis.xml");
        carMapper carMapper = ctx.getBean(com.lpp.test.dao.carMapper.class);

        Car car = null;
        car = carMapper.findCarbyId(1);
        System.out.println(car.toString());
    }
}

  The results of the two test methods are the same, calling different query functions. The above are the steps I took to do the integration. When I tried it for the first time, it was inevitable that there would be some problems. I hope everyone can gain something.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061954&siteId=291194637