錯誤: 類型Session中的方法get(Class,Serializable)不適用於參數(Class,int)?當我想從表中獲取數據我得到這個錯誤。誰能幫我?
public class Test {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Transaction trx = session.beginTransaction();
Sample sample = new Sample();
sample = (Sample)session.get(Sample.class, 1);
trx.commit();
System.out.println("success");
session.close();
}
}
public class Sample {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
正如錯誤中所述,第二個參數不能只是一個Integer,但它必須事先定義爲Serializable。我最好的建議是爲這個普通查詢編寫一個通用的實現,就像[這個類](https://github.com/luciomartinez/hibernate/blob/master/Registro/src/registro/dao/GenericDaoImpl.java)。如果你願意嘗試內聯的解決方案,可以使用[SerializationUtils]中的'serialize'方法(https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache /commons/lang/SerializationUtils.html)類可以工作,但不能確定。 – Lucio
如果這對你有用,我會在稍後回答一個答案時寫下一些清潔劑:-) – Lucio