MyBatis(9)整合spring

具体的感兴趣可以参考:MyBatis

 

此时此刻,没用的话不再多说了,直接开始代码工程吧!

 

整体的代码实现:

具体使用到的我们在进行细说

基本上理解一边就能会使用整合

 

 准备工作:

 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/shopping
jdbc.username=root
jdbc.password=12345

 

 

 log4j.properties

#Global logging configuration
# 在开发环境下日志级别要设成
log4j.rootLogger = DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =%5p [%t] - %m%n

 

 

applivationContext.xml
mvc,context,aop,tx,beans...命名约束
     <!-- 加载配置文件 -->
     <context:property-placeholder location="classpath:db.properties" />

 

 

 使用dbcp数据库连接池

<!-- 数据源,使用dbcp -->
     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
           destroy-method="close">
           <property name="driverClassName" value="${jdbc.driver}" />
           <property name="url" value="${jdbc.url}" />
           <property name="username" value="${jdbc.username}" />
           <property name="password" value="${jdbc.password}" />
           <property name="maxActive" value="10" />
           <property name="maxIdle" value="5" />
     </bean>

 

 

配置SqlSessionFactory

 不需要在类中单独进行配置

<!-- sqlSessinFactory -->
     <!-- org.mybatis.spring.SqlSessionFactoryBean -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <!-- 加载mybatis的配置文件 -->
           <property name="configLocation" value="mybatis/SqlMapConfig.xml" />
           <!-- 数据源 -->
           <property name="dataSource" ref="dataSource" />
     </bean>

 

 

 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>
     <typeAliases>
           <package name="com.MrChengs.po"/>
     </typeAliases>  
     
     <!-- 加载 映射文件 -->
     <mappers>
           <mapper resource="sqlmap/User.xml"/>
     </mappers>
</configuration>

 

 其他的设置项在使用的时候在进行添加,,,,,,

 

 

 一.dao开发

 Userser.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="test">
     <select id="findUserByID" parameterType="int" resultType="com.MrChengs.po.User">
           select * from user where id=#{id}
     </select>
</mapper>

 

 

 UserDao.java

public interface UserDao {
     //根据id查询用户信息
     public User findUserById(int id) throws Exception;
}

 

 

 UserDaoImp.java

让实现接口类的类继承SqlSessionDaoSupport
通过spring进行注入,声明配置方式,配置dao的bean
 
此时不需要手动配置SqlSessionFactory
直接可以得到其对象
 
此时不需要手动关闭,在spring容器池里会自动关闭
public class UserDaoImp extends SqlSessionDaoSupport implements UserDao {
     @Override
     public User findUserById(int id) throws Exception {
           SqlSession sqlSession = this.getSqlSession();
           User user =sqlSession.selectOne("test.findUserByID", id);
           return user;
     }
}

 

 

applivationContext.xml
注入sqlSessionFactory
     <bean id="userDao" class="com.MrChengs.UserDao.UserDaoImp">
           <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
     </bean>

 

 

测试:

public class Test {
     private ApplicationContext applicationContext;
     public ApplicationContext getApplication(){
           applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
           return applicationContext;
     }
     //Dao开发
     @org.junit.Test
     public void testDao() throws Exception{
           UserDao userdao = (UserDao) getApplication().getBean("userDao");
           User user =  userdao.findUserById(1);
           System.out.println(user);
     }
}

 

DEBUG [main] - ==>  Preparing: select * from user where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3bf7ca37]
DEBUG [main] - Returning JDBC Connection to DataSource
User [id=1, username=王五, birthday=null, sex=2, address=null]

 

 

 

二.Mapper代理开发

UserMapper.java

//相当于dao接口
public interface UserMapper {
     //根据id查询用户信息
     public User findUserById(int id) throws Exception;
}

 

 

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.MrChengs.mapper.UserMapper">
     <select id="findUserById" parameterType="int" resultType="com.MrChengs.po.User">
           SELECT * FROM USER WHERE id=#{value}
     </select>
</mapper>

 

 

注意上述的两个文件在一个路径下。

 

SqlMapConfig.xml

     <!-- 加载 映射文件 -->
     <mappers>
           <mapper resource="sqlmap/User.xml"/>
           <package name="com.MrChengs.mapper"/>
     </mappers>

 

 

通过MapperFactoryBean创建代理对象

<!-- mapper配置
     MapperFactoryBean:根据mapper接口生成代理对象
-->
     <!-- mapperInterface指定mapper接口 -->
     <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
           <property name="mapperInterface" value="com.MrChengs.mapper.UserMapper"/>
           <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
     </bean>

 

 

测试:

public class TestMapper {
     private ApplicationContext applicationContext;
     public ApplicationContext getApplication(){
           applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
           return applicationContext;
     }
     //Mapper开发
     @org.junit.Test
     public void testmapper() throws Exception{
           UserMapper user = (UserMapper) getApplication().getBean("userMapper");
           User u = user.findUserById(1);
           System.out.println(u);
     }
}

 

DEBUG [main] - ==>  Preparing: SELECT * FROM USER WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7c729a55]
DEBUG [main] - Returning JDBC Connection to DataSource
User [id=1, username=王五, birthday=null, sex=2, address=null]

 

 

 

如果有很多个类都需要对每个mapper进行配置,此时需要大量的工程???

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

 

 

 

通过MapperScannerConfigurer进行mapper扫描(建议使用)

applicationContext.xml

说明:

 
mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
自动扫描出来的mapper的bean的id为mapper类名(首字母小写
 
name="basePackage"
指定扫描的包名
如果扫描多个包,每个包中间使用半角逗号分隔
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.MrChengs.mapper"/>
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     
     </bean>

 

 

 其余的测试不变......

 

 

posted @ 2018-10-24 20:53  MrChengs  阅读(370)  评论(0编辑  收藏  举报