❤️ — Spring from introduction to God -- Spring integrates MyBatis

Keywords: Java Maven Mybatis Spring


The persistence layer framework used before is Mybatis. Now Mybatis framework is integrated into Spring framework and managed by Spring. Its core idea is to store the implementation class objects corresponding to Mapper in IOC container

Overall idea:
1. Build the Mybatis framework in the original way
2. Build the Spring framework in the original way
3. Replace sqlMapConfig.xml and MyBatisUtils tool classes with MyBatisConfig configuration classes
4. Make specific modifications in the SpringConfig configuration class

Requirement: add a user's information to the database through Spring+Mybatis integration
Implementation steps:
1. Environmental construction
2. Write Dao and Service
3. Write configuration class
4. Test
The complete project structure is as follows:

1. Environment construction

1.1 import jar package

Here I use web projects

There is also a pom file for the maven project version

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


<dependencies>

  <!-- spring start -->

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

1.2. Configuration file


jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db1
jdbc.username=root
jdbc.password=1234

1.3. Creating databases and tables

CREATE TABLE USER(
uid VARCHAR(32) PRIMARY KEY,
username VARCHAR(50),
PASSWORD VARCHAR(32)
)

2. Write dao and service

2.1. Write dao interface

public interface UserMapper extends Mapper {
}

2.2. Write service interface

public interface UserService {
public User findByPrimaryKey(String uid);
public void insertUser(User user);
}

2.3. Service implementation class

@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public User findByPrimaryKey(String uid) {
return userMapper.selectByPrimaryKey(uid);
}
@Override
public void insertUser(User user) {
userMapper.insert(user);
}
}

3. Configuration class

3.1 spring configuration class

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

@Configuration
@ComponentScan(basePackages = {"com.czxy"})
@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(" j d b c . d r i v e r " ) p r i v a t e S t r i n g d r i v e r C l a s s ; @ V a l u e ( " {jdbc.driver}") private String driverClass; @Value(" jdbc.driver")privateStringdriverClass;@Value("{jdbc.url}")
private String url;
@Value(" j d b c . u s e r n a m e " ) p r i v a t e S t r i n g u s e r n a m e ; @ V a l u e ( " {jdbc.username}") private String username; @Value(" jdbc.username")privateStringusername;@Value("{jdbc.password}")
private String password;
//The data source uses a 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);
}
}

3.2,

  1. When configuring the session factory and integrating spring and MyBatis, obtain SqlSessionFactory through SqlSessionFactoryBean
    SqlSessionFactoryBean can only load mapper mapping files
    Mapper class needs to be loaded for annotation development, so mapper needs to be scanned
  2. Configure mapping scanner

@Configuration
public class MyBatisConfig {
/**
*Build a SessionFactory object. SessionFactory can create a Session object. Finally, use 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. Finally, you need to call getObject() to obtain the specific object
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//1.1 setting data source
factoryBean.setDataSource(dataSource);
//1.2 set alias package scanning
factoryBean.setTypeAliasesPackage("com.czxy.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 xmapper interfaces, create UserMapper and other objects, and store them in the IOC container
* @return
*/
@Bean
public MapperScannerConfigurer mapperScanner() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage("com.czxy.dao");
return configurer;
}
}

4. Test class

4.1. Mode 1: integrate Junit

@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("added");
}
}

Test result: user information was added successfully

4.2. Method 2: manually create a factory

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. Obtain 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("added");
}
}

Posted by subrata on Fri, 08 Oct 2021 03:45:42 -0700