关于java:动力节点Spring框架学习笔记王鹤三spring整合MyBatis

5次阅读

共计 7137 个字符,预计需要花费 18 分钟才能阅读完成。

三、spring 整合 MyBatis

官网下载地址

能源节点 spring 材料

视频观看地址

https://www.bilibili.com/vide…

将 MyBatis 与 Spring 进行整合,次要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来治理

只须要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可实现整合

整合思路

须要有须要有 Dao 接口的代理对象, 例如 studentDao 须要一个他的代理对象, 应用 SqlSession.getMapper(StudentDao.class), 失去 dao 代理对象

须要有 SqlSessionFactory, 创立一个 SqlSessionFactory 对象, 应用 SqlSessionFactory.open() 失去 SqlSession 对象

数据源 DataSource 对象, 应用连接池对象替换 mybatis 本人的 PooledDataSource

3.1 maven 依赖

maven 依赖

   <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><!-- 所在的目录 -->
        <includes><!-- 包含目录下的.properties,.xml 文件都会扫描到 -->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

3.2 实体类

定义实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer age;
}

3.3 Dao 接口与 mapper 文件

Dao 接口

public interface StudentDao {int insertStudent(Student student);

    List<Student> selectStudentList();}

mapper 文件

<?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 接口与实现类

service 接口

public interface StudentService {int addStudent(Student student);

    List<Student> queryAllStudents();}

service 实现类

@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 主配置文件

主配置文件中不再须要数据源的配置了, 因为数据源要交给 Spring 容器来治理了

这里对 mapper 映射文件的注册,应用 <package/> 标签,即只需给出 mapper 映射文件所在的包即可, 因为 mapper 的名称与 Dao 接口名雷同,能够应用这种简略注册形式。这种形式的益处是,若有多个映射文件,这里的配置也是不必扭转的。当然,也可应用原来的 <resource/> 标签形式

<?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.jjh.domain.entity"/>
    </typeAliases>

    <!-- sql mapper(sql 映射文件) 的地位 -->
    <mappers>
        <!--
            package: 指定 Dao 接口包的地位, 示意将包上面的 sql 映射文件找到
            name:Dao 接口的包名
            应用 package 指定映射文件的要求:
            1.sql 映射的文件名与 Dao 接口名统一
            2.sql 映射文件和 Dao 接口在同一目录
        -->
        <package name="com.jjh.dao"/>
    </mappers>
</configuration>

3.6 spring 的配置文件

  • jdbc.properties 文件
  • jdbc.driver=com.mysql.cj.jdbc.Driver
  • jdbc.url=jdbc:mysql://localhost:3306/mybatis01?serverTimezone=Asia/Shanghai
  • jdbc.username=root
  • jdbc.password=123456

该属性文件若要被 Spring 配置文件读取,其必须在配置文件中进行注册。应用 <context> 标签
<context:property-placeholder/> 标签中有一个属性 location,用于指定属性文件的地位

注册 SqlSessionFactoryBean

<!-- 申明的是 mybatis 中提供的 SqlSessionFactoryBean 类,这个类外部创立 SqlSessionFactory 的
    SqlSessionFactory  sqlSessionFactory = new ..
    -->
    <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>

定义 Mapper 扫描配置器 MapperScannerConfigurer

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

<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.jjh.dao"/>
    </bean>

3.7 向 service 注入接口名

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

全副配置文件

<context:component-scan base-package="com.jjh.service"/>

    <!--
        把数据库的配置信息,写在一个独立的文件,编译批改数据库的配置内容
        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.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="20"/>
    </bean>

    <!-- 申明的是 mybatis 中提供的 SqlSessionFactoryBean 类,这个类外部创立 SqlSessionFactory 的
    SqlSessionFactory  sqlSessionFactory = new ..
    -->
    <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.jjh.dao"/>
    </bean>
    
</beans>
正文完
 0