您的位置:首页 > 编程语言 > Java开发

spring jpa 的配置及使用实例

2010-01-25 23:58 453 查看
jdbc.propperties配置文件如下:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testdatabase?useUnicode=true&characterEncoding=UTF-8
username=root
password=1
initialSize=1
maxActive=100
maxIdle=8
minIdle=1

beans.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: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/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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:component-scan base-package="com.leo"/>
<context:property-placeholder location="classpath:jdbc.properties"/>

<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}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
</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="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

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

srt/META-INF目录下persistence.xml 如下:

<?xml version="1.0"?>
<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="leo" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.jdbc.fetch_size" value="18"/>
<property name="hibernate.jdbc.batch_size" value="10"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.format_sql" value="false"/>
</properties>
</persistence-unit>
</persistence>

juint.test

package junit.test;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.leo.bean.product.ProductType;
import com.leo.service.product.ProductTypeService;
import com.leo.service.product.impl.ProductTypeServiceBean;

public class ProductTest {
private static ApplicationContext ctx;
private static ProductTypeService productService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ctx= new ClassPathXmlApplicationContext("beans.xml");
productService=(ProductTypeService)ctx.getBean("productTypeServiceBean");
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
@Test public void testSave(){
ProductType type = new ProductType();
type.setName("passketball用品");
type.setNote("好产品�");
productService.save(type);

//productService.save(new ProductType());
//DataSource productService=(DataSource)ctx.getBean("dataSource");
//System.out.print(productService);
}
@Test public void testFind(){
ProductType type = productService.find(ProductType.class,1);
Assert.assertNotNull("获取不到id为1的记录",type);
}
@Test public void testUpdate(){
ProductType type = productService.find(ProductType.class,1);
type.setName("45645645");
type.setNote("fdg�");
productService.update(type);
}
@Test public void testDelete(){
productService.delete(ProductType.class,1);
}
}
产品类型实体如下:

package com.leo.bean.product;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class ProductType implements Serializable{
/**����id**/
private Integer typeid;
/**������**/
private String name;
/**��ע������google����ҳ������**/
private String note;
/**�Ƿ�ɼ�**/
private Boolean visible=true;
/**子类别**/
private Set<ProductType> childtype =new HashSet<ProductType>();
/**所属父类**/
private ProductType parent;

@Column(length=36,nullable=false)
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
@Column(length=200)
public String getNote() {
return note;
}

public void setNote(String note) {
this.note = note;
}
@Column(nullable=false)
public Boolean getVisible() {
return visible;
}

public void setVisible(Boolean visible) {
this.visible = visible;
}

@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Integer getTypeid() {
return typeid;
}

public void setTypeid(Integer typeid) {
this.typeid = typeid;
}

@OneToMany(cascade={CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="parent")
public Set<ProductType> getChildtype() {
return childtype;
}
public void setChildtype(Set<ProductType> childtype) {
this.childtype = childtype;
}
@ManyToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name="parentid")
public ProductType getParent() {
return parent;
}

public void setParent(ProductType parent) {
this.parent = parent;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((typeid == null) ? 0 : typeid.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductType other = (ProductType) obj;
if (typeid == null) {
if (other.typeid != null)
return false;
} else if (!typeid.equals(other.typeid))
return false;
return true;
}
}
**************

//公共DAO

package com.leo.service.base;

public interface DAO {

/**
*保存实体
* @param entity
*/
public void save(Object entity);
public void update(Object entity);
public <T> void delete(Class<T> entityClass,Object entityid);
public <T> void delete(Class<T> entityClass,Object[] entityids);

public <T> T find(Class<T> entityClass,Object entityID);
}

_____________

package com.leo.service.base;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public abstract class DaoSupport implements DAO{
@PersistenceContext protected EntityManager em;

public void save(Object entity) {
// TODO Auto-generated method stub
em.persist(entity);
}

public <T> void delete(Class<T> entityClass,Object entityid) {
delete(entityClass,new Object[]{entityid});
}

public <T> void delete(Class<T> entityClass,Object[] entityids) {
for(Object id:entityids){
em.remove(em.getReference(entityClass, id));
}

}
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> T find(Class<T> entityClass, Object entityID) {
return em.find(entityClass, entityID);
}

public void update(Object entity) {
// TODO Auto-generated method stub
em.merge(entity);
}

}

_____________package com.leo.service.product;

import com.leo.bean.product.ProductType;
import com.leo.service.base.DAO;

public interface ProductTypeService extends DAO{

}

____________

package com.leo.service.product.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.leo.service.base.DaoSupport;
import com.leo.service.product.ProductTypeService;

@Service
@Transactional
public class ProductTypeServiceBean extends DaoSupport implements ProductTypeService {

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