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 {
}
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 {
}
相关文章推荐
- spring List,Set,Map,Properties,array的使用配置文件注入实例
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(五):使用@Component 来简化bean的配置
- spring cloud使用spring data jpa配置druid做数据源和监控
- spring与jpa整合 简化persistence.xml配置文件 使用属性文件 数据源dbcp访问数据库
- 使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例、Java提供了Class类获取类别的字段和方法,包括构造方法
- 使用spring-data-jpa的JpaRepository来进行类的db操作(配置)
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(四):使用 命名空间 简化配置
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(五):使用@Component 来简化bean的配置
- 使用spring-boot-starter-data-jpa 怎么配置使运行时输出SQL语句
- 使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例、Java提供了Class类获取类别的字段和方法,包括构造方法
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(五):使用@Component 来简化bean的配置
- spring+hibernate 二级缓存 配置+java使用实例
- 使用spring-boot-starter-data-jpa 怎么配置使运行时输出SQL语句
- 使用spring-boot-starter-data-jpa 怎么配置使运行时输出SQL语句
- Spring学习之使用静态工厂方法以及实例工厂方法配置bean
- SpringBoot 使用yml配置 mybatis+pagehelper+druid+freemarker实例
- Spring boot 使用jpa时对于数据库的配置
- spring+hibernate 二级缓存 配置+java使用实例
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(四):使用 命名空间 简化配置
- 使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例