【Spring】mybatis-spring

Mu Xin 2021-11-25 18:34:45
spring mybatis-spring mybatis spring

MyBatis-Spring Will help you to MyBatis The code is seamlessly integrated into Spring in . It will allow MyBatis Participate in Spring In the management of , Create mapper mapper and  SqlSession  And injected into the bean in , And will be Mybatis Exception converted to Spring Of  DataAccessException. Final , It can be done that the application code does not depend on MyBatis,Spring or MyBatis-Spring.

Spring 2.0 Only support iBatis 2.0. that , We just want to put MyBatis3 Add support to Spring 3.0 in . Unfortunately ,Spring 3.0 The development of MyBatis 3.0 It's over before the official release . because Spring The development team doesn't want to release an unpublished version of MyBatis Integration support for , If you want to get Spring Official support , Can only wait for the next release . Based on Spring Chinese vs MyBatis Interest in providing support ,MyBatis The community thinks , It's time to start bringing together contributors who are interested in participating , Will be right Spring Integration as MyBatis It's a community component of .

MyBatis-Spring The following version is required :

MyBatis-Spring MyBatis Spring Framework Spring Batch Java
2.0 3.5+ 5.0+ 4.0+ Java 8+
1.3 3.4+ 3.2.2+ 2.1+ Java 6+

1. install mybatis-spring

To use MyBatis-Spring modular , Just include... In the classpath  mybatis-spring-2.0.6.jar  Documents and related dependencies .

If you use Maven As a build tool , Only need to pom.xml Add the following code to :

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>

2. Quick start

Want to be with Spring Use it together MyBatis, Need to be in Spring Define at least two things in the context of the application :

  • One  SqlSessionFactory 
  • At least one data mapper class

stay MyBatis-Spring in , You can use  SqlSessionFactoryBean To create  SqlSessionFactory. To configure this factory bean, Just put the following code in Spring Of XML In profile :

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}
}

【 Be careful 】:SqlSessionFactory  Need one  DataSource( data source ). It can be arbitrary  DataSource, Just need and configure other Spring Just configure it like a database connection .

Suppose you define the following mapper Interface :

public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}

So you can go through  MapperFactoryBean  Add the interface to Spring in :

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

It should be noted that : The specified mapper class must It's an interface , Not the concrete implementation class . In this example , Specify by annotation SQL sentence , But it can also be used MyBatis Mapper's XML The configuration file .

After configuration , You can be like Spring Medium common bean Injection method , Inject the mapper into your business or service object .MapperFactoryBean  Will be responsible  SqlSession  Create and close . If used Spring The transaction function of , So when the transaction is completed ,session Will be committed or rolled back . Eventually, any exception will be converted to Spring Of  DataAccessException  abnormal .

Use Java The code is configured as follows :

@Configuration
public class MyBatisConfig {
@Bean
public UserMapper userMapper() throws Exception {
SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
return sqlSessionTemplate.getMapper(UserMapper.class);
}
}

To be called MyBatis Data method , Just one line of code :

public class FooServiceImpl implements FooService {
private final UserMapper userMapper;
public FooServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User doSomeBusinessStuff(String userId) {
return this.userMapper.getUser(userId);
}
}

3. example

Here is an example :

(1) Project structure

(2) Blog.java

package com.company.org.pojo;
import lombok.Data;
@Data
public class Blog {
private int id;
private String title;
private int readcount;
}

(3)BlogMapper.java

package com.company.org.mapper;
import com.company.org.pojo.Blog;
import java.util.List;
public interface BlogMapper {
public List<Blog> selectBlog();
}

(4)BlogMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.company.org.mapper.BlogMapper">
<select id="selectBlog" resultType="Blog">
select id, title, readcount from article limit 10;
</select>
</mapper>

(5)BlogMapperIpl.java

package com.company.org.mapper;
import com.company.org.pojo.Blog;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class BlogMapperIpl implements BlogMapper {
// In the original , All our operations are done with sqlSession To execute ;
// Now? , Of hi use SqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession){
this.sqlSession = sqlSession;
}
@Override
public List<Blog> selectBlog() {
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
return mapper.selectBlog();
}
}

(6)mybatis-config.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<!-- configuration Core profile -->
<configuration>
<typeAliases>
<typeAlias type="com.company.org.pojo.Blog" alias="Blog"/>
</typeAliases>
</configuration>

