Service层设计
service层接口设计
1.DAO
package cn.itcast.service;
import java.io.Serializable;
import java.util.LinkedHashMap;
import cn.itcast.bean.QueryResult;
/**
* 实体操作通用接口
*
* @param <T> 实体类型
*/
public interface DAO<T> {
/**
* 分页获取所有记录
* @return
*/
public QueryResult<T> getScrollData();
/**
* 分页获取记录
* @param firstResult 开始索引,如果输入值为-1,即获取全部数据
* @param maxResult 每页获取的记录数,如果输入值为-1,即获取全部数据
* @return
*/
public QueryResult<T> getScrollData(int firstResult, int maxResult);
/**
* 分页获取记录
* @param firstResult 开始索引,如果输入值为-1,即获取全部数据
* @param maxResult 每页获取的记录数,如果输入值为-1,即获取全部数据
* @param orderby 排序,Key为排序属性,Value为asc/desc,如:
* LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
orderby.put("email", "asc");
orderby.put("password", "desc");
* @return
*/
public QueryResult<T> getScrollData(int firstResult, int maxResult, LinkedHashMap<String, String> orderby);
/**
* 分页获取记录
* @param firstResult 开始索引,如果输入值为-1,即获取全部数据
* @param maxResult 每页获取的记录数,如果输入值为-1,即获取全部数据
* @param where 条件语句,不带where关键字,条件语句只能使用位置参数,位置参数的索引值以1开始,如:o.username=?1 and o.password=?2
* @param params 条件语句出现的位置参数值
* @return
*/
public QueryResult<T> getScrollData(int firstResult, int maxResult, String where, Object[] params);
/**
* 分页获取记录
* @param firstResult 开始索引,如果输入值为-1,即获取全部数据
* @param maxResult 每页获取的记录数,如果输入值为-1,即获取全部数据
* @param where 条件语句,不带where关键字,条件语句只能使用位置参数,位置参数的索引值以1开始,如:o.username=?1 and o.password=?2
* @param params 条件语句出现的位置参数值
* @param orderby 排序,Key为排序属性,Value为asc/desc,如:
* LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
orderby.put("email", "asc");
orderby.put("password", "desc");
* @return
*/
public QueryResult<T> getScrollData(int firstResult, int maxResult, String where, Object[] params, LinkedHashMap<String, String> orderby);
/**
* 保存实体
* @param entity 实体对象
*/
public void save(T entity);
/**
* 更新实体
* @param entity 实体对象
*/
public void update(T entity);
/**
* 删除实体
* @param entityid 实体标识
*/
public void delete(Serializable entityid);//JPA 规定实体的id属性必须实现序列化接口
/**
* 获胜实体
* @param entityid 实体标识
* @return 实体对象
*/
public T find(Serializable entityid);
/**
* 获取实体的总记录数
* @return 总记录数
*/
public long getCount();
}
ArticalService
package cn.itcast.service;
import cn.itcast.bean.db.Artical;
public interface ArticalService extends DAO<Artical> {
}
ArticalTypeService
package cn.itcast.service;
import cn.itcast.bean.db.ArticalType;
public interface ArticalTypeService extends DAO<ArticalType>{
}
FriendService
package cn.itcast.service;
import cn.itcast.bean.db.Friend;
public interface FriendService extends DAO<Friend> {
}
MasterService
package cn.itcast.service;
import cn.itcast.bean.db.Master;
public interface MasterService extends DAO<Master> {
}
PhotoService
package cn.itcast.service;
import cn.itcast.bean.db.Photo;
public interface PhotoService extends DAO<Photo> {
}
ReviewServcie
package cn.itcast.service;
import cn.itcast.bean.db.Review;
public interface ReviewServcie extends DAO<Review> {
}
WordService
package cn.itcast.service;
import cn.itcast.bean.db.Word;
public interface WordService extends DAO<Word> {
}
Servcie实现类设计
DaoSuppout
package cn.itcast.service.base;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
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 cn.itcast.bean.QueryResult;
import cn.itcast.service.DAO;
import cn.itcast.utils.GenericsUtils;
@SuppressWarnings("unchecked")
@Transactional
public abstract class DaoSupport<T> implements DAO<T> {
@PersistenceContext protected EntityManager em;
/* 实体类 */
protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(getClass());
public QueryResult<T> getScrollData(){
return getScrollData(-1, -1, null, null, null);
}
public QueryResult<T> getScrollData(int firstResult, int maxResult){
return getScrollData(firstResult, maxResult, null, null, null);
}
public QueryResult<T> getScrollData(int firstResult, int maxResult, LinkedHashMap<String, String> orderby){
return getScrollData(firstResult, maxResult, null, null, orderby);
}
public QueryResult<T> getScrollData(int firstResult, int maxResult, String where, Object[] params){
return getScrollData(firstResult, maxResult, where, params, null);
}
public QueryResult<T> getScrollData(int firstResult, int maxResult, String where, Object[] params, LinkedHashMap<String, String> orderby){
String entityName = getEntityName(entityClass);
String whereql = where!=null && !"".equals(where.trim()) ? " where "+ where : "" ;
Query query = em.createQuery("select o from "+ entityName +" o" + whereql + buildOrderby(orderby));
if(firstResult!=-1 && maxResult!=-1) query.setFirstResult(firstResult).setMaxResults(maxResult);
setQueryParameter(query, params);
QueryResult<T> qr = new QueryResult<T>();
qr.setResultlist(query.getResultList());
query = em.createQuery("select count(o) from "+ entityName +" o"+ whereql);
setQueryParameter(query, params);
qr.setRecordtotal((Long)query.getSingleResult());
return qr;
}
/**
* 设置查询参数
* @param query 查询对象
* @param params 参数值
*/
public static void setQueryParameter(Query query, Object[] params){
if(params!=null){
for(int i = 0; i < params.length ; i++){
query.setParameter(i+1, params[i]);
}
}
}
/**
* 构建排序语句
* @param orderby 排序属性与asc/desc, Key为属性,Value为asc/desc
* @return
*/
public static String buildOrderby(LinkedHashMap<String, String> orderby){
StringBuilder sb = new StringBuilder();
if(orderby!=null && !orderby.isEmpty()){
sb.append(" order by ");
for(Map.Entry<String, String> entry : orderby.entrySet()){
sb.append("o.").append(entry.getKey()).append(" ").append(entry.getValue()).append(',');
}
sb.deleteCharAt(sb.length()-1);
}
return sb.toString();
}
public void delete(Serializable entityid) {
em.remove(em.getReference(entityClass, entityid));
}
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public T find(Serializable entityid) {
return em.find(entityClass, entityid);
}
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public long getCount() {
return (Long)em.createQuery("select count(o) from " + getEntityName(this.entityClass) + " o").getSingleResult();
}
/**
* 获取实体名称
* @return
*/
protected static <E> String getEntityName(Class<E> entityClass){
String entityName = entityClass.getSimpleName();
Entity entity = entityClass.getAnnotation(Entity.class);
if(entity.name()!=null && !"".equals(entity.name())) entityName = entity.name();
return entityName;
}
public void save(T entity) {
em.persist(entity);
}
public void update(T entity) {
em.merge(entity);
}
}
Master实现类
package cn.itcast.service.impl;
import java.io.Serializable;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.itcast.bean.db.Master;
import cn.itcast.service.MasterService;
import cn.itcast.service.base.DaoSupport;
@Service
public class MasterServiceImpl extends DaoSupport<Master> implements MasterService{
@Override
public void delete(Serializable entityid) {
// TODO Auto-generated method stub
super.delete(entityid);
}
@Override
public Master find(Serializable entityid) {
// TODO Auto-generated method stub
return super.find(entityid);
}
@Override
public void save(Master entity) {
// TODO Auto-generated method stub
super.save(entity);
}
@Override
public void update(Master entity) {
// TODO Auto-generated method stub
super.update(entity);
}
}
其他的实现类分别实现其Service接口,继承DaoSupport,就不在发表其他实现类代码
Util层设计
GenericsUtils
package cn.itcast.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* ��������
* @author lihuoming
*
*/
public class GenericsUtils {
/**
* ͨ����,���ָ����ĸ���ķ��Ͳ����ʵ������. ��BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz ��Ҫ�������,�������̳з�����
* @param index ���Ͳ�����������,��0��ʼ.
* @return ���Ͳ����ʵ������, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ���<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();//�õ�������
//���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�ֱ�ӷ���Object.class
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
//���ر�ʾ������ʵ�����Ͳ����Type���������,������ŵĶ��Ƕ�Ӧ���͵�Class, ��BuyerServiceBean extends DaoSupport<Buyer,Contact>�ͷ���Buyer��Contact����
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("�����������"+ (index<0 ? "����С��0" : "�����˲��������"));
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
/**
* ͨ����,���ָ����ĸ���ĵ�һ�����Ͳ����ʵ������. ��BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz ��Ҫ�������,�������̳з�����
* @return ���Ͳ����ʵ������, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ���<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz,0);
}
/**
* ͨ����,��÷�������ֵ���Ͳ����ʵ������. ��: public Map<String, Buyer> getNames(){}
*
* @param Method method ����
* @param int index ���Ͳ�����������,��0��ʼ.
* @return ���Ͳ����ʵ������, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ���<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method, int index) {
Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
if (index >= typeArguments.length || index < 0) {
throw new RuntimeException("�����������"+ (index<0 ? "����С��0" : "�����˲��������"));
}
return (Class)typeArguments[index];
}
return Object.class;
}
/**
* ͨ����,��÷�������ֵ��һ�����Ͳ����ʵ������. ��: public Map<String, Buyer> getNames(){}
*
* @param Method method ����
* @return ���Ͳ����ʵ������, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ���<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method) {
return getMethodGenericReturnType(method, 0);
}
/**
* ͨ����,��÷�����������index�������������з��Ͳ����ʵ������. ��: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method ����
* @param int index �ڼ����������
* @return �������ķ��Ͳ����ʵ�����ͼ���, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ��ؿռ���
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
List<Class> results = new ArrayList<Class>();
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (index >= genericParameterTypes.length ||index < 0) {
throw new RuntimeException("�����������"+ (index<0 ? "����С��0" : "�����˲��������"));
}
Type genericParameterType = genericParameterTypes[index];
if(genericParameterType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for(Type parameterArgType : parameterArgTypes){
Class parameterArgClass = (Class) parameterArgType;
results.add(parameterArgClass);
}
return results;
}
return results;
}
/**
* ͨ����,��÷�����������һ�������������з��Ͳ����ʵ������. ��: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method ����
* @return �������ķ��Ͳ����ʵ�����ͼ���, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ��ؿռ���
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method) {
return getMethodGenericParameterTypes(method, 0);
}
/**
* ͨ����,���Field���Ͳ����ʵ������. ��: public Map<String, Buyer> names;
*
* @param Field field �ֶ�
* @param int index ���Ͳ�����������,��0��ʼ.
* @return ���Ͳ����ʵ������, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ���<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getFieldGenericType(Field field, int index) {
Type genericFieldType = field.getGenericType();
if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
if (index >= fieldArgTypes.length || index < 0) {
throw new RuntimeException("�����������"+ (index<0 ? "����С��0" : "�����˲��������"));
}
return (Class)fieldArgTypes[index];
}
return Object.class;
}
/**
* ͨ����,���Field���Ͳ����ʵ������. ��: public Map<String, Buyer> names;
*
* @param Field field �ֶ�
* @param int index ���Ͳ�����������,��0��ʼ.
* @return ���Ͳ����ʵ������, ���û��ʵ��ParameterizedType�ӿڣ�����֧�ַ��ͣ�����ֱ�ӷ���<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getFieldGenericType(Field field) {
return getFieldGenericType(field, 0);
}
}
MyFielUtil
实现file-byte[]和byte[]-file之间的转换,为图片保存到数据库做准备
package cn.itcast.utils;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MyFileUtils {
public static byte[] fileTobyte(File file)
{
BufferedInputStream in=null;
try {
in = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
byte[] content = out.toByteArray();
return content;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public static File byteTofail(byte[] b,String filepath)
{
File file=new File(filepath);
FileOutputStream fos=null;
try {
fos=new FileOutputStream(file);
fos.write(b);
return file;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
ps:DAO DAOSupport GenericsUtils为csdn中BaBaSport中的源码