0
我想了解通用DAO的最基本的級別。我得在這裏DAO創建基本的CRUD方法:通用DAO休眠Java
public interface ObjectDAO <T>{
boolean insert(T t);
boolean update(int id, T t);
boolean delete(int id);
T retrieveByID(int id);
List<T> retrieveAll();
}
但是,我無法弄清楚如何獲得ID爲我傳遞到ObjectDAOImpl類。這裏是執行:
public class ImplObjectDAO<T> implements ObjectDAO<T>{
Session session;
public ImplObjectDAO() {
session= SessionSingleton.getInstance();
}
@Override
public boolean insert(T t){
try{
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
}
catch(HibernateException he){
he.printStackTrace();
return false;
}
return true;
}
@Override
public boolean update(int id, T t) {
try{
session.beginTransaction();
session.update(t);
session.getTransaction().commit();
return true;
}
catch(HibernateException he){
he.printStackTrace();
return false;
}
catch(NullPointerException np){
np.printStackTrace();
return false;
}
}
public boolean delete(int id){
return true;
}
@Override
public <T> retrieveByID(int id){
return T;
}
@Override
public List<T> retrieveAll(){
return new ArrayList<T>(objectSet);
}
}
所以,如果我傳遞一個對象,像我創建的員工類。插入方法工作正常。但是一旦它被插入到數據庫中,我如何獲得實體的ID,以便我可以執行更新,刪除或檢索等操作?我不理解。任何幫助表示讚賞。
下面是實體類:
@Entity
@Table(name="Employee_Records")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int eID;
@Column(name="EMP_NAME", length=20)
private String empName;
@Column(name="EMPLOYEE_AGE")
private int empAge;
public Employee(){
eID= 0;
empName="temp";
empAge=0;
}
public Employee(int eID, String empName, int empAge) {
this.eID = eID;
this.empName = empName;
this.empAge = empAge;
}
public int geteID() {
return eID;
}
public void seteID(int eID) {
this.eID = eID;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpAge() {
return empAge;
}
public void setEmpAge(int empAge) {
this.empAge = empAge;
}
@Override
public String toString() {
return "Employee ID=" + eID + ", Employee Name=" + empName + ", Employee Age="
+ empAge;
}
}
是從休眠的Session類嗎?如果是這樣,我通常使用這種代碼'Session sess = getSession(); IdentifierLoadAccess byId = sess.byId(persistentClass); T實體=(T)byId.load(id); sess.update(entity); sess.delete(entity);' – irvana