Spring框架学习笔记 --- [Spring框架整合Mybatis框架]

Posted 小智RE0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring框架学习笔记 --- [Spring框架整合Mybatis框架]相关的知识,希望对你有一定的参考价值。


Spring框架整合Mybatis框架

这里初步整合搭建结束的话,在下一篇关于springmvc的笔记也会用到.

这里创建JavaEE的项目模块;把web的功能也选上,便于后面使用;

(1)导入需要使用的maven包

主要是mybatis-spring这个整合包;其他的包是之前使用过的;

<dependencies>
   <!--spring.context-->
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>5.2.2.RELEASE</version>
   </dependency>
   <!-- spring-jdbc -->
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>5.2.2.RELEASE</version>
   </dependency>
   <!-- spring-aop -->
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-aspects</artifactId>
       <version>5.2.2.RELEASE</version>
   </dependency>
   <!--mybatis-->
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.4.2</version>
   </dependency>
   <!--log4j日志-->
   <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.17</version>
   </dependency>
   <!-- 阿里数据源 -->
   <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.1.10</version>
   </dependency>
   <!--spring-mybatis-->
   <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>8.0.22</version>
   </dependency>
</dependencies>

(2)实体类,数据访问层,服务层,以及数据访问映射文件

📢创建实体类Person

pojo包下创建Person

package com.xiaozhire0.ssm.pojo;

import org.springframework.stereotype.Component;
import java.util.Date;
/**
 * @author by CSDN@小智RE0
 * @date 2021-11-21 12:25
 * 人类;
 */
//将这个类注入到spring;
@Component
public class People 
    //这边的话,就保持和数据库的字段名一致吧;
    private Integer id;
    private String  name;
    private String  password;
    private Integer age;
    private Date    birthday;

    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 getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    public Integer getAge() 
        return age;
    

    public void setAge(Integer age) 
        this.age = age;
    

    public Date getBirthday() 
        return birthday;
    

    public void setBirthday(Date birthday) 
        this.birthday = birthday;
    

    @Override
    public String toString() 
        return "People" + "id=" + id +
                ", name='" + name + '\\'' +
                ", password='" + password + '\\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '';
    

📢数据访问接口PersonMapper

dao包下创建PersonMapper接口

package com.xiaozhire0.ssm.dao;

import com.xiaozhire0.ssm.pojo.People;
import org.springframework.stereotype.Repository;

/**
 * @author by CSDN@小智RE0
 * @date 2021-11-21 12:14
 * 使用的数据访问接口
 */
 //数据访问接口注入spring
@Repository
public interface PersonMapper 
        //简易地添加用户方法,
        void savePeople(People people);

📢服务层PersonService

service包下创建PersonService

package com.xiaozhire0.ssm.service;

import com.xiaozhire0.ssm.dao.PersonMapper;
import com.xiaozhire0.ssm.pojo.People;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @author by CSDN@小智RE0
 * @date 2021-11-21 12:40
 * 使用的服务类
 */
//将服务类注入spring
@Service(value = "personService")
public class PersonService 
    //自动装配数据访问层;
    @Autowired
    PersonMapper personMapper;

    //添加用户的方法;写上事务标记注解
    @Transactional
    public void savePeople(People people) 
        personMapper.savePeople(people);
    

📢数据访问映射文件PersonMapper.xml

resources目录下创建mapper文件夹,创建PersonMapper.xml

