Spring(4)之 Spring与Mybatis整合

Spring与Mybatis整合

  1. 整合思路
    Spring管理:Mybatis的 SqlSessionFactory、Mapper
    第一步:整合dao
    第二步:添加事务管理
    第三步:整合service、Spring管理Service接口、service通过IOC容器调用Dao(mapper)
  2. jar 包
    ① mybatis 的 jar包
    mybatis : mybatis、log4j、cglib、slf4j、javassist、asm)
    ② spring 的 jar包:
    spring-core: spring-core、spring-context、spring-beans、spring-expression、spring-logging、aopalliance)
    spring-aop: aspectjrt.jar、aspectjweaver.jar、spring-aop)
    spring-jdbc: spring-jdbc、spring-orm、spring-tx、mysql-connector、c3p0)
    ③ mybatis和 spring的整合包
    mybatis-spring: mybatis-spring
    ④ 数据库驱动包
  3. 工程结构
    配置文件:
    1.SqlMapConfig.xml —mybais配置文件:配置别名、setting、mapper(一般在spring配置文件中配置)
    2.Spring配置文件(可写在一个配置文件也可以分开写):
    bean.xml
    bean-dao.xml —配置数据源、SqlSessionFactory、Mapper扫描器
    bean-service.xml —配置 service
    bean-transaction.xml —事务管理
  4. Mybatis与Spring整合的过程中:
    Spring对于 Mybatis中 Mapper的管理方式有两种(两者都是mybatis和spring整合包中的类 [ 如下方class="org.mybatis.spring… ]):(下方 1.2 bean-dao.xml 中):

①. MapperFactoryBean:
缺点:如果有多个 Mapper接口对象,则要配置多次;

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

②. MapperScannerConfigurer:
可以一次性配置多个 Mapper接口对象;
(第二种管理 Mapper的方式,使用 MapperScannerConfigurer:自动生成代理对象,sqlSessionFactory 可以不写; MapperScannerConfigurer: 是Mapper扫描器,将指定包下的mapper接口自动创建对象,bean的id是mapper的类名,首字母小写; <property name=“basePackage”…>: 配置扫描包的路径,要求:mapper.xml与mapper.java同名且同目录;<property name=“sqlSessionFactoryBeanName”…>: 使用 sqlSessionFactory;)

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.asd.mapper"/>
    //<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

eg:工程目录结构:
在这里插入图片描述
eg:1.1 SqlMapConfig.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>
    <typeAliase> 
        <package name="com.iotek.po"/>
    </typeAliase>

    <!-- 若是让Spring来管理,此处可以不配置 -->
    <!-- <mapper>
    	<package name="com.asd.mapper"/>
    </mapper>-->

</configuration>

1.2 bean.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://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 http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.asd"></context:component-scan>

</beans>

1.2 bean-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 1. 数据库连接池 -->
    <!-- 法一: -->
    <!-- <bean id="dataSource" class="com.mchange.v2.com.mchange.v2.c3p0.ComboPooledDataSource">
    	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
    	<property name="user" value="root"></property>
    	<property name="password" value="12345"></property>
    </bean> -->
    <!-- 法二: -->
    <context:property-placeholder location="classpath:db.properties"/>
    
    <bean id="dataSource" class="com.mchange.v2.com.mchange.v2.c3p0.ComboPooledDataSource">
    	<property name="driverClass" value="${jdbc.driver}"></property>
    	<property name="jdbcUrl" value="${jdbc.url}"></property>
    	<property name="user" value="${jdbc.username}"></property>
    	<property name="password" value="${jdbc.password}"></property>
    </bean>
    
    <!-- 2. SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 加载mybatis的配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
    </bean>
    
    <!-- 3. Mapper配置 -->
    
    <!-- 法二(常用)简化版:第二种管理Mapper的方式,使用MapperScannerConfigurer:自动生成代理对象,sqlSessionFactory 可以不写-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.asd.mapper"/>
    </bean>
   
    <!-- 法二(常用)未简化版:-->
    <!-- MapperScannerConfigurer:是Mapper扫描器,将指定包下的mapper接口自动创建对象,bean的id是mapper的类名(首字母小写) -->
    <!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置扫描包的路径,要求:mapper.xml与mapper.java同名且同目录 -->
        <property name="basePackage" value="com.asd.mapper"/>
        <!-- 使用sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>-->
    
    <!-- 法一: 第一种管理Mapper的方式,使用MapperFactoryBean -->
    <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    	<property name="mapperInterface" value="com.asd.mapper.UserMapper"></property>
    	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    <bean id="userMapper2" class="org.mybatis.spring.mapper.MapperFactoryBean">
    	<property name="mapperInterface" value="com.asd.mapper.OrderMapper"></property>
    	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>-->
    
</beans>

1.2 ’ db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=12345

1.2’ bean-service.xml
(法一:可以使用 xml 方式生成 service的 bean对象;法二:也可以使用注解扫描的方式生成 Service类的对象:则下方 1.5 UserService.java 中可以使用@Service的类注解;)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://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 http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 法一: -->
    //<bean id="userService" class="com.asd.service.UserService"></bean>
    <!-- 法二: -->
    <context:component-scan base-package="com.asd"></context:component-scan>

</beans>

1.2’’ bean-transaction.xml
(事务管理两种方式:第一种: 配置事务管理器、事务增强、AOP;
第二种: 开启事务注解,这样可以在需要配置事务的类、或者方法上直接使用注解。)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://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 http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
        
    <!-- 法一: -->
    
    <!-- 事务增强 -->
    <!--<tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<tx:attributes>
    		<tx:method name="save" read-only="false"/>
    		<tx:method name="get*" read-only="true"/>
    		<tx:method name="*" read-only="false"/>
    	</tx:attributes>
    </tx:advice>
    <!-- AOP(切面) -->
    <aop:config>
    	<aop:advisor advice-ref="txAdvice" point-cut="execution(* com.asd.service.*.*(..))"/>
    </aop:config>  -->
    
     <!-- 法二: -->
     //使用此方法开启事务后,可以直接在下方1.5 UserService.java的类或者方法上使用@Transactional注解
     <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

1.3 User.java

public class User{
	private int id;
	private String username;
	private int age;
	set、get();
}

1.4 UserMapper.java

public interface UserMapper{
	public User findUserById(int id)throws Exception;
}

1.4’ UserMapper.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.asd.mapper.UserMapper">
    <select id="findUserById" parameterType="int" resultType="user">
	    select * from user where id=#{id}
   </select>
</mapper>

1.5 UserService.java

(因为1.2 bean-dao.xml 中有 mapper的配置,即Mapper扫描器,扫描指定包下的mapper接口自动创建 mapper对象(bean的id是mapper的类名,首字母小写),所以此处生成了userMapper可以使用@Autowired注解来自动注入; 1.2’ bean-service.xml 中使用 xml方式生成 UserService的 bean对象;)对于:
@Service   此注解在上方1.2’ bean-service.xml中(法二)开启注解扫描后才可使用;
@Autowired   此注解无需上方1.2’ bean-service.xml中(法二)开启注解扫描后才可使用,因为1.2 bean-dao.xml 中有 mapper扫描器,可自动生成 mapper对象了;

@Service 
@Transactional
public class UserService{
    @Autowired  //自动注入
    private UserMapper userMapper;
    
    public User findUserById(int id) throws Exception{
        return userMapper.findUserById(id);
    } 
}

Test.java
(此 .getBean(“sqlSessionFactory”)是上面1.2 bean-dao.xml中生成的 sqlSessionFactory的 bean对象;)

public class Test{
	ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring/bean.xml","spring/bean-*.xml");
	@Test
	public void test throws Exception{
    	SqlSessionFactory factory=(SqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
    	SqlSession sqlSession=factory.openSession();
    	UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
    	System.out.println(userMapper.findUserById(20));
    } 
    
    @Test
    public void test2 throws Exception{
        UserService userService=(UserService)applicationContext.getBean("userService");
        System.out.println(userService.findUserById(20));
        //直接得到UserService的bean对象,通过userService调用方法
        //【结果: User[id=20,username=测试3,age=2] 】
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值