巴巴运动网学习札记三之产品分类实体对象基本属性的JPA映射,用泛型技术对产品分类的业务管理Bean抽象,单元测试产品分类的业务管理Bean.重载业务管理Bean的删除方法

巴巴运动网学习笔记三之产品分类实体对象基本属性的JPA映射,用泛型技术对产品分类的业务管理Bean抽象,单元测试产品分类的业务管理Bean.,重载业务管理Bean的删除方法,

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("");
		orderbysql.append(" order by ");
		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 entity
	protected <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;
	}

	
	

}

创建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();
		}
	}


}

测试ProductTypeServiceImpl

package 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());
		}
	}

}