Build a Spring project and integrate MyBatis

Build a Spring project

  • Step one:

  • Step two:

  • Step three:

  • Step four:

  • Step five:

  • Step six:

  • Step seven:

  • Final directory structure

2. Integrate MyBatis

2.1 import pom dependency:

Import pom related dependencies. See the pom file at the end of the blog

2.2 configuration file

jdbc.driver=com.mysql.jdbc.Driver
# Database address
jdbc.url=jdbc:mysql://127.0.0.1:3306/springday01
# mysql account
jdbc.username=root
# mysql password
jdbc.password=root

2.3 creating databases and tables

create database springday01;
use springday01;
CREATE TABLE USER(
 uid VARCHAR(32) PRIMARY KEY,
 username VARCHAR(50),
 PASSWORD VARCHAR(32)
)

2.4 write domain

  • Create User class

  • Add get and set methods
package com.zqh.domain;

import javax.persistence.Table;
import java.io.Serializable;

/**
 * @author Diffuse Road
 */
@Table(name = "user")
public class User implements Serializable {
    private String uid;
    private String username;
    private String password;

    public User() {
    }

    public User(String uid, String username, String password) {
        this.uid = uid;
        this.username = username;
        this.password = password;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

2.5. Write dao

package com.zqh.dao;

import com.zqh.domain.User;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author Diffuse Road
 */
public interface UserMapper extends Mapper<User> {
}

2.6. Write service interface

package com.zqh.service;

import com.zqh.domain.User;

/**
 * @author Diffuse Road
 */
public interface UserService {
    public User findByPrimaryKey(String uid);
    public void insertUser(User user);
}

2.6. Write service implementation class

package com.zqh.service.impl;

import com.zqh.dao.UserMapper;
import com.zqh.domain.User;
import com.zqh.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Diffuse Road
 */
@Service
@Transactional //Turn on transaction support
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    public User findByPrimaryKey(String uid) {
        return userMapper.selectByPrimaryKey(uid);
    }

    public void insertUser(User user) {
        userMapper.insert(user);
    }
}

2.7. Write Spring configuration class

1. Configuration notes
	1.1 scan annotation package
	1.2 loading properties file
	1.3 enable annotation transaction support
 2. Get the properties data (implementation class, @ Value)
3. Configure data source
 4. Configure the transaction manager (DataSourceTransactionManager)

package com.zqh.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;


/**
 * @author Diffuse Road
 */
@Configuration
@ComponentScan(basePackages = {"com.zqh"})
@EnableTransactionManagement
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {
    // 4.2.4 version fixed configuration
    @Bean
    public static PropertySourcesPlaceholderConfigurer create(){
        return  new PropertySourcesPlaceholderConfigurer();
    }

    //Read database related configuration
    @Value("${jdbc.driver}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    //Data source uses Druid connection pool
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClass);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    // Open transaction manager
    @Bean
    @Resource
    public DataSourceTransactionManager txManager(DataSource dataSource){
        return  new DataSourceTransactionManager(dataSource);
    }

}

2.8. Write MyBatis configuration class

1. Configure the session factory. When spring and MyBatis are integrated, obtain SqlSessionFactory through SqlSessionFactoryBean
	SqlSessionFactoryBean can only load mapper mapping files
	Annotation development needs to load mapper class, so mapper needs to be scanned
 2. Configure the mapping scanner
package com.zqh.config;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Spring Integrating the configuration classes of MyBatis
 * @author Diffuse Road
 */
// statement
@Configuration
public class MyBatisConfig {

    /**
     * Build the SessionFactory object. The SessionFactory can create the Session object, and finally use the Session to operate the database
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    @Resource
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        // 1. Create the object through the factory bean, and finally call getObject() to get the specific object
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 1.1 set data source
        factoryBean.setDataSource(dataSource);
        // 1.2 setting alias package scanning
        factoryBean.setTypeAliasesPackage("com.zqh.domain");
        // 1.3 global configuration: hump mapping
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(config);

        // 2 plug in configuration
        // 2.1 paging plug in
        PageHelper pageHelper = new PageHelper();
        Properties pageProps = new Properties();
        pageProps.setProperty("dialect", "mysql");
        pageProps.setProperty("rowBoundsWithCount", "true");
        pageHelper.setProperties(pageProps);
        factoryBean.setPlugins(new Interceptor[]{pageHelper});

        // 3. Obtain sqlSessionFactory through the factory bean
        return factoryBean.getObject();
    }

    /**
     * Scan Dao's package, find various interfaces of XxxMapper, create UserMapper and other objects and store them in IOC container
     *
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScanner() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.zqh.dao");
        return configurer;
    }

}

2.9. Write test class

Mode 1: integrate Junit

package com.zqh;


import com.zqh.config.MyBatisConfig;
import com.zqh.config.SpringConfig;
import com.zqh.domain.User;
import com.zqh.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class, MyBatisConfig.class})
public class TestA {


    @Resource
    private UserService userService;

    @Test
    public void test01(){
        User user = new User("u001","Zhang Sanfeng","123");
        userService.insertUser(user);
        System.out.println("Add up");
    }
}

  • Function

  • Console printing

  • data base

Mode 2: create factory manually

package com.zqh;

import com.zqh.config.MyBatisConfig;
import com.zqh.config.SpringConfig;
import com.zqh.domain.User;
import com.zqh.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestB {
    public static void main(String[] args) {
        //1. Create a factory and set two configuration classes
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class, MyBatisConfig.class);
        //2. Get the required objects from the factory
        UserService userService = applicationContext.getBean(UserService.class);
        //3. Execute statement
        User user = new User("u800","zhangsan","123");
        userService.insertUser(user);
        System.out.println("Add up");
    }
}
  • Execute main method

Appendix pom document

<properties>
        <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <!--spring core start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring core end-->

        <!--spring aop start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spirng aop end-->

        <!--spring aspects start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring aspects end-->

        <!--spring instrumentation start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring instrumentation end-->

        <!--spring messaging start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring messaging end-->

        <!--spring data access start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring data access end-->

        <!--spring web start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring web end -->

        <!--spring test start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <!--spring test end -->
        <!-- spring end -->


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>3.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

    </dependencies>

Tags: Programming Spring Mybatis JDBC MySQL

Posted on Sat, 14 Mar 2020 10:53:38 -0400 by Rabioza123