addressdaohibernate.java

来自「使用struts2及Spring框架对数据库表进行增删改查操作」· Java 代码 · 共 89 行

JAVA
89
字号
package crud.dao;

import crud.model.Address;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 *	Implementation of the {@link AddressDao} interface which interacts with
 *	Spring and Hibernate to map a {@link crud.model.Address} object to the 
 *	<em>AddressBook</em> *	table in the data store. This class provides a 
 *	basic set of CRUD methods for accessing the address table.
 *
 * 	@see crud.model.Address
 *	@author <a href="mailto:kevin@rkcole.com">R. Kevin Cole</a>
 */
public final class AddressDaoHibernate extends HibernateDaoSupport implements AddressDao
{
	/**	Remove a address with the given identifier.
	 * 	@param	addr the address to be removed.
	 * 	@see crud.model.Address
	 * 	@return	a count of the affected rows.
	 */
	public int deleteAddress( Address addr ) 
	{
		String hql = "delete from Address where id = :id";
        Query query = getSession().createQuery(hql);
        query.setLong("id", addr.getId() );
        return query.executeUpdate();
	}


	/**	Save or update an address in the data store.
	 * 	@param addr the Address to be saved.
	 * 	@see crud.model.Address
	 * 	@return	a count of the affected rows.
	 */
	public void updateAddress( Address addr )
	{
        getHibernateTemplate().saveOrUpdate(addr);
	}


	/**
	 * 	Search for address records matching the given example.
	 * 	@return a list of Addresses that match the search criteria.
	 * 	@see crud.model.Address
	 */
    public List getAddress( Address addr ) 
	{
		final List list = new ArrayList();

		if( addr == null )
			return list;

		Criteria criteria = getSession().createCriteria(Address.class);
		if(addr.getName() != null && addr.getName().length() > 0 ) 
		{
			criteria.add(Restrictions.eq("name", addr.getName() ) );
		}
		if(addr.getAddress() != null && addr.getAddress().length() > 0 ) 
		{
			criteria.add(Restrictions.eq("address", addr.getAddress() ) );
		}
		if(addr.getCity() != null && addr.getCity().length() > 0 ) 
		{
			criteria.add(Restrictions.eq("city", addr.getCity() ) );
		}
		if(addr.getState() != null && addr.getState().length() > 0 ) 
		{
			criteria.add(Restrictions.eq("state", addr.getState() ) );
		}
		if(addr.getZipcode() != null && addr.getZipcode().length() > 0 ) 
		{
			criteria.add(Restrictions.eq("zipcode", addr.getZipcode() ) );
		}
		return criteria.list();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?