spring+Struts+hibernate增删改查实现

package com.sykj.entity;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
//实体类
@Entity
@Table(name = "t_transportcompany")
public class Transportcompany implements Serializable {
	private int id;
	private String pname; // 物流公司名称
	private String linkman; // 联系人
	private String ptel; // 联系电话
	private String paddress; // 地址
	private int cars; // 有多少车
	private double maxweight; // 最大承受重量 /吨
	private String bankNum;// 银行卡号
	private String openBank;// 开户行
	private String bankName;// 持卡人姓名
	private String realFlag;// 物流公司审核 0:未通过 1:通过
	private Date addTime;
	private WayBillForBg wayBillForBg;
	public Date getAddTime() {
		return addTime;
	}
	public void setAddTime(Date addTime) {
		this.addTime = addTime;
	}
	@ManyToOne(/* fetch = FetchType.LAZY */)
	@JoinColumn(name = "wbfbid")
	public WayBillForBg getWayBillForBg() {
		return wayBillForBg;
	}
	public void setWayBillForBg(WayBillForBg wayBillForBg) {
		this.wayBillForBg = wayBillForBg;
	}
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public String getLinkman() {
		return linkman;
	}
	public void setLinkman(String linkman) {
		this.linkman = linkman;
	}
	public String getPtel() {
		return ptel;
	}
	public void setPtel(String ptel) {
		this.ptel = ptel;
	}
	public String getPaddress() {
		return paddress;
	}
	public void setPaddress(String paddress) {
		this.paddress = paddress;
	}
	public int getCars() {
		return cars;
	}
	public void setCars(int cars) {
		this.cars = cars;
	}
	public double getMaxweight() {
		return maxweight;
	}
	public void setMaxweight(double maxweight) {
		this.maxweight = maxweight;
	}
	public String getBankNum() {
		return bankNum;
	}
	public void setBankNum(String bankNum) {
		this.bankNum = bankNum;
	}
	public String getOpenBank() {
		return openBank;
	}
	public void setOpenBank(String openBank) {
		this.openBank = openBank;
	}
	public String getBankName() {
		return bankName;
	}
	public void setBankName(String bankName) {
		this.bankName = bankName;
	}
	public String getRealFlag() {
		return realFlag;
	}
	public void setRealFlag(String realFlag) {
		this.realFlag = realFlag;
	}
}
//接口
package com.sykj.service; 
import java.util.List;    
import com.sykj.common.page.Pagination;
import com.sykj.common.service.IBaseService;
import com.sykj.entity.Transportcompany;
import com.sykj.entity.User; 
public interface ITransportcompanyService extends IBaseService {
	/**
	 * 查找所有物流公司信息
	 * 
	 * @return yxz
	 */
	public Pagination findAll(int pageNo, int pageSize);    	
	/**
	 * 查询物流公司信息,保存到select下拉框中
	 * @return
	 */
	public Pagination findAll();    
	/**
	 * 添加物流公司信息
	 * 
	 * @return yxz
	 */
	public boolean addTC(Transportcompany tc);  
	/**
	 * 根据id 删除物流公司信息
	 * 
	 * @param id
	 * @return yxz
	 */
	public boolean del(int id);
	
	public Transportcompany findById(int id);    
	/**
	 * 根据id修改物流公司信息
	 * 
	 * @param id
	 * @return yxz
	 */
	public boolean update(Transportcompany transportcompany);  	
	public List selectCount(int pageNow);    	
	/**
	 * 验证用户手机号是否存在
	 */
	public boolean existsPhone(Transportcompany transportcompany);
}

//接口实现类

package com.sykj.service.impl;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.sykj.common.dao.Finder;
import com.sykj.common.dao.HibernateBaseDao;
import com.sykj.common.page.Pagination;
import com.sykj.entity.Transportcompany;
import com.sykj.service.ITransportcompanyService;

