myeclipse2013下spring3.1与jpa2.0之整合
不断在学习,但是没有整理的话,好像什么东西都会忘掉,好似了解一点,但要是实际使用的话,又会差了很多,所以记录下学习的脚步,后天就过年了,明年终于毕业了,可以找工作了,嘿嘿.
本文主要涉及到以下几点
1.利用spring的事务管理器对jpa的事务进行管理(在利用spring的事务管理器进行管理jpa的事务的时候,主要有两点
a.用spring 容器管理实体工厂(EntityManagerFactory),并用PersistenceAnnotationBeanPostProcessor解析@PersistenceContext,进行EntityManager的依赖注入
b.使用JpaTransactionManager进行实体工厂的自动事务管理,并在需要进行事务管理的dao中加上@Transactional注解,用tx:annotation-driven对@Transactional进行解析后,自动进行事务管理)
2.利用myeclipse的jpa工程翻转获取实体的接口类与dao类
好了,多的不说了,一切都在代码里面,必要的地方我都加了详细的注释了
1.利用myeclipse2013为项目添加spring和jpa的功能,myeclipse2013会为你自动的添加相应的jar包,如下图
2.使用myeclipse2013的jpa翻转功能,生成相应的实体类与实体类的接口与Dao
附:已在oracle中建立好了表stus,sql如下
-- Create table
create table STUS
(
stu_id VARCHAR2(50) not null,
stu_name VARCHAR2(30) not null,
stu_age NUMBER not null,
stu_birthday DATE not null
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table STUS
add constraint INFOIDS primary key (STU_ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
3.调整接口类与dao类的位置,并为StusDao建立Junit case测试,并添加oracle的jar包到工程中,最终的目录结构如下
4.进行单元测试
StusDAOTest.java源码如下
package com.undergrowth.test;
import static org.junit.Assert.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.undergrowth.bean.Stus;
import com.undergrowth.bean.inter.IStusDAO;
import com.undergrowth.bean.inter.imple.StusDAO;
public class StusDAOTest {
private static IStusDAO isd;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
isd=StusDAO.getFromApplicationContext(ac);
}
@Test
public void testSave() {
Stus stus=new Stus(UUID.randomUUID().toString(), "张三", 20.0, new Timestamp(new Date().getTime()));
//这里使用spring的事务管理器管理事务
isd.save(stus);
}
@Test
public void testDelete() {
List<Stus> listEntity=isd.findAll();
for (Stus stus2 : listEntity) {
isd.delete(stus2);
}
}
@Test
public void testUpdate() {
List<Stus> listEntity=isd.findAll();
for (Stus stus2 : listEntity) {
stus2.setStuName("undergrowth");
isd.update(stus2);
}
}
@Test
public void testFindAll() {
List<Stus> listEntity=isd.findAll();
for (Stus stus2 : listEntity) {
System.out.println(stus2);
}
}
}
StusDao.java
package com.undergrowth.bean.inter.imple;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.undergrowth.bean.Stus;
import com.undergrowth.bean.inter.IStusDAO;
/**
* A data access object (DAO) providing persistence and search support for Stus
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see com.undergrowth.bean.Stus
* @author MyEclipse Persistence Tools
*/
@Repository @Transactional
public class StusDAO implements IStusDAO {
private static final Log logger = LogFactory.getLog(StusDAO.class);
// property constants
public static final String STU_NAME = "stuName";
public static final String STU_AGE = "stuAge";
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
private EntityManager getEntityManager() {
return entityManager;
}
/**
* Perform an initial save of a previously unsaved Stus entity. All
* subsequent persist actions of this entity should use the #update()
* method. This operation must be performed within the a database
* transaction context for the entity's data to be permanently saved to the
* persistence store, i.e., database. This method uses the
* {@link javax.persistence.EntityManager#persist(Object)
* EntityManager#persist} operation.
* <p>
* User-managed Spring transaction example:
*
* <pre>
* TransactionStatus txn = txManager
* .getTransaction(new DefaultTransactionDefinition());
* StusDAO.save(entity);
* txManager.commit(txn);
* </pre>
*
* @see <a href =
* "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
* container-managed transaction examples</a>
* @param entity
* Stus entity to persist
* @throws RuntimeException
* when the operation fails
*/
public void save(Stus entity) {
logger.info("saving Stus instance");
try {
getEntityManager().persist(entity);
logger.info("save successful");
} catch (RuntimeException re) {
logger.error("save failed", re);
throw re;
}
}
/**
* Delete a persistent Stus entity. This operation must be performed within
* the a database transaction context for the entity's data to be
* permanently deleted from the persistence store, i.e., database. This
* method uses the {@link javax.persistence.EntityManager#remove(Object)
* EntityManager#delete} operation.
* <p>
* User-managed Spring transaction example:
*
* <pre>
* TransactionStatus txn = txManager
* .getTransaction(new DefaultTransactionDefinition());
* StusDAO.delete(entity);
* txManager.commit(txn);
* entity = null;
* </pre>
*
* @see <a href =
* "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
* container-managed transaction examples</a>
* @param entity
* Stus entity to delete
* @throws RuntimeException
* when the operation fails
*/
public void delete(Stus entity) {
logger.info("deleting Stus instance");
try {
entity = getEntityManager().getReference(Stus.class,
entity.getStuId());
getEntityManager().remove(entity);
logger.info("delete successful");
} catch (RuntimeException re) {
logger.error("delete failed", re);
throw re;
}
}
/**
* Persist a previously saved Stus entity and return it or a copy of it to
* the sender. A copy of the Stus entity parameter is returned when the JPA
* persistence mechanism has not previously been tracking the updated
* entity. This operation must be performed within the a database
* transaction context for the entity's data to be permanently saved to the
* persistence store, i.e., database. This method uses the
* {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
* operation.
* <p>
* User-managed Spring transaction example:
*
* <pre>
* TransactionStatus txn = txManager
* .getTransaction(new DefaultTransactionDefinition());
* entity = StusDAO.update(entity);
* txManager.commit(txn);
* </pre>
*
* @see <a href =
* "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
* container-managed transaction examples</a>
* @param entity
* Stus entity to update
* @return Stus the persisted Stus entity instance, may not be the same
* @throws RuntimeException
* if the operation fails
*/
public Stus update(Stus entity) {
logger.info("updating Stus instance");
try {
Stus result = getEntityManager().merge(entity);
logger.info("update successful");
return result;
} catch (RuntimeException re) {
logger.error("update failed", re);
throw re;
}
}
public Stus findById(String id) {
logger.info("finding Stus instance with id: " + id);
try {
Stus instance = getEntityManager().find(Stus.class, id);
return instance;
} catch (RuntimeException re) {
logger.error("find failed", re);
throw re;
}
}
/**
* Find all Stus entities with a specific property value.
*
* @param propertyName
* the name of the Stus property to query
* @param value
* the property value to match
* @return List<Stus> found by query
*/
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
@SuppressWarnings("unchecked")
public List<Stus> findByProperty(String propertyName, final Object value) {
logger.info("finding Stus instance with property: " + propertyName
+ ", value: " + value);
try {
final String queryString = "select model from Stus model where model."
+ propertyName + "= :propertyValue";
Query query = getEntityManager().createQuery(queryString);
query.setParameter("propertyValue", value);
return query.getResultList();
} catch (RuntimeException re) {
logger.error("find by property name failed", re);
throw re;
}
}
public List<Stus> findByStuName(Object stuName) {
return findByProperty(STU_NAME, stuName);
}
public List<Stus> findByStuAge(Object stuAge) {
return findByProperty(STU_AGE, stuAge);
}
/**
* Find all Stus entities.
*
* @return List<Stus> all Stus entities
*/
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
@SuppressWarnings("unchecked")
public List<Stus> findAll() {
logger.info("finding all Stus instances");
try {
final String queryString = "select model from Stus model";
Query query = getEntityManager().createQuery(queryString);
return query.getResultList();
} catch (RuntimeException re) {
logger.error("find all failed", re);
throw re;
}
}
public static IStusDAO getFromApplicationContext(ApplicationContext ctx) {
return (IStusDAO) ctx.getBean("StusDAO");
}
}IStusDao.java
package com.undergrowth.bean.inter;
import java.sql.Timestamp;
import java.util.List;
import com.undergrowth.bean.Stus;
/**
* Interface for StusDAO.
*
* @author MyEclipse Persistence Tools
*/
public interface IStusDAO {
/**
* Perform an initial save of a previously unsaved Stus entity. All
* subsequent persist actions of this entity should use the #update()
* method. This operation must be performed within the a database
* transaction context for the entity's data to be permanently saved to the
* persistence store, i.e., database. This method uses the
* {@link javax.persistence.EntityManager#persist(Object)
* EntityManager#persist} operation.
* <p>
* User-managed Spring transaction example:
*
* <pre>
* TransactionStatus txn = txManager
* .getTransaction(new DefaultTransactionDefinition());
* IStusDAO.save(entity);
* txManager.commit(txn);
* </pre>
*
* @see <a href =
* "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
* container-managed transaction examples</a>
* @param entity
* Stus entity to persist
* @throws RuntimeException
* when the operation fails
*/
public void save(Stus entity);
/**
* Delete a persistent Stus entity. This operation must be performed within
* the a database transaction context for the entity's data to be
* permanently deleted from the persistence store, i.e., database. This
* method uses the {@link javax.persistence.EntityManager#remove(Object)
* EntityManager#delete} operation.
* <p>
* User-managed Spring transaction example:
*
* <pre>
* TransactionStatus txn = txManager
* .getTransaction(new DefaultTransactionDefinition());
* IStusDAO.delete(entity);
* txManager.commit(txn);
* entity = null;
* </pre>
*
* @see <a href =
* "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
* container-managed transaction examples</a>
* @param entity
* Stus entity to delete
* @throws RuntimeException
* when the operation fails
*/
public void delete(Stus entity);
/**
* Persist a previously saved Stus entity and return it or a copy of it to
* the sender. A copy of the Stus entity parameter is returned when the JPA
* persistence mechanism has not previously been tracking the updated
* entity. This operation must be performed within the a database
* transaction context for the entity's data to be permanently saved to the
* persistence store, i.e., database. This method uses the
* {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
* operation.
* <p>
* User-managed Spring transaction example:
*
* <pre>
* TransactionStatus txn = txManager
* .getTransaction(new DefaultTransactionDefinition());
* entity = IStusDAO.update(entity);
* txManager.commit(txn);
* </pre>
*
* @see <a href =
* "http://www.myeclipseide.com/documentation/quickstarts/jpaspring#containermanaged">Spring
* container-managed transaction examples</a>
* @param entity
* Stus entity to update
* @return Stus the persisted Stus entity instance, may not be the same
* @throws RuntimeException
* if the operation fails
*/
public Stus update(Stus entity);
public Stus findById(String id);
/**
* Find all Stus entities with a specific property value.
*
* @param propertyName
* the name of the Stus property to query
* @param value
* the property value to match
* @return List<Stus> found by query
*/
public List<Stus> findByProperty(String propertyName, Object value);
public List<Stus> findByStuName(Object stuName);
public List<Stus> findByStuAge(Object stuAge);
/**
* Find all Stus entities.
*
* @return List<Stus> all Stus entities
*/
public List<Stus> findAll();
}Stus.java
package com.undergrowth.bean;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Stus entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "STUS", schema = "UNDER")
public class Stus implements java.io.Serializable {
// Fields
private String stuId;
private String stuName;
private Double stuAge;
private Timestamp stuBirthday;
// Constructors
/** default constructor */
public Stus() {
}
/** full constructor */
public Stus(String stuId, String stuName, Double stuAge,
Timestamp stuBirthday) {
this.stuId = stuId;
this.stuName = stuName;
this.stuAge = stuAge;
this.stuBirthday = stuBirthday;
}
// Property accessors
@Id
@Column(name = "STU_ID", unique = true, nullable = false, length = 50)
public String getStuId() {
return this.stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
@Column(name = "STU_NAME", nullable = false, length = 30)
public String getStuName() {
return this.stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
@Column(name = "STU_AGE", nullable = false, precision = 0)
public Double getStuAge() {
return this.stuAge;
}
public void setStuAge(Double stuAge) {
this.stuAge = stuAge;
}
@Column(name = "STU_BIRTHDAY", nullable = false, length = 7)
public Timestamp getStuBirthday() {
return this.stuBirthday;
}
public void setStuBirthday(Timestamp stuBirthday) {
this.stuBirthday = stuBirthday;
}
@Override
public String toString() {
return "Stus [stuId=" + stuId + ", stuName=" + stuName + ", stuAge="
+ stuAge + ", stuBirthday=" + stuBirthday + "]";
}
}jpa配置文件
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_2_0.xsd"
version="2.0">
<persistence-unit name="SpringContainerPrinc"
transaction-type="RESOURCE_LOCAL">
<provider>
org.eclipse.persistence.jpa.PersistenceProvider
</provider>
<class>com.undergrowth.bean.Stus</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:ganew" />
<property name="javax.persistence.jdbc.user" value="under" />
<property name="javax.persistence.jdbc.password" value="under" />
</properties>
</persistence-unit>
</persistence>
spring配置文件
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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx"> <!-- 将EntityManagerFactory交给spring容器进行管理 --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <!-- 注入持久化单元的名称,这里的value的值 和META-INF下面的persistece.xml里面的persistence-unit的name一致 --> <property name="persistenceUnitName" value="SpringContainerPrinc" /> </bean> <!-- 使用spring的支持的jpa事务管理器管理EntityManagerFactory --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <!-- 打开事务注解的解析器 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 处理EntityManager和EntityManagerFactory的注入 This post-processor will inject sub-interfaces of EntityManagerFactory and EntityManager if the annotated fields or methods are declared as such. --> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> </bean> <!-- Bean post-processor that automatically applies persistence exception translation to any bean marked with Spring's @Repository annotation --> <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"> </bean> <!-- 使用spring管理dao --> <bean id="StusDAO" class="com.undergrowth.bean.inter.imple.StusDAO"></bean> </beans>
posted on 2014-01-28 17:24 liangxinzhi 阅读(160) 评论(0) 收藏 举报
浙公网安备 33010602011771号