(7)spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- DataSource: Use Spring Data source replacement for Mybatis Configuration of -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/csdn_blog?useSSL=true&amp;userUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;failOverReadOnly=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- binding Mybatis The configuration file -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/company/org/mapper/*.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- Can only be injected with a constructor sqlSessionFactory, Because it doesn't have set Method -->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="blogMapper" class="com.company.org.mapper.BlogMapperIpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>

(8)MyTest.java

import com.company.org.mapper.BlogMapper;
import com.company.org.pojo.Blog;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.util.List;
public class MyTest {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
BlogMapper blogMapper = context.getBean("blogMapper", BlogMapper.class);
List<Blog> blogList = blogMapper.selectBlog();
for (Blog blog : blogList){
System.out.println(blog);
}
}
}

(9)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>org.example</groupId>
<artifactId>springProject-24</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
版权声明
本文为[Mu Xin]所创,转载请带上原文链接,感谢
https://javamana.com/2021/11/20211109101849615U.html

  1. Flink Handling Function Real War II: processfunction class, Java thread interview subject
  2. Oracle SQL injection summary
  3. [Java data structure] you must master the classic example of linked list interview (with super detailed illustration and code)
  4. Record a java reference passing problem
  5. spring JTA 關於异常處理的時機問題
  6. Java - Set - Map (double file) - dija Rewriting, 2021 Java Developer's Performance Optimization
  7. Android入门教程 | OkHttp + Retrofit 取消请求的方法
  8. Java 8 Stream API and common methods, Java Junior Program interview
  9. Github 疯传!史上最强!BAT 大佬,2021年最新Java大厂面试笔试题分享
  10. git(3)Git 分支,zookeeper下载教程
  11. Java Backend Internet 500 questions d'entrevue moyennes et avancées (y compris les réponses), technologie de crochet Linux
  12. Entretien d'entretien d'usine Java post sprint de 100 jours - accumulation de jours et de mois, trois questions par jour [jour 12, fonction de principe de Zookeeper
  13. Tutoriel Java - reflection, tutoriel de téléchargement mongodb
  14. How to analyze several common key and hot issues in redis from multiple dimensions
  15. GIT (3) GIT Branch, Zookeeper Download tutoriel
  16. Tutoriel de démarrage Android | okhttp + Retrofit comment annuler une demande
  17. Design pattern [3.3] - Interpretation of cglib dynamic agent source code
  18. Share the actual operation of private collection project nodejs backend + Vue + Mysql to build a management system
  19. Springboot has 44 application initiators
  20. GitHub上霸榜久居不下的《Java面试突击宝典》,java图形用户界面设计基础
  21. GitHub上访问下载破百万的神仙文档《Java面试神技》看完我呆了,java面试问项目中遇到的问题
  22. GitHub上标星75k 超牛的《Java面试突击版,java高级工程师技能
  23. GitHub上标星2,java项目开发实训教程
  24. Docker development environment Preview
  25. JavaScript高級深入淺出:掌握 this 指向
  26. JavaScript Advanced Insight and outside: Mastering this direction
  27. Vue de l'application pratique de Javascript, drop drag Event
  28. docker 安装部署 Jenkins 2.322
  29. kafka安装
  30. 近九万字图文详解RabbitMQ
  31. Engaged in Java for one and a half years, how to break through yourself
  32. 输出9*9乘法表----java
  33. 判断一个数是不是素数-------java
  34. java项目,记录页面修改值,内部打“官司”用
  35. Docker installation Deployment Jenkins 2.322
  36. Comment porter un pantalon en hiver? Les petits hommes, les jambes épaisses et la largeur de l'entrejambe peuvent être vus. 3 techniques pour éviter la foudre
  37. MySQL下载和安装教程
  38. In depth analysis of rocketmq source code - message storage module
  39. Spring transaction management
  40. mysql恢复ibd数据,为何频频报错?
  41. [skills with annual salary of 60W] after working for 5 years, do you really understand netty and why to use it? (deep dry goods)
  42. Pourquoi MySQL récupère - t - il fréquemment les données ibd?
  43. Tutoriels de téléchargement et d'installation MySQL
  44. In IntelliJ idea, develop a fishing and reading plug-in
  45. Talk about how to integrate SPI with spring
  46. 重学Spring系列之Swagger2.0和Swagger3.0
  47. Hadoop05【命令操作】,Java400道面试题通关宝典助你进大厂
  48. Guava Cache缓存设计原理,java基础入门
  49. Gson:GitHub 标星 18K 的 JSON 解析器,Google 出品的 Java JSON 解析器
  50. gRPC学习之六:gRPC-Gateway集成swagger,java语言程序设计与数据结构进阶版
  51. Projet Java, enregistrer la valeur de modification de la page, utilisé pour les litiges internes
  52. Déterminer si un nombre est un nombre premier - - Java
  53. Sortie 9 * 9 tableau de multiplication - Java
  54. Plusieurs façons de réinitialiser le déplacement du Groupe de consommateurs Kafka
  55. GRPC Learning six: GRPC Gateway Integrated Swagger, Java language programming and data structure Advanced Edition
  56. python数据结构:数组、列表、栈、队列及实现
  57. Gson: json Parser for github Star 18k, Java json Parser from Google
  58. Principes de conception du cache Guava, Introduction à la base Java
  59. Un pantalon beige = élégant, blanc + haut de gamme, si beau cet hiver!
  60. Hadoop05 【 commande 】, Java 400 questions d'entrevue pour vous aider à entrer dans l'usine