目录
将 MyBatis与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合
实现 Spring 与 MyBatis 的整合常用的方式:扫描的 Mapper 动态代理
完整的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>com.md</groupId> <artifactId>06-spring-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- 单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--spring核心--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--spring事务用到的--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--mybatis的--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!--mybatis和spring集成的--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!--德鲁伊,数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> </dependencies> <build> <!--目的是把src/main/java目录中的xml文件包含到输出结果中,也就是输出到classes目录中--> <resources> <resource> <directory>src/main/java</directory><!--所在的目录--> <includes><!--包括目录下的.properties,.xml 文件都会扫描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
package com.md.domain; /** * @author MD * @create 2020-08-09 20:02 */ public class Student { // 属性名和列名一样 private Integer id; private String name; private String email; private Integer age; public Student() { } public Student(Integer id, String name, String email, Integer age) { this.id = id; this.name = name; this.email = email; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", email='" + email + '\'' + ", age=" + age + '}'; } }
package com.md.dao; import com.md.domain.Student; import java.util.List; /** * @author MD * @create 2020-08-09 20:04 */ public interface StudentDao { int insertStudent(Student student); List<Student> selectStudents(); }
和dao在同一目录下,名字和dao接口的一样,StudentDao.xml
mapper 中的 namespace 取值也为 Dao 接口的全限定性名
<?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.md.dao.StudentDao"> <insert id="insertStudent"> insert into student values(#{id},#{name},#{email},#{age}) </insert> <select id="selectStudents" resultType="com.md.domain.Student"> select id,name,email,age from student </select> </mapper>
在 src /main/resources下定义 MyBatis 的主配置文件,命名为 mybatis.xml
注意:
<?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:控制mybatis全局行为--> <settings> <!--设置mybatis输出日志--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--设置别名--> <typeAliases> <!-- package:把包下面的所有类名作为别名 name:实体类所在的包名--> <package name="com.md.domain"/> </typeAliases> <!-- sql映射文件的位置 --> <mappers> <!--name是包名,这个包中所有mapper.xml一次加载--> <package name="com.md.dao"/> </mappers> </configuration>
package com.md.service; import com.md.domain.Student; import java.util.List; /** * @author MD * @create 2020-08-09 20:25 */ public interface StudentService { int addStudent(Student student); List<Student> queryStudent(); } //------------------------------------- package com.md.service.impl; import com.md.dao.StudentDao; import com.md.domain.Student; import com.md.service.StudentService; import java.util.List; /** * @author MD * @create 2020-08-09 20:27 */ public class StudentServiceImpl implements StudentService { // 引用类型 private StudentDao studentDao; // 为了使用set注入来赋值 public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; } @Override public int addStudent(Student student) { int i = studentDao.insertStudent(student); return i; } @Override public List<Student> queryStudent() { List<Student> studentList = studentDao.selectStudents(); return studentList; } }
在 src /main/resources下定义 Spring的主配置文件,命名为 applicationContext.xml
声明mybatis的对象交给spring创建
1. 数据源DateSource
使用 JDBC 模板,首先需要配置好数据源,数据源直接以 Bean 的形式配置在 Spring 配置文件中。根据数据源的不同,其配置方式不同:
这里使用的Druid,Druid 是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接池。Druid 能 够提供强大的监控和扩展功能
https://github.com/alibaba/druid
首先在pom.xml中加入依赖,上面添加过了
然后是在spring的配置文件中
<!--声明数据源DataSource,作用是连接数据库--> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!--set注入提供连接数据库信息--> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean>
为了维护方法方便,还可以使用属性文件
在在 src /main/resources下定义jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=123456 jdbc.maxActive=20
然后再spring的配置文件中
<!-- 把数据库的配置信息写在一个独立的文件中,编译修改数据库的配置内容 让spring知道jdbc.properties文件的位置 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--声明数据源DataSource,作用是连接数据库--> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 使用属性配置文件中的数据,语法 ${key} --> <property name="url" value="${jdbc.url}" /><!--setUrl()--> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean>
这样就可以了
2. 注册SqlSessionFactoryBean
<!--SqlSessionFactory--> <!--声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory--> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--set注入,把数据库连接池付给dataSource属性--> <property name="dataSource" ref="myDataSource"/> <!--mybatis主配置文件的位置 configLocation属性是Resource类型,读取配置文件 它的赋值使用的是value , 指定文件的路径,使用的是classpath:表示文件的位置 --> <property name="configLocation" value="classpath:mybatis.xml"/> </bean>
3. 定义 Mapper 扫描配置器 MapperScannerConfigurer
也就是创建dao对象
<!--创建 dao对象 使用SqlSession的getMapper(StudentDao.class) MapperScannerConfigurer在内部调用getMapper()生成每个dao接口的代理对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定的是SqlSessionFactory对象的id--> <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/> <!--指定包名,包名是dao接口所在的包名 MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行 一次getMapper()方法,得到每个接口的dao对象 创建好的dao对象放入到spring的容器中 dao默认对象的名称:是接口名字的首字母小写 --> <property name="basePackage" value="com.md.dao"/> <!--多个包--> <!--<property name="basePackage" value="com.md.dao,com.md.dao2"/>--> </bean>
4. 向 Service 注入接口名
<!--声明service--> <bean id="studentService" class="com.md.service.impl.StudentServiceImpl"> <!--就是上面通过创建的dao对象--> <property name="studentDao" ref="studentDao"/> </bean>
总:
Spring的配置文件
用的时候直接复制
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 把数据库的配置信息写在一个独立的文件中,编译修改数据库的配置内容 让spring知道jdbc.properties文件的位置 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--声明数据源DataSource,作用是连接数据库--> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!--set注入提供连接数据库信息--> <!--<property name="url" value="jdbc:mysql://localhost:3306/ssm" />--> <!--<property name="username" value="root" />--> <!--<property name="password" value="123456" />--> <!--<property name="maxActive" value="20" />--> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean> <!--SqlSessionFactory--> <!--声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory--> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--set注入,把数据库连接池付给dataSource属性--> <property name="dataSource" ref="myDataSource"/> <!--mybatis主配置文件的位置 configLocation属性是Resource类型,读取配置文件 它的赋值使用的是value , 指定文件的路径,使用的是classpath:表示文件的位置 --> <property name="configLocation" value="classpath:mybatis.xml"/> </bean> <!--创建 dao对象 使用SqlSession的getMapper(StudentDao.class) MapperScannerConfigurer在内部调用getMapper()生成每个dao接口的代理对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定的是SqlSessionFactory对象的id--> <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/> <!--指定包名,包名是dao接口所在的包名 MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行 一次getMapper()方法,得到每个接口的dao对象 创建好的dao对象放入到spring的容器中 dao默认对象的名称:是接口名字的首字母小写 --> <property name="basePackage" value="com.md.dao"/> <!--多个包--> <!--<property name="basePackage" value="com.md.dao,com.md.dao2"/>--> </bean> <!--上面的这个是一个模板,只有最后dao对象的这个包名的value的值是根据自己创建写的--> <!--下面的就是自己定义的service--> <!--声明service--> <bean id="studentService" class="com.md.service.impl.StudentServiceImpl"> <!--就是上面通过创建的dao对象--> <property name="studentDao" ref="studentDao"/> </bean> </beans>
@Test public void test03(){ ApplicationContext c = new ClassPathXmlApplicationContext("applicationContext.xml"); // 获取到了spring容器中的对象 StudentService studentService = (StudentService) c.getBean("studentService"); studentService.addStudent(new Student(1008,"冯宝宝","[email protected]",20)); // spring和mybatis整合在一起使用,事务是自动提交的 List<Student> studentList = studentService.queryStudent(); studentList.forEach(stu-> System.out.println(stu)); }
整体目录结构
原文链接:https://www.cnblogs.com/mengd/p/13493502.html