1.准备
这段时间学习了Spring和Mybatis的知识,我们知道持久层的 mapper,dao都需要spring进行管理, 需要spring通过单例的方式管理SqlSessionFactory,spring和mybatis整合生成代理对象使用sqlsessionFactory创建sqlsession;
练习全部jar (Spring+Mybatis+Spring-mybatis整合包)下载 :
http://download.csdn.net/detail/lablenet/9385114
demo数据准备 :
(1) 创建一个客户表 :
--客户表
CREATE TABLE F_CLIENT(
ID NUMBER(12) PRIMARY KEY,--用户编号
USERNAME VARCHAR2(20) NOT NULL,--用户姓名
CLIENT_CERTIFICATE_NO VARCHAR2(20) NOT NULL UNIQUE,--证件号码
BORN_DATE DATE,--出生日期
FAMILY_REGISTER_ADDRESS VARCHAR2(200),--家庭住址
NOW_ADDRESS VARCHAR2(200) NOT NULL,--现在住址
CONTACT_MODE VARCHAR2(50) NOT NULL,--联系方式
URGENCY_CONTACT_MODE VARCHAR2(50) NOT NULL,--紧急联系方式
CREATE_DATE DATE NOT NULL--创建时间
);
(2) 初始化数据 :
insert into f_client(id,username,client_certificate_no,born_date,family_register_address,now_address,contact_mode,urgency_contact_mode,create_date) values (14,
'yuan','311209070127',to_date('1993-03-12','yyyy-mm-dd'),'河南省焦作市','河南省河南理工大学','150000000','110',sysdate);
insert into f_client(id,username,client_certificate_no,born_date,family_register_address,now_address,contact_mode,urgency_contact_mode,create_date) values(
15,'yang','311209070126',to_date('1993-04-12','yyyy-mm-dd'),'河南温县','河南理工大学','3987321','110',sysdate);
insert into f_client values(
16,'yang','311209070129',to_date('1997-04-12','yyyy-mm-dd'),'河南新乡','河南理工大学','3987321','110',sysdate);
public class FClient {
private Integer id;
private String username;
private String client_certificate_no;
private Date born_date;
private String family_register_address;
private String now_address;
private String contact_mode;
private String urgency_contact_mode;
private Date create_data;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getClient_certificate_no() {
return client_certificate_no;
}
public void setClient_certificate_no(String client_certificate_no) {
this.client_certificate_no = client_certificate_no;
}
public Date getBorn_date() {
return born_date;
}
public void setBorn_date(Date born_date) {
this.born_date = born_date;
}
public String getFamily_register_address() {
return family_register_address;
}
public void setFamily_register_address(String family_register_address) {
this.family_register_address = family_register_address;
}
public String getNow_address() {
return now_address;
}
public void setNow_address(String now_address) {
this.now_address = now_address;
}
public String getContact_mode() {
return contact_mode;
}
public void setContact_mode(String contact_mode) {
this.contact_mode = contact_mode;
}
public String getUrgency_contact_mode() {
return urgency_contact_mode;
}
public void setUrgency_contact_mode(String urgency_contact_mode) {
this.urgency_contact_mode = urgency_contact_mode;
}
public Date getCreate_data() {
return create_data;
}
public void setCreate_data(Date create_data) {
this.create_data = create_data;
}
}
2.原始dao整合
整合图解 :
下面我们使用一个例子来说明 :
场景描述 : 通过客户id查询客户信息 ;
(1)dao层
dao接口
public interface ClientDao {
FClient findClientById(int id);
}
dao接口实现 :
注意 : 在这里我们让dao实现接口继承SqlSessionDaoSupport (在spring-mybatis整合包中 org.mybatis.spring.support.SqlSessionDaoSupport),则在dao接口实现中不需要sqlsessionFactory属性了;就不用了在注入sqlSessionFactory了;
public class ClinetDapimpl extends SqlSessionDaoSupport implements ClientDao {
/*
* 原始的sqlSessionFactory的注入方式
* private SqlSessionFactory sqlSessionFactory;
public ClinetDapimpl(SqlSessionFactory sqlSessionFactory) {
super();
this.sqlSessionFactory = sqlSessionFactory;
}*/
@Override
public FClient findClientById(int id) {
SqlSession session = this.getSqlSession();
FClient client = (FClient) session.selectOne("cn.labelnet.dao.ClientDao.findClientById",id);
return client;
}
}
(2)Clientmap.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="cn.labelnet.dao.ClientDao">
<select id="findClientById" parameterType="int" resultType="cn.labelnet.po.FClient">
select * from f_client where id=#{value}
</select>
</mapper>
(3)SqlMapConfig.xml
在之前的练习中,我们在这里加载数据源,但是在整合中我们将数据源加载交给了spring的ApplicationContext.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>
<mappers>
<mapper resource="cn/lablenet/dao/sqlmap/ClientMap.xml"/>
<!-- 加载mapper映射文件 -->
<!-- <mapper resource="cn/labelnet/mapper/ClientMapper.xml" /> -->
</mappers>
</configuration>
(4)ApplicationContext.xml
注意 :1)数据源加载用的是 org.apache.commons.dbcp.BasicDataSource ;
2)配置sqlsessionFactory 用的是 org.mybatis.spring.SqlSessionFactoryBean ;
3)配置dao的接口实现,为其注入sqlSessionFactory ;
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${oracle.driver}"></property>
<property name="url" value="${oracle.url}"></property>
<property name="username" value="${oracle.name}"></property>
<property name="password" value="${oracle.pass}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<!-- 1.配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 加载mybatis的配置信息 -->
<property name="configLocation" value="cn/labelnet/mybatis/config/SqlmapDaoConfig.xml"></property>
<!-- 加载数据源 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置dao的接口实现,为其注入sqlSessionFactory -->
<bean id="ClientDao" class="cn.labelnet.dao.ClinetDapimpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
5)测试
//得到Spring 容器
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext=new ClassPathXmlApplicationContext("classpath:cn/labelnet/spring/config/applicationContext.xml");
}
@Test
public void test() {
ClientMapper bean = (ClientMapper) applicationContext.getBean("clientMapper");
bean.findClientById(15);
}
3.Mapper代理整合
整合图解 :
示例 :上面的场景不变,采用上面的场景实现
(1)Mapper.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="cn.labelnet.mapper.ClientMapper">
<select id="findClientById" parameterType="int" resultType="cn.labelnet.po.FClient">
select * from f_client where id=#{value}
</select>
</mapper>
(2)Mapper.java实现
public interface ClientMapper {
FClient findClientById(int id);
}
(3)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>
<mappers>
<mapper resource="cn/lablenet/dao/sqlmap/ClientMap.xml"/>
<!-- 加载mapper映射文件 -->
<mapper resource="cn/labelnet/mapper/ClientMapper.xml" />
</mappers>
</configuration>
(4)Applicationcontext.xml
注意 :1)数据源加载用的是 org.apache.commons.dbcp.BasicDataSource ;
2)配置sqlsessionFactory 用的是 org.mybatis.spring.SqlSessionFactoryBean ;
3)通过MapperFactoryBean 实现 创建代理对象用的是 org.mybatis.spring.mapper.MapperFactoryBean
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${oracle.driver}"></property>
<property name="url" value="${oracle.url}"></property>
<property name="username" value="${oracle.name}"></property>
<property name="password" value="${oracle.pass}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<!-- 1.配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 加载mybatis的配置信息 -->
<property name="configLocation" value="cn/labelnet/mybatis/config/SqlmapDaoConfig.xml"></property>
<!-- 加载数据源 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- <!-- 配置dao的接口实现,为其注入sqlSessionFactory -->
<bean id="ClientDao" class="cn.labelnet.dao.ClinetDapimpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> -->
<!--1.配置mapper代理对象
通过MapperFactoryBean 实现 创建代理对象
-->
<bean id="clientMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- value为接口的全限定名 -->
<property name="mapperInterface" value="cn.labelnet.mapper.ClientMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
(5)测试
//得到Spring 容器
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext=new ClassPathXmlApplicationContext("classpath:cn/labelnet/spring/config/applicationContext.xml");
}
@Test
public void test() {
ClientMapper bean = (ClientMapper) applicationContext.getBean("clientMapper");
bean.findClientById(15);
}
(6)问题
在使用mapper代理的时候,发生了一个错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [cn/labelnet/spring/config/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:591)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cn.labelnet.dao.ClientMapperScannerTest.setUp(ClientMapperScannerTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.MalformedParameterizedTypeException
at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:60)
at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:53)
at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:95)
at sun.reflect.generics.factory.CoreReflectionFactory.makeParameterizedType(CoreReflectionFactory.java:105)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:140)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.visitor.Reifier.visitArrayTypeSignature(Reifier.java:159)
at sun.reflect.generics.tree.ArrayTypeSignature.accept(ArrayTypeSignature.java:42)
at sun.reflect.generics.repository.ConstructorRepository.getParameterTypes(ConstructorRepository.java:94)
at java.lang.reflect.Method.getGenericParameterTypes(Method.java:292)
at java.beans.FeatureDescriptor.getParameterTypes(FeatureDescriptor.java:387)
at java.beans.MethodDescriptor.setMethod(MethodDescriptor.java:114)
at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:72)
at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:56)
at java.beans.Introspector.getTargetMethodInfo(Introspector.java:1149)
at java.beans.Introspector.getBeanInfo(Introspector.java:416)
at java.beans.Introspector.getBeanInfo(Introspector.java:163)
at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:224)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:149)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:324)
at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptors(BeanWrapperImpl.java:331)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.filterPropertyDescriptorsForDependencyCheck(AbstractAutowireCapableBeanFactory.java:1242)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1101)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 34 more
再此陷入纠结中;开始的时候,自己的spring , mybatis ,spring-mybatis的整合包是自己这里复制哪里粘贴的,导致很多重复包,经过使用上面的全部整合包,解决了;
还有一个问题 :
问题 : mapper多的话,需要配置多个mapper
解决:mapper批量扫描,从mapper包中扫描出mapper接口,自动创建mapper对象
4.Mapper代理整合 bean扫描实现
整合图解 :
1) bean配置
Mapper.xml 和 mapper.java一样,在这里就只配置下ApplicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${oracle.driver}"></property>
<property name="url" value="${oracle.url}"></property>
<property name="username" value="${oracle.name}"></property>
<property name="password" value="${oracle.pass}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<!-- 1.配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 加载mybatis的配置信息 -->
<property name="configLocation" value="cn/labelnet/mybatis/config/SqlmapDaoConfig.xml"></property>
<!-- 加载数据源 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置dao的接口实现,为其注入sqlSessionFactory -->
<bean id="ClientDao" class="cn.labelnet.dao.ClinetDapimpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<!--1.配置mapper代理对象
通过MapperFactoryBean 实现 创建代理对象
-->
<!-- <bean id="clientMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
value为接口的全限定名
<property name="mapperInterface" value="cn.labelnet.mapper.ClientMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean> -->
<!-- mapper批量扫描:
从mapper包中扫描出mapper接口,自动创建代理对象 并且在spring容器中注册;
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中,
自动扫描出来的mapper的bean的 id为mapper类名首字母小写;-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描的包名 -->
<property name="basePackage" value="cn.labelnet.mapper"></property>
<!-- Sqlsession -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
(2) 重点是 :
<!-- mapper批量扫描:
从mapper包中扫描出mapper接口,自动创建代理对象 并且在spring容器中注册;
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中,
自动扫描出来的mapper的bean的 id为mapper类名首字母小写;-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描的包名 -->
<property name="basePackage" value="cn.labelnet.mapper"></property>
<!-- Sqlsession -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
1)扫描bean不需要 设置ID ,使用的时候是扫描出来的mapper的类名且首字母小写;
2)扫描bean使用的是 org.mybatis.spring.mapper.MapperScannerConfigurer;
3)配置SqlSessionFactory的时候使用 :value为sqlSessionFactory的bean的id ;
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
5.Demo免积分下载
http://download.csdn.net/detail/lablenet/9385109