前面介绍了在《非容器环境下如何使用OpenJPA》,现在我们来看一下它如何与现在流行的Spring框架集成的问题,包括事务的处理。
1.修改AniamlDAOImpl.java
package com.openjpa.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import com.openjpa.dao.AnimalDAO;
import com.openjpa.entity.Animal;
/**
* AnimalDAOImpl 演示了如何使用OpenJPA访问数据库的方法和步骤
*
* @author king
*
*/
public class AnimalDAOImpl extends JpaDaoSupport implements AnimalDAO {
/**
* removeAnimal方法可以从数据库中删除指定编号的Animal对象
*
* @param id
* Animal对象的编号
*/
public void removeAnimal(final int id) {
// 使用Query删除对象
getJpaTemplate().execute(new JpaCallback(){
public Object doInJpa(EntityManager em) throws PersistenceException {
em.createQuery("delete from Animal animal where animal.id=" + id).executeUpdate();
return null;
}
});
}
/**
* findAnimalsByName 通过输入的name内容模糊查找符合条件的Animal对象列表
*
* @param name
* Animal对象的name
* @return 符合模糊查找条件的Animal对象列表
*/
@SuppressWarnings("unchecked")
public List<Animal> findAnimalsByName(final String name) {
return (List<Animal>) getJpaTemplate().execute(new JpaCallback(){
public Object doInJpa(EntityManager em) throws PersistenceException {
/*
* 通过EntityManager的createQuery方法获取Query对象
* createQuery方法的参数是JPQL查询语句,JPQL语句的语法请参考OpenJPA的帮助文档.
*
* 由于查询不需要事务的支持,因此Query操作的前后没有出现begin、commit方法的调用
*
*/
Query q = em.createQuery("select animal from Animal animal where animal.name like :name");
q.setParameter("name", "%" + name + "%");
return q.getResultList();
}
});
}
/**
* getAnimalByPrimaryKey 方法可以查找符合条件的单个Animal对象,如果不存在对应的Animal对象将返回null
*
* @param id
* Animal对象的编号
* @return 唯一符合条件的Animal对象
*
*/
public Animal getAnimalByPrimaryKey(final int id) {
return (Animal) getJpaTemplate().find(Animal.class, id);
}
/**
* 将对象持久化到数据库中
*
* @param animal
* 需要被持久化的对象
*/
public void persistAnimal(final Animal animal) {
getJpaTemplate().persist(animal);
}
public void updateAnimal(final Animal animal) {
getJpaTemplate().merge(animal);
}
}
2.增加AnimalService.java和AnimalServiceImpl.java:
package com.openjpa.service;
import java.util.List;
import com.openjpa.entity.Animal;
public interface AnimalService {
/**
* removeAnimal方法可以从数据库中删除指定编号的Animal对象
*
* @param id
* Animal对象的编号
*/
public void removeAnimal(final int id) ;
/**
* findAnimalsByName 通过输入的name内容模糊查找符合条件的Animal对象列表
*
* @param name
* Animal对象的name
* @return 符合模糊查找条件的Animal对象列表
*/
@SuppressWarnings("unchecked")
public List<Animal> findAnimalsByName(final String name) ;
/**
* getAnimalByPrimaryKey 方法可以查找符合条件的单个Animal对象,如果不存在对应的Animal对象将返回null
*
* @param id
* Animal对象的编号
* @return 唯一符合条件的Animal对象
*
*/
public Animal getAnimalByPrimaryKey(final int id);
/**
* 将对象持久化到数据库中
*
* @param animal
* 需要被持久化的对象
*/
public void persistAnimal(final Animal animal);
public void updateAnimal(final Animal animal);
}
package com.openjpa.service.impl;
import java.util.List;
import com.openjpa.dao.AnimalDAO;
import com.openjpa.entity.Animal;
import com.openjpa.service.AnimalService;
public class AnimalServiceImpl implements AnimalService {
private AnimalDAO animalDao;
/**
* removeAnimal方法可以从数据库中删除指定编号的Animal对象
*
* @param id
* Animal对象的编号
*/
public void removeAnimal(final int id){
animalDao.removeAnimal(id);
}
/**
* findAnimalsByName 通过输入的name内容模糊查找符合条件的Animal对象列表
*
* @param name
* Animal对象的name
* @return 符合模糊查找条件的Animal对象列表
*/
@SuppressWarnings("unchecked")
public List<Animal> findAnimalsByName(final String name){
return animalDao.findAnimalsByName(name);
}
/**
* getAnimalByPrimaryKey 方法可以查找符合条件的单个Animal对象,如果不存在对应的Animal对象将返回null
*
* @param id
* Animal对象的编号
* @return 唯一符合条件的Animal对象
*
*/
public Animal getAnimalByPrimaryKey(final int id){
return animalDao.getAnimalByPrimaryKey(id);
}
/**
* 将对象持久化到数据库中
*
* @param animal
* 需要被持久化的对象
*/
public void persistAnimal(final Animal animal){
animalDao.persistAnimal(animal);
}
public void updateAnimal(final Animal animal){
animalDao.updateAnimal(animal);
}
public AnimalDAO getAnimalDao() {
return animalDao;
}
public void setAnimalDao(AnimalDAO animalDao) {
this.animalDao = animalDao;
}
}
3.Spring配置文件:
<?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: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.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="animalDao" class="com.openjpa.dao.impl.AnimalDAOImpl"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean id="animalService" class="com.openjpa.service.impl.AnimalServiceImpl"> <property name="animalDao" ref="animalDao"/> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"> <property name="showSql" value="true"/> <property name="generateDdl" value="true"/> <property name="databasePlatform" value="org.apache.openjpa.jdbc.sql.OracleDictionary"/> </bean> </property> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:test" /> <property name="username" value="test" /> <property name="password" value="test" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" lazy-init="true"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="read*" read-only="true" /> <tx:method name="list*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="load*" read-only="true" /> <tx:method name="doquery" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="businessService" expression="execution(* com.openjpa.service.*.*(..))" /> <aop:advisor advice-ref="transactionAdvice" pointcut-ref="businessService" /> </aop:config> </beans>
4.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" version="1.0"> <persistence-unit name="oracle" transaction-type="RESOURCE_LOCAL"/> </persistence>
5.测试代码TestService.java:
package test.openjpa;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.openjpa.entity.Animal;
import com.openjpa.service.AnimalService;
public class TestService {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:spring/applicationContext4App.xml");
AnimalService animalService = (AnimalService) ctx.getBean("animalService");
//新增
Animal a = new Animal();
a.setName("孔雀");
animalService.persistAnimal(a);
/*
//查询
List<Animal> animals = animalService.findAnimalsByName("open");
for(Animal animal: animals){
System.out.println("name = " + animal.getName());
}
//查询单个
Animal an = animalService.getAnimalByPrimaryKey(a.getId());
if(an != null){
System.out.println("Aniaml id = " + a.getId() + " , name = " + an.getName());
}
//删除
//animalService.removeAnimal(a.getId());
//查询
animals = animalService.findAnimalsByName("open");
for(Animal animal: animals){
System.out.println("name = " + animal.getName());
}
*/
}
}
详细见附件源代码。