ProductType的JPA映射
package com.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 {
/**
* 实体bean应用到ejb3,便于网络传送。
*/
private static final long serialVersionUID = -3711997324115011724L;
private Integer typeid;
private String name;
//google 描述
private String note;
private boolean visible = true;
//子类别
private Set<ProductType> childTypes = new HashSet<ProductType>();
//父类别
private ProductType parent;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
@Column(length = 36 , nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(length = 300)
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Column(nullable = false)
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
@OneToMany(cascade = {CascadeType.REFRESH,CascadeType.REMOVE}, mappedBy="parent")
public Set<ProductType> getChildTypes() {
return childTypes;
}
public void setChildTypes(Set<ProductType> childTypes) {
this.childTypes = childTypes;
}
//false:不是可选的=必须要有。true是可选的,可以没有。默认下为true
@ManyToOne(cascade = (CascadeType.REFRESH),optional = true )
@JoinColumn(name="parentid")
public ProductType getParent() {
return parent;
}
public void setParent(ProductType parent) {
this.parent = parent;
}
/* 对象之间的比较,所以需要重写hashCode and equals
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((typeid == null) ? 0 : typeid.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductType other = (ProductType) obj;
if (typeid == null) {
if (other.typeid != null)
return false;
} else if (!typeid.equals(other.typeid))
return false;
return true;
}
}
实现ProductTypeService和ProductTypeServiceImp
a.创建DAO接口,实现增删改查代码的服用
/**
*
*/
package com.service.base;
import java.util.LinkedHashMap;
import com.bean.QueryResult;
/**
* @author zhangsm
*
*/
public interface DAO {
public void save(Object entity);
public <T> void delete(Class <T> entityClass ,Object entityid);
public <T> void delete(Class <T> entityClass ,Object[] entityids);
public void update(Object entity);
public <T> T find(Class <T> entityClass , Object entityId);
//分页封装
public <T> QueryResult<T> getStrollData(Class<T> entityClass,
int firstIndex, int maxResult , String whereSql, Object[] queryParams , LinkedHashMap<String, String> orderby);
public <T> QueryResult<T> getStrollData(Class<T> entityClass,
int firstIndex, int maxResult , LinkedHashMap<String, String> orderby);
public <T> QueryResult<T> getStrollData(Class<T> entityClass,
int firstIndex, int maxResult , String whereSql, Object[] queryParams );
public <T> QueryResult<T> getStrollData(Class<T> entityClass,int firstIndex, int maxResult );
public <T> QueryResult<T> getStrollData(Class<T> entityClass);
}
创建DAOSupport抽象类,为以后类实现DAO接口提供方便
package com.service.base; import java.util.LinkedHashMap; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.bean.QueryResult; /** * @author zhangsm * */ @Transactional public abstract class DaoSupport implements DAO { @PersistenceContext protected EntityManager em ; @Override public void save(Object entity) { em.persist(entity); } @Override public <T> void delete(Class<T> entityClass, Object entityid) { delete(entityClass, new Object[]{entityid}); } @Override public <T> void delete(Class<T> entityClass, Object[] entityids) { for(Object id : entityids){ em.remove(em.getReference(entityClass, id)); } } @Override public void update(Object entity ) { em.merge(entity); } @Override @Transactional(readOnly = true , propagation = Propagation.NOT_SUPPORTED) public <T> T find(Class<T> entityClass, Object entityId) { return em.find(entityClass, entityId); } @Override @Transactional(readOnly = true ,propagation = Propagation.NOT_SUPPORTED) public <T> QueryResult<T> getStrollData(Class<T> entityClass, int firstIndex, int maxResult, LinkedHashMap<String, String> orderby) { return getStrollData(entityClass, firstIndex, maxResult, null, null, orderby); } @Override @Transactional(readOnly = true ,propagation = Propagation.NOT_SUPPORTED) public <T> QueryResult<T> getStrollData(Class<T> entityClass, int firstIndex, int maxResult, String whereSql, Object[] queryParams) { return getStrollData(entityClass, firstIndex, maxResult, whereSql, queryParams, null); } @Override @Transactional(readOnly = true ,propagation = Propagation.NOT_SUPPORTED) public <T> QueryResult<T> getStrollData(Class<T> entityClass, int firstIndex, int maxResult) { return getStrollData(entityClass, firstIndex, maxResult, null, null, null); } @Override @Transactional(readOnly = true ,propagation = Propagation.NOT_SUPPORTED) public <T> QueryResult<T> getStrollData(Class<T> entityClass) { return getStrollData(entityClass, -1, -1); } @SuppressWarnings("unchecked") @Override @Transactional(readOnly = true ,propagation = Propagation.NOT_SUPPORTED) public <T> QueryResult<T> getStrollData(Class<T> entityClass, int firstIndex, int maxResult , String whereSql, Object[] queryParams , LinkedHashMap<String, String> orderby) { @SuppressWarnings("rawtypes") QueryResult qr = new QueryResult<T>(); String entityName = getEntityName(entityClass); Query query = em.createQuery("select p from "+ entityName +" p " +(whereSql == null ? "" : "where " + whereSql) + buildOderby(orderby)); setQueryParams(query, queryParams); if(firstIndex != -1 && maxResult != -1) query.setFirstResult(firstIndex).setMaxResults(maxResult); qr.setResultList(query.getResultList()); query = em.createQuery("select count(p) from " + entityName +" p " + (whereSql == null ? "" : "where " + whereSql)); setQueryParams(query, queryParams); qr.setTotalRecord((Long)query.getSingleResult()); return qr; } protected void setQueryParams(Query query , Object[] queryParams){ if (null != queryParams && queryParams.length > 0) { for(int i = 0 ; i < queryParams.length ; i++){ query.setParameter(i+1, queryParams[i]); } } } //get orderby sql protected String buildOderby(LinkedHashMap<String, String> orderby){ StringBuffer orderbysql = new StringBuffer(""); if(null != orderby && orderby.size() > 0){
for(String key : orderby.keySet()){orderbysql.append(" p.").append(key).append(" ").append(orderby.get(key)).append(",");}orderbysql.deleteCharAt(orderbysql.length()-1);}return orderbysql.toString();}// get entityprotected <T> String getEntityName(Class<T> entityClass) {String entityName = entityClass.getSimpleName();Entity entity = entityClass.getAnnotation(Entity.class);if(null != entity.name() && !"".equals(entity.name())){entityName = entity.name();}return entityName;}}orderbysql.append(" order by ");
创建ProductTypeService接口package com.service.product; import com.service.base.DAO; public interface ProductService extends DAO { }
创建ProductTypeServiceImpl类
package com.service.product.imp; import javax.persistence.Query; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.service.base.DaoSupport; import com.service.product.ProductService; @Service @Transactional public class ProductTypeServiceBean extends DaoSupport implements ProductService { @Override public <T> void delete(Class<T> entityClass, Object[] entityids) { if(null != entityids && entityids.length > 0){ StringBuffer jpsql = new StringBuffer(); for(int i = 0 ; i < entityids.length ; i++){ jpsql.append("?").append(i+2).append(","); } jpsql.deleteCharAt(jpsql.length()-1); Query query = em.createQuery("update ProductType p set p.visible = ?1 where p.typeid in( " + jpsql.toString()+")").setParameter(1, false); for(int i = 0 ; i < entityids.length ; i++){ query.setParameter(i+2, entityids[i]); } query.executeUpdate(); } } }
覆盖DAOSupport的delete方法
package com.service.product.imp; import javax.persistence.Query; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.service.base.DaoSupport; import com.service.product.ProductService; @Service @Transactional public class ProductTypeServiceBean extends DaoSupport implements ProductService { @Override public <T> void delete(Class<T> entityClass, Object[] entityids) { if(null != entityids && entityids.length > 0){ StringBuffer jpsql = new StringBuffer(); for(int i = 0 ; i < entityids.length ; i++){ jpsql.append("?").append(i+2).append(","); } jpsql.deleteCharAt(jpsql.length()-1); Query query = em.createQuery("update ProductType p set p.visible = ?1 where p.typeid in( " + jpsql.toString()+")").setParameter(1, false); for(int i = 0 ; i < entityids.length ; i++){ query.setParameter(i+2, entityids[i]); } query.executeUpdate(); } } }
测试ProductTypeServiceImplpackage com.test; import java.util.LinkedHashMap; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bean.QueryResult; import com.bean.product.ProductType; import com.service.product.ProductService; public class ProdutctTest { private static ApplicationContext acx; private static ProductService productService; @BeforeClass public static void setUpBeforeClass() throws Exception { try { acx = new ClassPathXmlApplicationContext("beans.xml"); productService = (ProductService) acx.getBean("productTypeServiceBean"); } catch (Exception e) { e.printStackTrace(); } } @Test public void saveTest() { for(int i = 0 ; i< 20 ; i++ ){ ProductType productType = new ProductType(); productType.setName("家电用品"); productType.setNote("空调好啊"); productService.save(productType); } } @Test public void findTest() { ProductType productType = productService.find(ProductType.class, 1); Assert.assertNotNull("获取不到id为1的记录",productType); } @Test public void updateTest() { ProductType productType = productService.find(ProductType.class, 1); productType.setName("家电用品好吗"); productType.setNote("还是彩电好啊"); productService.update(productType); } @Test public void deleteTest() { productService.delete(ProductType.class, 1); } @Test public void scrollDataTest() { LinkedHashMap<String ,String > orderby = new LinkedHashMap<String, String>(); orderby.put("typeid", "asc"); QueryResult<ProductType> qr = productService.getStrollData(ProductType.class); for(ProductType t : qr.getResultList()){ System.out.println(t.getTypeid()+" "+t.getName()); } } }
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <aop:aspectj-autoproxy/> <context:component-scan base-package="com"/> <!-- 使用数据源和指定persistence.xml位置的方式创建entityManagerFactory,如果使用的不是hibernate JPA实现, 需要在tomcat作一些特殊配置.具体参考手册 注意:使用该方式需要把persistence.xml中的hibernate.connection.driver_class,hibernate.connection.username,hibernate.connection.password,hibernate.connection.url配置删除 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eshop?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123"/> <!-- 初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> </bean> <bean id="emf" 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="emf"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>