Generic Data Access Objects
普通數據訪問對象
我下面的代碼與Hibernate官網上提供的有點不同
首先定義DAO類的接口IGenericDAO
java 代碼
/**
* 定義通用的CRUD操作
* @author rainlife
*/
public interface IGenericDAO 〈T
{
// 通過主鍵標識查找某個對象
public T findById(ID id);
// 通過主鍵標識查找某個對象
T findById(ID id
//得到所有的對象
List
//通過給定的一個對象
List
//持久化對象
T makePersistent(T entity);
//刪除對象
void makeTransient(T entity);
}
下面是使用Hibernate針對該接口的實現GenericDAOHibernate
java 代碼
/**
* 這是針對IGenericDAO接口的Hibernate實現
* @author rainlife
* @param
* @param
* @param
*/
public abstract class GenericDAOHibernate 〈T
implements IGenericDAO〈T
{
private Class
protected Session session;
public GenericDAOHibernate()
{
this
}
@SuppressWarnings(
public DAOImpl setSession(Session s)
{
this
return (DAOImpl)this;
}
protected Session getSession()
{
if (session == null)
throw new IllegalStateException(
return session;
}
public Class
{
return persistentClass;
}
@SuppressWarnings(
public T findById(ID id)
{
return (T) getSession()
}
@SuppressWarnings(
public T findById(ID id
{
T entity;
if (lock)
entity = (T) getSession()
else
entity = findById(id);
return entity;
}
@SuppressWarnings(
public List
{
return findByCriteria();
}
@SuppressWarnings(
public List
{
Criteria crit = getSession()
Example example = Example
crit
return crit
}
@SuppressWarnings(
public List
{
Criteria crit = getSession()
Example example = Example
for (String exclude : excludeProperty)
{
example
}
crit
return crit
}
@SuppressWarnings(
public T makePersistent(T entity)
{
getSession()
//getSession()
return entity;
}
public void makeTransient(T entity)
{
getSession()
}
@SuppressWarnings(
protected List
{
Criteria crit = getSession()
for (Criterion c : criterion)
{
crit
}
return crit
}
@SuppressWarnings(
/**
* 增加了排序的功能
*/
protected List
{
Criteria crit = getSession()
for (Criterion c : criterion)
{
crit
}
if(order!=null)
crit
return crit
}
@SuppressWarnings(
protected List
{
Criteria crit = getSession()
for (Criterion c : criterion)
{
crit
}
if(order!=null)
crit
crit
crit
return crit
}
}
這樣
比如說我們定義一個IUserDAO接口
java 代碼
public interface IUserDAO extends IGenericDAO〈User
{
public User find(String username
public User find(String username);
}
該接口從IGenericDAO繼承
再來看一下針對IUserDAO 的Hibernate實現UserDAOHibernate:
java 代碼
public class UserDAOHibernate extends GenericDAOHibernate〈User
public User find(String username
//此處省略具體代碼
}
public User find(String username) {
//此處省略具體代碼
}
}
UserDAOHibernate繼承GenericDAOHibernate並實現IUserDAO接口
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27427.html