3, spring integrates MyBatis
-
Official download address
-
Video viewing address
https://www.bilibili.com/video/BV1nz4y1d7uy
Integrating MyBatis with Spring mainly solves the problem of handing over SqlSessionFactory objects to Spring for management
You only need to register the SqlSessionFactoryBean, the object generator of SqlSessionFactory, in the Spring container, and then inject it into Dao's implementation class to complete the integration
Integration ideas
A proxy object with Dao interface is required. For example, studentDao needs a proxy object, using sqlsession Getmapper (studentDao. Class) to get the Dao proxy object
SqlSessionFactory is required. Create a SqlSessionFactory object and use SqlSessionFactory SqlSession object obtained by open()
Data source DataSource object, replace mybatis's own PooledDataSource with a connection pool object
3.1 maven dependency
maven dependency
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.1</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><!--Directory where--> <includes><!--Including the.properties,.xml All files will be scanned--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
3.2 entity class
- Define entity classes
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer id; private String name; private String email; private Integer age; }
3.3 Dao interface and mapper file
- Dao interface
public interface StudentDao { int insertStudent(Student student); List<Student> selectStudentList(); }
- mapper file
<?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.jjh.dao.StudentDao"> <insert id="insertStudent"> insert into student values (#{id},#{name},#{email},#{age}) </insert> <select id="selectStudentList" resultType="com.jjh.domain.entity.Student"> select * from student order by id desc </select> </mapper>
3.4 service interface and implementation class
- service interface
public interface StudentService { int addStudent(Student student); List<Student> queryAllStudents(); }
- service implementation class
@Service("myStudentService") public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public int addStudent(Student student) { int result = studentDao.insertStudent(student); return result; } @Override public List<Student> queryAllStudents() { List<Student> students = studentDao.selectStudentList(); return students; } }
3.5 MyBatis master profile
The configuration of the data source is no longer needed in the main configuration file, because the data source will be managed by the Spring container
Here, the < package / > label is used to register the mapper mapping file, that is, only the package where the mapper mapping file is located needs to be given, because the mapper name is the same as the Dao interface name, so this simple registration method can be used. The advantage of this method is that if there are multiple mapping files, the configuration here does not need to be changed. Of course, you can also use the original < resource / > label
<?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: control mybatis Global behavior--> <settings> <!--set up mybatis Output log--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--Set alias--> <typeAliases> <!--Entity class alias--> <!-- package:Use all class names under the package as aliases name:Package name of entity class --> <package name="com.jjh.domain.entity"/> </typeAliases> <!-- sql mapper(sql Mapping file)Location of--> <mappers> <!-- package:appoint Dao Location of interface package,Indicates that the sql Mapping file found name:Dao Package name of the interface use package Specify the requirements for the mapping file: 1.sql Mapped file name and Dao Consistent interface name 2.sql Mapping files and Dao Interfaces in the same directory --> <package name="com.jjh.dao"/> </mappers> </configuration>
3.6 spring configuration file
- jdbc.properties file
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis01?serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=123456
To be read by the Spring configuration file, the property file must be registered in the configuration file. Use < context > tag
< context: Property placeholder / > there is a property location in the tag, which is used to specify the location of the property file
- Register SqlSessionFactoryBean
<!--The statement is mybatis Provided in SqlSessionFactoryBean Class, which is created internally SqlSessionFactory of SqlSessionFactory sqlSessionFactory = new .. --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--set Injection, paying the database connection pool dataSource attribute--> <property name="dataSource" ref="myDataSource" /> <!--mybatis Location of the master profile configLocation Property is Resource Type, read configuration file Its assignment, using value,Specify the path to the file, using classpath:Indicates the location of the file --> <property name="configLocation" value="classpath:mybatis.xml" /> </bean>
- Define Mapper scan configurator MapperScannerConfigurer
mapper scan configurator mappercannerconfigurer will automatically generate the proxy object of mapper in the specified basic package. The Bean does not need to set the id property. basePackage sets multiple packages with semicolons or commas
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--appoint SqlSessionFactory Object id--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!--Specify the package name, which is dao The package name of the interface. MapperScannerConfigurer It will scan all interfaces in the package and execute each interface once getMapper()Method to get the of each interface dao Object. Created dao Object into spring In the container. dao The default name of an object is the lowercase initial of the interface name --> <property name="basePackage" value="com.jjh.dao"/> </bean>
3.7 inject interface name into service
When injecting Mapper proxy objects into the Service, it should be noted that since the Mapper proxy objects generated through Mapper scan configurator mappercannerconfigurer do not have names, when injecting Mapper proxy objects into the Service, they cannot be injected by names. However, it can be injected through the simple class name of the interface, because the generated object is the object of the Dao interface.
- All profiles
<context:component-scan base-package="com.jjh.service"/> <!-- Write the configuration information of the database in an independent file, compile and modify the configuration content of the database spring know jdbc.properties File location --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--Declare data source DataSource,The function is to connect to the database--> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!--set injection--> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="20"/> </bean> <!--The statement is mybatis Provided in SqlSessionFactoryBean Class, which is created internally SqlSessionFactory of SqlSessionFactory sqlSessionFactory = new .. --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--set Injection, paying the database connection pool dataSource attribute--> <property name="dataSource" ref="myDataSource" /> <!--mybatis Location of the master profile configLocation Property is Resource Type, read configuration file Its assignment, using value,Specify the path to the file, using classpath:Indicates the location of the file --> <property name="configLocation" value="classpath:mybatis.xml" /> </bean> <!--establish dao Objects, using SqlSession of getMapper(StudentDao.class) MapperScannerConfigurer:Call internally getMapper()Generate each dao Proxy object for the interface. --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--appoint SqlSessionFactory Object id--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!--Specify the package name, which is dao The package name of the interface. MapperScannerConfigurer It will scan all interfaces in the package and execute each interface once getMapper()Method to get the of each interface dao Object. Created dao Object into spring In the container. dao The default name of an object is the lowercase initial of the interface name --> <property name="basePackage" value="com.jjh.dao"/> </bean> </beans>