• Spring 集成 MyBatis-将对象交给spring管理。


    Spring 集成 MyBatis

    ​ 将 MyBatis 与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器SqlSessionFactoryBean 注 册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。

    ​ 实现 Spring 与 MyBatis 的整合常用的方式:

    扫描的 Mapper 动态代理 Spring 像插线板一样,mybatis 框架是插头,可以容易的组合到一起。插线板 spring 插 上 mybatis,两个框架就是一个整体。

    1.这里我们还是使用的是SSM数据库中的student表

    2. maven 依赖 pom.xml

    1. <dependency>
    2. <groupId>junitgroupId>
    3. <artifactId>junitartifactId>
    4. <version>4.11version>
    5. <scope>testscope>
    6. dependency>
    7. <dependency>
    8. <groupId>org.springframeworkgroupId>
    9. <artifactId>spring-contextartifactId>
    10. <version>5.2.5.RELEASEversion>
    11. dependency>
    12. <dependency
    13. <groupId>org.springframeworkgroupId>
    14. <artifactId>spring-txartifactId>
    15. <version>5.2.5.RELEASEversion>
    16. dependency>
    17. <dependency>
    18. <groupId>org.springframeworkgroupId>
    19. <artifactId>spring-jdbcartifactId>
    20. <version>5.2.5.RELEASEversion>
    21. dependency>
    22. <dependency>
    23. <groupId>org.mybatisgroupId>
    24. <artifactId>mybatisartifactId>
    25. <version>3.5.1version>
    26. dependency>
    27. <dependency>
    28. <groupId>org.mybatisgroupId>
    29. <artifactId>mybatis-springartifactId>
    30. <version>1.3.1version>
    31. dependency>
    32. <dependency>
    33. <groupId>mysqlgroupId>
    34. <artifactId>mysql-connector-javaartifactId>
    35. <version>5.1.9version>
    36. dependency>
    37. <dependency>
    38. <groupId>com.alibabagroupId>
    39. <artifactId>druidartifactId>
    40. <version>1.1.12version>
    41. dependency>
    42. <build>
    43. <resources>
    44. <resource>
    45. <directory>src/main/javadirectory>
    46. <includes>
    47. <include>**/*.propertiesinclude>
    48. <include>**/*.xmlinclude>
    49. includes>
    50. <filtering>falsefiltering>
    51. resource>
    52. resources>
    53. <plugins>
    54. <plugin>
    55. <artifactId>maven-compiler-pluginartifactId>
    56. <version>3.1version>
    57. <configuration>
    58. <source>1.8source>
    59. <target>1.8target>
    60. configuration>
    61. plugin>
    62. plugins>
    63. build>

    项目结构:

    3. 定义实体类 Student

    1. package com.bjpowernode.domain;
    2. public class Student {
    3. //属性名和列名一样。
    4. private Integer id;
    5. private String name;
    6. private String email;
    7. private Integer age;
    8. public Student() {
    9. }
    10. public Student(Integer id, String name, String email, Integer age) {
    11. this.id = id;
    12. this.name = name;
    13. this.email = email;
    14. this.age = age;
    15. }
    16. public Integer getId() {
    17. return id;
    18. }
    19. public void setId(Integer id) {
    20. this.id = id;
    21. }
    22. public String getName() {
    23. return name;
    24. }
    25. public void setName(String name) {
    26. this.name = name;
    27. }
    28. public String getEmail() {
    29. return email;
    30. }
    31. public void setEmail(String email) {
    32. this.email = email;
    33. }
    34. public Integer getAge() {
    35. return age;
    36. }
    37. public void setAge(Integer age) {
    38. this.age = age;
    39. }
    40. @Override
    41. public String toString() {
    42. return "Student{" +
    43. "id=" + id +
    44. ", name='" + name + '\'' +
    45. ", email='" + email + '\'' +
    46. ", age=" + age +
    47. '}';
    48. }
    49. }

    4.定义 StudentDao 接口

    1. package com.bjpowernode.dao;
    2. import com.bjpowernode.domain.Student;
    3. import java.util.List;
    4. public interface StudentDao {
    5. int insertStudent(Student student);
    6. List selectStudents();
    7. }

    5定义映射文件 mapper

    在 Dao 接口的包中创建 MyBatis 的映射文件 mapper,命名与接口名相同,本例为 StudentDao.xml。mapper 中的 namespace 取值也为 Dao 接口的全限定性名。

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.bjpowernode.dao.StudentDao">
    6. <insert id="insertStudent">
    7. insert into student values(#{id},#{name},#{email},#{age})
    8. insert>
    9. <select id="selectStudents" resultType="Student">
    10. select id,name,email,age from student order by id desc
    11. select>
    12. mapper>

    6定义 Service 接口和实现类

    1. //接口
    2. package com.bjpowernode.service;
    3. import com.bjpowernode.domain.Student;
    4. import java.util.List;
    5. public interface StudentService {
    6. int addStudent(Student student);
    7. List queryStudents();
    8. }
    9. //实现类
    10. package com.bjpowernode.service.impl;
    11. import com.bjpowernode.dao.StudentDao;
    12. import com.bjpowernode.domain.Student;
    13. import com.bjpowernode.service.StudentService;
    14. import java.util.List;
    15. public class StudentServiceImpl implements StudentService {
    16. //引用类型
    17. private StudentDao studentDao;
    18. //使用set注入,赋值
    19. public void setStudentDao(StudentDao studentDao) {
    20. this.studentDao = studentDao;
    21. }
    22. @Override
    23. public int addStudent(Student student) {
    24. int nums = studentDao.insertStudent(student);
    25. return nums;
    26. }
    27. @Override
    28. public List queryStudents() {
    29. List students = studentDao.selectStudents();
    30. return students;
    31. }
    32. }

    7定义 MyBatis 主配置文件

    在 src 下定义 MyBatis 的主配置文件,命名为 mybatis.xml。 这里有两点需要注意:

    (1)主配置文件中不再需要数据源的配置了。因为数据源要交给 Spring 容器来管理了。

    (2)这里对 mapper 映射文件的注册,使用标签,即只需给出 mapper 映射文件 所在的包即可。因为 mapper 的名称与 Dao 接口名相同,可以使用这种简单注册方式。这种 方式的好处是,若有多个映射文件,这里的配置也是不用改变的。当然,也可使用原来的 标签方式。

    1. "1.0" encoding="UTF-8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <settings>
    7. <setting name="logImpl" value="STDOUT_LOGGING"/>
    8. settings>
    9. <typeAliases>
    10. <package name="com.bjpowernode.domain"/>
    11. typeAliases>
    12. <mappers>
    13. <package name="com.bjpowernode.dao"/>
    14. mappers>
    15. configuration>

    8Spring 配置文件(重点)

    使用 JDBC 模板,首先需要配置好数据源,数据源直接以 Bean 的形式配置在 Spring 配 置文件中。根据数据源的不同,其配置方式不同:

    Druid 数据源 DruidDataSource

    Druid是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接池。Druid 能 够提供强大的监控和扩展功能。Druid 与其他数据库连接池的最大区别是提供数据库的

    官网:https://github.com/alibaba/druid 使用地址:https://github.com/alibaba/druid/wiki/常见问题

    • 据源的配置(掌握)

    • 从属性文件读取数据库连接信息

    • 注册 SqlSessionFactoryBean

    • 定义 Mapper 扫描配置器 MapperScannerConfigurer

      Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代 理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包。

    • 向 Service 注入接口名

      向 Service 注入 Mapper 代理对象时需要注意,由于通过 Mapper 扫描配置器 MapperScannerConfigurer 生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper 代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口 的对象。

    9 全局的配置文件如下:

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. 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">
    6. <context:property-placeholder location="classpath:jdbc.properties" />
    7. <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
    8. init-method="init" destroy-method="close">
    9. <property name="url" value="${jdbc.url}" />
    10. <property name="username" value="${jdbc.username}"/>
    11. <property name="password" value="${jdbc.passwd}" />
    12. <property name="maxActive" value="${jdbc.max}" />
    13. bean>
    14. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    15. <property name="dataSource" ref="myDataSource" />
    16. <property name="configLocation" value="classpath:mybatis.xml" />
    17. bean>
    18. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    19. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    20. <property name="basePackage" value="com.bjpowernode.dao"/>
    21. bean>
    22. <bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl">
    23. <property name="studentDao" ref="studentDao" />
    24. bean>
    25. beans>

    10,测试

    1. package com.bjpowernode;
    2. import com.bjpowernode.dao.StudentDao;
    3. import com.bjpowernode.domain.Student;
    4. import com.bjpowernode.service.StudentService;
    5. import org.junit.Test;
    6. import org.springframework.context.ApplicationContext;
    7. import org.springframework.context.support.ClassPathXmlApplicationContext;
    8. import java.util.List;
    9. public class MyTest {
    10. @Test
    11. public void test01(){
    12. String config="applicationContext.xml";
    13. ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
    14. String names[] = ctx.getBeanDefinitionNames();
    15. for(String na:names){
    16. System.out.println("容器中对象名称:"+na+"|"+ctx.getBean(na));
    17. }
    18. }
    19. @Test
    20. public void testDaoInsert(){
    21. String config="applicationContext.xml";
    22. ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
    23. //获取spring容器中的dao对象
    24. StudentDao dao = (StudentDao) ctx.getBean("studentDao");
    25. Student student = new Student();
    26. student.setId(1013);
    27. student.setName("zhoufeng");
    28. student.setEmail("zhoufeng@qq.com");
    29. student.setAge(20);
    30. int nums = dao.insertStudent(student);
    31. System.out.println("nums="+nums);
    32. }
    33. @Test
    34. public void testServiceInsert(){
    35. String config="applicationContext.xml";
    36. ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
    37. //获取spring容器中的dao对象
    38. StudentService service = (StudentService) ctx.getBean("studentService");
    39. Student student = new Student();
    40. student.setId(1015);
    41. student.setName("lishengli");
    42. student.setEmail("zhoufeng@qq.com");
    43. student.setAge(26);
    44. int nums = service.addStudent(student);
    45. //spring和mybatis整合在一起使用,事务是自动提交的。 无需执行SqlSession.commit();
    46. System.out.println("nums="+nums);
    47. }
    48. @Test
    49. public void testServiceSelect(){
    50. String config="applicationContext.xml";
    51. ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
    52. //获取spring容器中的dao对象
    53. StudentService service = (StudentService) ctx.getBean("studentService");
    54. List students = service.queryStudents();
    55. for (Student stu:students){
    56. System.out.println(stu);
    57. }
    58. }
    59. }
  • 相关阅读:
    三网91话费接口源码分享
    pg和oracle的区别
    027:vue中两列表数据联动,购物车添加、删除和状态更改
    数字化未来:实时云渲染在智慧城市中的创新应用
    (C语言)啥?4除以2等于0?
    Java学习 --- 面向对象之多态
    【C++】C++基础解析,容易混淆的引用&&内联&&NULL与nullptr
    城市交通场景分割系统:Web前端可视化
    【服务器学习】scheduler协程调度模块
    Linux安装Anaconda(Anaconda3-2022.10-Linux-x86_64.sh版本)
  • 原文地址:https://blog.csdn.net/weixin_48370579/article/details/127807089