2016-08-15 36 views
0

錯誤: 類型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; 
    } 
} 
+1

正如錯誤中所述,第二個參數不能只是一個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

+0

如果這對你有用,我會在稍後回答一個答案時寫下一些清潔劑:-) – Lucio

回答

0

你應該使用簡單的整型

... 
sample = (Sample)session.get(Sample.class, new Integer(1)); 
... 

代替。

+0

謝謝你使用streetturtle –

+0

它適合你嗎?如果是,請將答案標記爲已接受。 – streetturtle

相關問題