Spring(3)—Spring-Mybatis、整合Mabatis配置、声明式事务管理

1、Mybatis实现数据库操作的思路回顾

  • 与数据库属性一致的实体类,如User
  • 用于实现数据库操作的Mapper接口以及Mapper接口的配置文件
    • Mapper接口中可以添定义数据库的增删改查等方法
    • Mapper接口的配置文件中对接口的方法进行配置
    • Mapper接口和配置文件是进行数据库操作的主要文件
  • Mybatis配置文件,配置Mytis的属性,如数据库连接池、Mapper映射的路径、别名日志等
  • 相应的,为了简化数据库的连接,将数据库的相关属性定义在一个properties文件中,传入Mybatis配置文件数据库连接池中
  • sqlSession的工厂类,Mybatis通过JDBC对数据库的操作是通过sqlSession对象获得Mapper对象进行,因此需要先建立工厂类,工厂类中声明mybatis核心配置文件的全限定名
  • 测试类,测试类中首先通过工厂类获得核心配置文件对应的sqlSession类,进一步得到Mapper对象,然后直接调用Mapper接口中的方法即可

2、Spring-Mybatis

  • Spring的思想是IOC编程,即不需要自己来创建对象,交给Spring容器来注入
  • 将Mybatis整合到Spring中:SqlSessionFactory工厂类和Mapper接口类
    • Mybatis中通过工厂类SqlSessionFactory得到的sqlsession,同样的整合到Spring容器中时,要获取这个工厂类对象,因此需要将工厂类作为一个bean进行配置
    • Mybatis对于数据库的操作代码是通过跟接口对应的配置文件进行编写或者通过注解实现,重要的是通过Mybatis可以得到这个接口Mapper类,来执行我们想要的数据库操作。因此Spring中也同样需要加入Mapper的bean
    • 对于mybatis的配置文件,需要将数据库资源放在Spring中进行配置,mybatis配置文件中只需要保留一些别名等设置即可,具体的配置视需求而定
  • 总的来说,将mybatis整合到Spring中,能够借助Spring的IOC特性,将之前需要得到的中间类,包括工厂类、sqlsession类等通过Spring内部获取,我们要做的仅仅是从Spring容器中取出我们想使用的Mapper对象,调用对象的方法即可对数据库进行操作

3、Spring-Mybatis实例

(1)与数据库相一致的实体类

@Data
public class User {
     
    private int id;
    private String name;
    private String pwd;
} 

(2)数据库驱动接口即注解实现配置

public interface UserMapper {
     
    @Select("SELECT * FROM user WHERE id=#{userId}")
    User getUser(@Param("userId") int id);
}

(3)mybatis配置文件



<configuration>
    <typeAliases>
        <package name="com.hdu.pojo"/>
    typeAliases>
configuration>

(4)数据库配置的属性文件及Spring配置文件

driver =com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
name=root
password=123456

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.hdu"/>
    
    <context:annotation-config/>

    
    <context:property-placeholder location="db.properties"/>
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${name}"/>
        <property name="password" value="${password}"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
    bean>

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        
        <property name="mapperInterface" value="com.hdu.Mapper.UserMapper"/>
        
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    bean>
beans>

(5)测试类

public class MyTest {
     
    public static void main(String[] args) {
     
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        UserMapper userMapper = (UserMapper) context.getBean("userMapper");
        User user = userMapper.getUser(1);
        System.out.println(user);
    }
}

(6)整体项目

Spring(3)—Spring-Mybatis、整合Mabatis配置、声明式事务管理_第1张图片

(7)总结

  • 从测试类中可以发现,将mybatis整合进Spring后,我们所需要操作的步骤仍然是Spring容器提供的步骤,与mybatis的操作都在Spring内部封装,这就部分就是spring配置文件中的SqlSessionFactory配置以及Mapper配置
  • SqlSessionFactory配置:将数据库的相关属性作为dataSource传入工厂实现类,得到工厂类对象
  • Mapper配置:传入的参数包括我们自定义的数据库操作方法接口以及工厂类对象,Spring内部完成了通过工厂类获得SqlSession对象,再获得Mapper这个过程,最后将Mapper作为一个bean来让我们获得

(8)遇到的一个bug

Exception in thread "main" org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'pc'@'localhost' (using password: YES)
### The error may exist in com/hdu/Mapper/UserMapper.java (best guess)
### The error may involve com.hdu.Mapper.UserMapper.getUser
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'pc'@'localhost' (using password: YES)
  • 说明mybatis和spring整合好了,但是在检索数据库时不能进行,报异常,找了很久资料发现是因为通过db.properties来定义数据库属性并导入配置中这种方法,如果properties文件中定义了username作为传递的数据库用户名,就会和系统的环境变量冲突,导致数据库连接不上,因此在properties中将username改为name传入配置文件就解决了。
  • 具体参考了:【添加链接描述】

4、Spring声明性事务:AOP

(1)事务的ACID原则:

  • 原子性
  • 一致性
  • 隔离性
  • 持久性

(2)AOP实现的事务管理在Spring中的配置:


    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    bean>
    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        
        <tx:attributes>
            <tx:method name="addUser"/>
            <tx:method name="*"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.wcd.Mapper.*..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    aop:config>

你可能感兴趣的:(mybatis,spring)