The integration method of two popular frameworks Spring and Mybatis

Integrated approach

  • New maven project

  • Introduce dependency packages

  • Configuration resource file

Case practice

New maven project

New maven project spring_mybatis

The directory structure is as follows:

Home directory package:

Com.xxx.dao 、

​ com.xxx.mapper、

​ com.xxx.service、

​ com.xxx.service.impl

Test package: spring_mybatis

Introduce dependency packages

Open pom.xml and start adding dependency packages

<?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.xxx</groupId>
  <artifactId>test-xxxms</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>test-xxxms</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- spring 核心jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring 测试jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring事物 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- c3p0 连接池 -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</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.39</version>
    </dependency>

    <!-- 日志打印相关的jar -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.2</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.2</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>tpl-web</finalName>

    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

Configuration resource file

​ a) Spring file spring.xml

​ b) Mybatis file mybatis.xml

​ c) Database connection properties file db.properties

​ d) Log output file log4j.properties

spring.xml file configuration

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:component-scan base-package="com.xxx"/>

    <context:property-placeholder location="db.properties"/>

    <tx:annotation-driven  transaction-manager="txManager"/>

    <!-- 配置c3p0 数据源  -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


<!--  整合 框架(Spring与Mybatis)  -->

    <!-- 配置 sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 框架的配置文件 -->
        <property name="configLocation" value="classpath:mybatis.xml" />
        <!-- 映射文件 -->
        <property name="mapperLocations" value="classpath:com/xxx/dao/mapper/*.xml" />
    </bean>

    <!-- 配置扫描器 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描com.xxx.dao这个包以及它的子包下的所有映射接口类 -->
        <property name="basePackage" value="com.xxx.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>


</beans>

mybatis.xml file configuration

<?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>

    <!--别名的配置  每个人必须会 -->
    <typeAliases>
        <package name="com.xxx.model"/>
    </typeAliases>

</configuration>
 

db.properties file configuration (for other data source property configuration, see c3p0 configuration explanation, here default property configuration is used)

Create a database mybatis ( note that the database, user name and password are subject to your own local database )

jdbc.driver=com.mysql.jdbc.Driver 

jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding= 

utf8 

jdbc.username=root 

jdbc.password= 

log4j.properties

Convenient for console log output

# Global logging configuration 
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 

Expand

Start writing helloworld

User entity class definition

public class User {
    
     

    private int id; 

    private String userName; 

    private String userPwd; 

    public int getId() {
    
     

    	return id; 

    } 

    public void setId(int id) {
    
     

    	this.id = id; 

    } 

    public String getUserName() {
    
     

    	return userName; 

    } 

    public void setUserName(String userName) {
    
     

    	this.userName = userName; 

    } 

    public String getUserPwd() {
    
     

    	return userPwd; 

    } 

    public void setUserPwd(String userPwd) {
    
     

    	this.userPwd = userPwd; 

    } 

    @Override 

    public String toString() {
    
     

    	return "User [id=" + id + ", userName=" + userName + ", userPwd=" 

    \+ userPwd + "]"; 

    } 

} 

UseDao interface and mapping file definition

UserDao interface

public interface UserDao {
    
     

	public User queryUserById(int id); 

} 

UserMapper.xml ( Note: At this time, the mapping file namespace definition must comply with the rules: interface package name . interface class

Name , otherwise the cards are not played according to the rules, the test will report an error, and then you will be trapped! ! ! )

<?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.xxx.dao.UserDao"> 

<select id="queryUserById" parameterType="int" resultType="user"> 

	select id,userName,userPwd from user where id=#{id}  

</select> 

</mapper> 

UserService interface class and implementation class definition

public interface UserService {
    
     

	public User queryUserById(); 

} 

UserServiceImpl implementation class ( inject our UserDao interface directly at this time , and then call directly

The method, the matter is here, only one step away from success! )

@Service 

public class UserServiceImpl implements UserService{
    
     

    @Resource 

    private UserDao userDao; 

    public User queryUserById(){
    
     

    	return userDao.queryUserById(7);  

    } 

} 

junit test

Because of the integration with spring framework, we use spring framework to test spring Test

@RunWith(SpringJUnit4ClassRunner.class) 

@ContextConfiguration(locations = {
    
    "classpath:spring.xml"} ) 

public class TestSpringMybatis {
    
     

    @Autowired 

    private UserService userService; 

    @Test 

    public void testQueryUserById() {
    
     

    	System.out.println(userService.queryUserById(1)); 

    } 

} 

Result output


Insert picture description here

Guess you like

Origin blog.csdn.net/xyx12321/article/details/111563139