前幾天用eclipse下產生的Hibernate DAO做了一個實現的增刪查改的小例子,在這裡解釋下產生DAO中的幾個方法到底是做什麼用的.
這裡我將以注釋的形式在下面的這段java代碼中解釋.
package dao;
/** */ /**
* 很簡單引入你要用的包
*/
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
/** */ /**
* 類UsertableDAO繼承了BaseHibernateDAO
*/
public class UsertableDAO extends BaseHibernateDAO ... {
private static final Log log = LogFactory.getLog(UsertableDAO.class);
public static final String NAME = "name";
public static final String AGE = "age";
/** *//**
* save()方法提供了向資料庫中添加資料的功能,但只能添加,這個DAO沒有產生Update()的方法
* 但你可以簡單的八save()方法改稱具有Update功能:將getSession().save
* (transientInstance);這句改成
* getSession().merge(transientInstance);或者getSession().saveOrUpdate
* (transientInstance);
*/
public void save(Usertable transientInstance) ...{
log.debug("saving Usertable instance");
try ...{
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) ...{
log.error("save failed", re);
throw re;
}
}
/** *//**
* delete()方法看名知意是用來刪除的.
*/
public void delete(Usertable persistentInstance) ...{
log.debug("deleting Usertable instance");
try ...{
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) ...{
log.error("delete failed", re);
throw re;
}
}
/** *//**
* findById()方法實現了按ID查詢資料.
*/
public Usertable findById(java.lang.Integer id) ...{
log.debug("getting Usertable instance with id: " + id);
try ...{
Usertable instance = (Usertable) getSession().get("dao.Usertable",
id);
return instance;
} catch (RuntimeException re) ...{
log.error("get failed", re);
throw re;
}
}