spring+openJPA+DB 2環境構築、プログラム開発及びテスト

11327 ワード

1.リードバック(ここでは省略)
2.環境構築
方法1:データソースは、persistence.xmlに配置されています。
    persistence.xml(META-INFの下にあります)
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
	version="1.0">

	<persistence-unit name="openJPAUnit" transaction-type="RESOURCE_LOCAL">
		<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
		<class>com.iteye.domain.User</class>
		<properties>
			<property name="openjpa.ConnectionURL" value="jdbc:db2://localhost:50000/USER" />
			<property name="openjpa.ConnectionDriverName" value="com.ibm.db2.jcc.DB2Driver" />
			<property name="openjpa.Log" value="SQL=TRACE" />
			<property name="openjpa.ConnectionUserName" value="username" />
			<property name="openjpa.ConnectionPassword" value="password" />
			<property name="openjpa.jdbc.TransactionIsolation" value="read-committed" />
			<property name="openjpa.jdbc.Schema" value="USER" />
		</properties>
	</persistence-unit>
</persistence>
  appication Contect.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.iteye.*" />

	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="openJPAUnit" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"/>
		</property>
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut expression="execution(* com.iteye.services.*.*(..))" id="allService" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="allService" />
	</aop:config>
</beans>
 
方法2:データソースは、appication Contect.xmlに配置されています。(推奨されています。データソースは動的に設定できますので)
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
	version="1.0">

	<persistence-unit name="openJPAUnit" transaction-type="RESOURCE_LOCAL">
		<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
		<class>com.iteye.User</class>
		<properties>
			<property name="openjpa.Log" value="SQL=TRACE" />
			<property name="openjpa.jdbc.TransactionIsolation" value="read-committed" />
			<property name="openjpa.jdbc.Schema" value="USER" />
		</properties>
	</persistence-unit>
</persistence>
 appication Contect.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.iteye.*" />
	<context:property-placeholder location="classpath:userDataSource.properties" />
	<!--       DBCP    -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
	</bean>
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"/>
		</property>
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut expression="execution(* com.iteye.services.*.*(..))" id="allService" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="allService" />
	</aop:config>
</beans>
 
3.entityManagerを取得する
方法1:コメントを使う@Persistence Unit
public class UserDao {
    //     unitName        unitName  
    @PersistenceUnit(unitName = "openJPAUnit")
    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;

    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public EntityManagerFactory getEntityManagerFactory() {
        return this.entityManagerFactory;
    }

    public EntityManager getEntityManager() {
        if (entityManager == null) {
            entityManager = entityManagerFactory.createEntityManager();
        }
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    
}
 
 方法二:直接entityManagerを取得する
    public EntityManager getEntityManager() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("openJPAUnit");
        EntityManager entityManager = emf.createEntityManager();
        // EntityManager   OpenJPAEntityManager
//        OpenJPAEntityManager openJPAEntityManager = OpenJPAPersistence.cast(entityManager);
        return entityManager;
    }
 4.entityManagerを使ってデータベースを操作する
public User saveUser(User user) {
    if (user == null) {
        throw new IllegalArgumentException("user can not be empty.");
    }
    getEntityManager().getTransaction().begin();
    getEntityManager().persist(user);
    getEntityManager().getTransaction().commit();
    return user;
}
 5.ここではserviceの呼び出しを省略します。Junnit直接作成テスト
//    spring    AbstractTransactionalSpringContextTests
class UserTest extends AbstractTransactionalSpringContextTests{
        @Resource(name = "userService")
        private UserService userService;
        @Override
        protected String[] getConfigLocations() {
            return new String[] {"applicationContext.xml" };
        }
        @Test
        public void testSaveUser() {
            User user = new User();
            user.setName("AAA");
            userService.saveUser(user);
        }
}
  
PS:Mockテスト参照リンクhttp://zhizizhishou0104.iteye.com/blog/1980182