今天第一次整合spring和mybatis,可谓是历程坎坷,前后历时3个小时才整合完成,各种错误加起来恐怕有几十个,尤其是导包的环节。
现在吧今天的成果贴出来,也算是对得起自己的这五个小时了,下面是整体的结构
这是spring的控制文件applicationContext.xml(悲剧的事情就是居然把有关数据的配置都放到了这里,这不是抢mybatis的饭碗吗,搞得我花了三个小时才想到!)
[html]
<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--创建jdbc数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:****:@***.***.**.**:1521:*****" />
<property name="username" value="******" />
<property name="password" value="******" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:configuration.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="customerTest" class="com.test.Test">
<!--注入SqlSessionTemplate实例 -->
<property name="sqlSessionTemplate" ref="sqlSession" />
</bean>
</beans>
</span>
这是mybatis的配置文件configuration.xml,没办法,饭碗被spring抢了,就只剩这点了
[html]
<span style="font-size:14px;"><?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>
<typeAlias alias="Customer" type="com.test.Customer" />
</typeAliases>
<mappers>
<mapper resource="com/test/Customer.xml" />
</mappers>
</configuration>
</span>
这是数据映射文件customer.xml
[html] view plaincopy
<span style="font-size:14px;"><?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="Customer">
<select id="selectCustomer" parameterType="int" resultType="Customer">
select * from tcor_crm_customer where CUSTID = #{id}
</select>
</mapper> </span>
customer的POJO类就省了,setter,getter方法,超简单,记着重写toString方法就可以了
这是测试方法
[java]
<span style="font-size:14px;">package com.test;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test extends SqlSessionDaoSupport{
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test().firstTest();
}
public void firstTest() {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Test test = (Test)factory.getBean("customerTest");
Customer cus = (Customer)test.getSqlSession().selectOne("selectCustomer",10696);
System.out.println(cus);
}
}
</span>