<?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.xiaozhire0.ssm.dao.PersonMapper">

    <!--添加用户-->
    <insert id="savePeople" parameterType="people">
        insert into t_spandmb(name,password,age,birthday)
        values (#name,#password,#age,#birthday)
    </insert>
</mapper>

(3)不同的配置文件

先在数据库简单地创建一个数据表;

#spring整合mybatis时使用的数据表;
CREATE TABLE IF NOT EXISTS t_spandmb(
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT 'ID号',
    `name` VARCHAR(20) COMMENT '姓名',
    `password` VARCHAR(10) COMMENT '密码',
    `age`  INT COMMENT '年龄',
    `birthday` DATE COMMENT '生日'       
);

📢database.properties 数据库连接池使用的属性文件

resources目录下创建database.properties
存入数据库连接池需要的几个参数

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day20211024_study_mybatis_db?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
user=root
pwd=123456
initialSize = 5
maxActive = 10

📢log4j.properties 日志属性文件

resources目录下创建log4j.properties文件

log4j.rootLogger = debug,stdout,D
#System out Console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%p] %dyyyy-MM-dd HH:mm:ss,SSS %m%n

#System out File
log4j.appender.D = org.apache.log4j.FileAppender
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %dyyyy-MM-dd HH:mm:ss  [ %t:%r ] - [ %p ] -[%l] %m%n

📢mybatis-config.xml 配置mybatis需要的几个配置

resources目录下创建mybatis-config.xml
数据库链接,mapper映射什么的,在spring的配置文件中编写即可;不需要写在mybatis的配置文件中;

<?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>
        <!--配置日志-->
        <setting name="logImpl" value="LOG4J"/>
        <!--设置开启驼峰命名匹配-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--配置延时加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="lazyLoadTriggerMethods" value=""/>
        <!--开启二级缓存,默认为true-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <!--配置别名,可直接用包扫描,即默认别名为首字母小写的别名-->
    <typeAliases>
        <package name="com.xiaozhire0.ssm.pojo"/>
    </typeAliases>
</configuration>

📢spring-dbandtx.xml 配置数据库连接池以及事务注解支持

resources目录下创建spring-dbandtx.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--读取数据库属性文件-->
    <context:property-placeholder location="classpath:database.properties"/>
    <!--创建连接池使用阿里数据源-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="$driverClassName"/>
        <property name="url"             value="$url"/>
        <property name="username"        value="$user"/>
        <property name="password"        value="$pwd"/>
        <property name="initialSize"     value="$initialSize"/>
        <property name="maxActive"       value="$maxActive"/>
     </bean>
    <!--配置事务管理引用数据库连接池-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>
    <!--若使用注解的话;不需要在此处配置事务传播,增强方法-->
    <!--开启事务注解扫描-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

📢spring-mybatis.xml ; spring整合mybatis

resources目录下创建spring-mybatis.xml
这里会由spring控制管理sqlSessionFactory,读取mybatis框架中的配置

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--配置sqlSession,由spring管理sqlSessionFactory,读取mybatis的配置文件-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="druidDataSource">
        </property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*Mapper.xml">
        </property>
    </bean>

    <!--mapper代理注入-->
    <bean id="mapperFactory" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xiaozhire0.ssm.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

📢使用spring.xml整合其他的配置文件

resources目录下创建spring.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!--开启注解扫描-->
    <context:component-scan base-package="com.xiaozhire0.ssm"></context:component-scan>

    <!--合并数据连接以及事务管理配置文件-->
    <import resource="spring-dbandtx.xml"></import>

    <!--合并spring整合mybatis的配置文件-->
    <import resource="spring-mybatis.xml"></import>
</beans>

(4) 测试执行

test包下创建TestDemo类,进行测试

package com.xiaozhire0.ssm.test;

import com.xiaozhire0.ssm.pojo.以上是关于Spring框架学习笔记 --- [Spring框架整合Mybatis框架]的主要内容,如果未能解决你的问题,请参考以下文章

Spring学习笔记--Spring简介

Java学习笔记:Spring框架

Spring框架学习笔记

Spring框架学习笔记 --- [Spring框架整合Mybatis框架]

Spring框架学习笔记 ---[spring框架概念 , 初步上手使用Spring , 控制反转 & 依赖注入初步理解 ]

Spring MVC +Spring 框架学习总结-全网最好用的学习笔记