我用下面的方法獲取預定義的對象。Hibernate:如何讓預定義的對象通過參數傳遞一個字符串值
public Patient getUserNameAndPassword(String username, Session session) {
Patient patient=(Patient)session.get(Patient.class,username);
return patient;
}
執行此方法後,生成以下異常。
org.hibernate.TypeMismatchException: Provided id of the wrong type for class beans.Patient. Expected: class java.lang.Integer, got class java.lang.String
PatientService.java
public class PatientService {
private static PatientDAOInterface patientDAOInterface;
public PatientService() {
patientDAOInterface = new PatientDAOImpl();
}
public Session getSession() {
Session session = patientDAOInterface.openCurrentSession();
return session;
}
public Transaction getTransaction(Session session) {
return patientDAOInterface.openTransaction(session);
}
public Patient getUserNameAndPassword(String username){
Session session = patientDAOInterface.openCurrentSession();
Transaction transaction = null;
Patient patient=new Patient();
try{
transaction = patientDAOInterface.openTransaction(session);
patient=patientDAOInterface.getUserNameAndPassword(username, session);
transaction.commit();
}catch(Exception ex){
ex.printStackTrace();
}finally{
session.close();
}
return patient;
}
}
PatientDAOInterface的.java
public interface PatientDAOInterface
{
public Patient getUserNameAndPassword(String username,Session session);
public Session openCurrentSession();
public Transaction openTransaction(Session session);
}
PatientDAOImpl.java
public class PatientDAOImpl implements PatientDAOInterface {
@Override
public Patient getUserNameAndPassword(String username, Session session) {
Patient patient=(Patient)session.get(Patient.class,username);
return patient;
}
private static final SessionFactoryBuilder sessionFactoryBuilder = SessionFactoryBuilder.getInstance();
@Override
public Session openCurrentSession() {
Session currentSession = sessionFactoryBuilder.getSessionFactory().openSession();
return currentSession;
}
@Override
public Transaction openTransaction(Session session) {
Transaction beginTransaction = session.beginTransaction();
return beginTransaction;
}
}
我已經提到過我的作品了。
其實,我想通過參數傳遞一個字符串並獲得一個Patient對象。 我熟悉通過Integer
而不是String
。但我不知道這件事。
有什麼想法?
看起來您已經創建了一個使用整數並傳遞字符串來獲取Patient對象的方法。請提供有關您的session.get(Patient.class,用戶名)方法如何工作的更準確信息。 –