mybatis 3とspring 3の統合(二)
2753 ワード
構成spring.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/context
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- jdbc -->
<context:property-placeholder location="jdbc.properties"/>
<!-- jdbc -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- SqlSessionFactory, -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="mybatis-config.xml"/>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- UserDao -->
<bean id="userDao" class="org.zsm.study.mybatis.dao.impl.UserDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
</beans>
テスト:
package test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zsm.study.mybatis.dao.IUserDao;
import org.zsm.study.mybatis.domain.User;
public class TestUseDao {
private ApplicationContext ctx = null;
@Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@After
public void tearDown() throws Exception {
ctx = null;
}
@Test
public void add() {
User user = new User();
user.setUserName(" ");
user.setUserAge("21");
user.setUserAddress("hubei huanggang");
IUserDao userDao = (IUserDao) ctx.getBean("userDao");
userDao.Save(user);
}
}