@Component("transportcompanyService")
@Transactional
public class TransportcompanyServiceImpl extends HibernateBaseDao
		implements ITransportcompanyService {
@Override
public Pagination findAll(int pageNo, int pageSize) {
	Pagination pagination = new Pagination();
	String hql = "from Transportcompany";
	Session session = this.getSession();
	List list = session.createQuery(hql).list();
	pagination.setList(list);
	
	return pagination;
}

@Override
public boolean addTC(Transportcompany tc) {

	return super.add(tc);
}

@Override
public boolean del(int id) {
	String hql = "delete Transportcompany t where t.id =" + id;
	getSession().createQuery(hql).executeUpdate();
	return true;
}

@Override
public boolean update(Transportcompany transportcompanyService) {
	/*
	 * String hql =
	 * "update Transportcompany set pname = :pname , linkman = :linkman , ptel = :ptel,paddress = :paddress , cars = :cars , maxweight = :maxweight,bankNum = :bankNum , openBank = :openBank , bankName = :bankName,realFlag = :realFlag where id = :id"
	 * ; this.getSession().createQuery(hql).setParameter("pname",
	 * transportcompanyService.getPname()).setParameter("linkman",
	 * transportcompanyService.getLinkman()) .setParameter("ptel",
	 * transportcompanyService.getPtel()).setParameter("paddress",
	 * transportcompanyService.getPaddress()) .setParameter("cars",
	 * transportcompanyService.getCars()).setParameter("maxweight",
	 * transportcompanyService.getMaxweight()) .setParameter("bankNum",
	 * transportcompanyService.getBankNum()).setParameter("openBank",
	 * transportcompanyService.getOpenBank()) .setParameter("bankName",
	 * transportcompanyService.getBankName()).setParameter("realFlag",
	 * transportcompanyService.getRealFlag()) .setParameter("id",
	 * transportcompanyService.getId()).executeUpdate();
	 */
	// 解决session两个对象对唯一标识冲突问题
	Transportcompany merge = (Transportcompany) this.getSession().merge(transportcompanyService);
	return super.update(merge);
}
@Override
public List selectCount(int pageNow) {
	String sql = "select count(*) from t_transportcompany";
	Query query = this.getSession().createSQLQuery(sql);
	List list = query.list();
	int totalCount = list.get(0).intValue(); // 一共totalCount条信息
	int dataNow = (pageNow - 1) * 20 - 1; // 当前第几条数据
	int totalPage = (totalCount + 20 - 1) / 20; // 总页数
	List rows = new ArrayList();
	rows.add(pageNow);// 当前页数 第几页
	rows.add(dataNow);// 当前第几条数据
	rows.add(totalCount);// 总共多少条数据
	rows.add(totalPage);// 总共多少页
	rows.add(20);// 每页几条记录
	return rows;
}

@Override
protected Class getEntityClass() {
	return Transportcompany.class;
}

@Override
public Transportcompany findById(int id) {

	return super.find(id);
}

@Override
public boolean existsPhone(Transportcompany transportcompany) {
	String hql = "from Transportcompany u where u.ptel=" + transportcompany.getPtel();
	Transportcompany tsc = (Transportcompany) getSession().createQuery(hql).uniqueResult();
	if (tsc != null)
		return true;
	else
		return false;
}

@Override
public Pagination findAll() {
	Pagination pagination = new Pagination();
	String hql = "from Transportcompany";
	Session session = this.getSession();
	List list = session.createQuery(hql).list();
	pagination.setList(list);
	return pagination;
}

}

//Action

package com.sykj.action.manage;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.sykj.common.action.BaseAction;
import com.sykj.common.page.Pagination;
import com.sykj.common.service.IBaseService;
import com.sykj.entity.Transportcompany;
import com.sykj.service.ITransportcompanyService;

public class TransportcompanyAction extends BaseAction {
	private ITransportcompanyService transportcompanyService;
	private Pagination ption;
	private Transportcompany transportcompany;
	private int pageNow;

public int getPageNow() {
	return pageNow;
}

public void setPageNow(int pageNow) {
	this.pageNow = pageNow;
}

private int id;

public int getId() {
	return id;
}

public void setId(int id) {
	this.id = id;
}
/**
 * 查找所有物流公司信息
 * @return
 */
public String findByTC() {
	ption = transportcompanyService.findAll(pageNo, pageSize);
	ActionContext context = ActionContext.getContext();
	ValueStack valueStack = context.getValueStack();
	valueStack.set("pagen", ption);	
	return "success";
}
/**
 * 删除
 * @return
 */
public String delTC() {
	flag = transportcompanyService.del(id);
	return "success";
}
public String addTC() {
	flag = transportcompanyService.addTC(transportcompany);
	return SUCCESS;
}
public String upadteTCByID() {
	System.out.println(id + "************************");
	transportcompany = transportcompanyService.findById(id);
	ActionContext context = ActionContext.getContext();
	ValueStack valueStack = context.getValueStack();
	valueStack.set("transportcompany", transportcompany);
	return SUCCESS;
}
public String upadteTC() {

	System.out.println(transportcompany.getId() + "+++++++++++");
	Transportcompany tc = transportcompanyService.findById(transportcompany.getId());
	tc.setPname(transportcompany.getPname());
	tc.setLinkman(transportcompany.getLinkman());
	tc.setPtel(transportcompany.getPtel());
	tc.setPaddress(transportcompany.getPaddress());
	tc.setCars(transportcompany.getCars());
	tc.setMaxweight(transportcompany.getMaxweight());
	tc.setBankNum(transportcompany.getBankNum());
	tc.setOpenBank(transportcompany.getOpenBank());
	tc.setBankName(transportcompany.getBankName());
	tc.setRealFlag(transportcompany.getRealFlag());
	tc.setAddTime(transportcompany.getAddTime());
	flag = transportcompanyService.update(transportcompany);
	return SUCCESS;
}
/***
 * 验证用户输入的手机号是否存在
 */
public String checkPhone() {
	this.flag = this.transportcompanyService.existsPhone(transportcompany);
	return SUCCESS;
}
/**
 * 页面跳转
 * @return
 */
public String tiaozhuan() {
	return "success";
}
public String findAllSele() {
	Pagination pagination = transportcompanyService.findAll();
	List list = (List) pagination.getList();
	HttpServletRequest request = ServletActionContext.getRequest();
	request.setAttribute("list", list);
	return SUCCESS;
}
@Override
public IBaseService baseService() {
	return null;
}
@Override
public void setObject(Transportcompany obj) {
}
@Override
public void setPagin(Pagination pagin) {
}
public Pagination getPtion() {
	return ption;
}
public void setPtion(Pagination ption) {
	this.ption = ption;
}
public ITransportcompanyService getTransportcompanyService() {
	return transportcompanyService;
}
public void setTransportcompanyService(ITransportcompanyService transportcompanyService) {
	this.transportcompanyService = transportcompanyService;
}
public Transportcompany getTransportcompany() {
	return transportcompany;
}
public void setTransportcompany(Transportcompany transportcompany) {
	this.transportcompany = transportcompany;
}

}

//增删改查工具类

package com.sykj.common.dao;

import static org.hibernate.EntityMode.POJO;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.sykj.common.page.Pagination;
import com.sykj.common.service.IBaseService;
import com.sykj.common.util.MyBeanUtils;

@Transactional
public abstract class HibernateBaseDao extends
		HibernateSimpleDao implements IBaseService {

@SuppressWarnings("unchecked")
public List findByObjList(T o) {
	try {
		String hql = "from " + this.getEntityClass().getName()
				+ " o where ";
		Finder finder = Finder.create(hql);
		finder = this.getQueryCondition(o, finder);
		return this.find(finder);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

public Pagination findByObj(T o, int pageNo, int pageSize) {
	try {
		String hql = "from " + this.getEntityClass().getName()
				+ " o where ";
		Finder finder = Finder.create(hql);
		finder = this.getQueryCondition(o, finder);
		Pagination pagin = this.find(finder, pageNo, pageSize);
		return pagin;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

/**
 * 返回字段的GET方法名称
 * 
 * @param fieldName
 * @return
 */
private String getGetterMethodName(String fieldName) {
	String field1 = fieldName.substring(0, 1);
	String field2 = fieldName.substring(1);
	return "get" + field1.toUpperCase() + field2;
}

/**
 * 拼接查询语句
 * 
 * @param user
 * @return
 * @throws Exception
 */
private Finder getQueryCondition(T o, Finder finder) throws Exception {
	/*String hql = "1=1";
	Class uc = this.getEntityClass();
	Field[] fields = uc.getDeclaredFields();
	finder.append(hql);
	for (Field field : fields) {
		Method method = uc.getMethod(getGetterMethodName(field.getName()));
		Object obj = method.invoke(o);
		if (checkObj(obj, field.getName()) && checkNotSearch(method)) {// 通过值和名称检查是否可生成查询语句
			hql = " and o." + field.getName() + "=:" + field.getName();
			finder.append(hql).setParam(field.getName(), obj);
		}
	}*/
	
	//如果传进来的对象为null,则查询所有(王立改)
	String hql = "1=1";
	finder.append(hql);

	if(o != null) {
		Class uc = this.getEntityClass();
		Field[] fields = uc.getDeclaredFields();
		for (Field field : fields) {
			Method method = uc.getMethod(getGetterMethodName(field.getName()));
			Object obj = method.invoke(o);
			if (checkObj(obj, field.getName()) && checkNotSearch(method)) {// 通过值和名称检查是否可生成查询语句
				hql = " and o." + field.getName() + "=:" + field.getName();
				finder.append(hql).setParam(field.getName(), obj);
			}
		}
	}
	return finder;
}

/**
 * 检查是否需要拼接可以为空
 * 
 * @param method
 * @return
 */
private boolean checkFieldIsNull(Method method) {

	return false;
}

/**
 * 检查是否用于生成查询
 * 
 * @param field
 * @return
 */
private boolean checkNotSearch(Method method) {
	if (method.getAnnotation(FieldNotSearch.class) != null) {
		return false;
	}
	return true;
}

private boolean checkObj(Object obj, String fieldName) {
	if (obj != null) {
		// System.out.println(obj + "  " + fieldName + "   "
		// + ("id".equals(fieldName) && !obj.equals(0)));
		if ("id".equals(fieldName)) {
			if (obj.equals(0)) {
				return false;
			} else {
				return true;
			}
		} else {
			if (!obj.equals("-1") && !obj.equals(-1) && !obj.equals(0.0f)
					&& !obj.equals(0.0d) && !"".equals(obj)) {
				return true;
			}
		}
	}
	return false;
}

public Pagination findAll(List fields, List orderByFields,
		int pageNo, int pageSize) {
	Pagination pagin = null;

	return pagin;
}

public boolean add(T o) {
	boolean flag = false;
	try {
		this.getSession().save(o);
		flag = true;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return flag;
}

public Pagination findAll(int pageNo, int pageSize) {
	String hql = "from " + this.getEntityClass().getName() + " o ";
	Finder finder = Finder.create(hql);
	Pagination pagin = this.find(finder, pageNo, pageSize);
	return pagin;
}

public boolean del(T o) {
	boolean flag = false;
	try {
		String hql = "update " + this.getEntityClass().getName()
				+ " o set o.delMark=1 where o.id="
				+ o.getClass().getMethod("getId").invoke(o);
		this.getSession().createQuery(hql).executeUpdate();
		flag = true;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return flag;
}

@SuppressWarnings("unchecked")
public T find(Integer id) {
	T t = null;
	try {
		t = (T) this.getSession().get(this.getEntityClass(), id);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return t;
}

public boolean update(T o) {
	boolean flag = false;
	try {
		this.getSession().update(o);
		flag = true;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return flag;
}

/**
 * @see Session.get(Class,Serializable)
 * @param id
 * @return 持久化对象
 */
protected T get(ID id) {
	return get(id, false);
}

/**
 * @see Session.get(Class,Serializable,LockMode)
 * @param id
 *            对象ID
 * @param lock
 *            是否锁定,使用LockMode.UPGRADE
 * @return 持久化对象
 */
@SuppressWarnings("unchecked")
protected T get(ID id, boolean lock) {
	T entity;
	if (lock) {
		entity = (T) getSession().get(getEntityClass(), id,
				LockMode.UPGRADE);
	} else {
		entity = (T) getSession().get(getEntityClass(), id);
	}
	return entity;
}

/**
 * 按属性查找对象列表
 */
@SuppressWarnings("unchecked")
protected List findByProperty(String property, Object value) {
	Assert.hasText(property);
	return createCriteria(Restrictions.eq(property, value)).list();
}

/**
 * 按属性查找唯一对象
 */
@SuppressWarnings("unchecked")
protected T findUniqueByProperty(String property, Object value) {
	Assert.hasText(property);
	Assert.notNull(value);
	return (T) createCriteria(Restrictions.eq(property, value))
			.uniqueResult();
}

/**
 * 按属性统计记录数
 * 
 * @param property
 * @param value
 * @return
 */
protected int countByProperty(String property, Object value) {
	Assert.hasText(property);
	Assert.notNull(value);
	return ((Number) (createCriteria(Restrictions.eq(property, value))
			.setProjection(Projections.rowCount()).uniqueResult()))
			.intValue();
}

/**
 * 按Criterion查询列表数据.
 * 
 * @param criterion
 *            数量可变的Criterion.
 */
@SuppressWarnings("unchecked")
protected List findByCriteria(Criterion... criterion) {
	return createCriteria(criterion).list();
}

/**
 * 通过Updater更新对象
 * 
 * @param updater
 * @return
 */
@SuppressWarnings("unchecked")
public T updateByUpdater(Updater updater) {
	ClassMetadata cm = sessionFactory.getClassMetadata(getEntityClass());
	T bean = updater.getBean();
	T po = (T) getSession().get(getEntityClass(),
			cm.getIdentifier(bean, POJO));
	updaterCopyToPersistentObject(updater, po, cm);
	return po;
}

/**
 * 将更新对象拷贝至实体对象,并处理many-to-one的更新。
 * 
 * @param updater
 * @param po
 */
private void updaterCopyToPersistentObject(Updater updater, T po,
		ClassMetadata cm) {
	String[] propNames = cm.getPropertyNames();
	String identifierName = cm.getIdentifierPropertyName();
	T bean = updater.getBean();
	Object value;
	for (String propName : propNames) {
		if (propName.equals(identifierName)) {
			continue;
		}
		try {
			value = MyBeanUtils.getSimpleProperty(bean, propName);
			if (!updater.isUpdate(propName, value)) {
				continue;
			}
			cm.setPropertyValue(po, propName, value, POJO);
		} catch (Exception e) {
			throw new RuntimeException(
					"copy property to persistent object failed: '"
							+ propName + "'", e);
		}
	}
}

/**
 * 根据Criterion条件创建Criteria,后续可进行更多处理,辅助函数.
 */
protected Criteria createCriteria(Criterion... criterions) {
	Criteria criteria = getSession().createCriteria(getEntityClass());
	for (Criterion c : criterions) {
		criteria.add(c);
	}
	return criteria;
}

/**
 * 获得Dao对于的实体类
 * 
 * @return
 */
abstract protected Class getEntityClass();

}

//配置


/WEB-INF/jsp/transportcompany/Transportcompany.jsp tc/findByTC tc/findByTC tc/findByTC
	
		
			flag
		
	
	
		/WEB-INF/jsp/transportcompany/upTC.jsp
		
	

	
		/WEB-INF/jsp/dispatch/dispatch.jsp
		
	
	
		/WEB-INF/jsp/dispatch/dispatch.jsp
		
	

你可能感兴趣的:(java)