Criteria:ClassCastException Integer to Long

时间:2013-10-31 12:20:44

标签: java hibernate postgresql

我正在使用Hibernate 4.2和PostgreSQL。

我在postgres中有这个表:

  id bigserial NOT NULL (chave primária)
  name text

我的实体是:

  

@Entity @Table(name =“customer”)public class Customer {       @ID       @GeneratedValue()       @Column(名称= “ID”)       private Long id;

@Column(name="name")
private String name;

    //getters and setters }

在我的班级(CustomerDAO)中,我有一个按标准搜索的方法。

public List<Customer> getByName(String name){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Criteria selection = selection.createCriteria(Customer.class);

        selection.add(Restrictions.eq("name", name));

        return selection.list(); //error here!
}

当我编写实体时,我将id设置为Integer,但是,我从int更改为Long,并开始出现此错误:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
    at org.hibernate.type.descriptor.java.LongTypeDescriptor.unwrap(LongTypeDescriptor.java:36)
    at org.hibernate.type.descriptor.sql.BigIntTypeDescriptor$1.doBind(BigIntTypeDescriptor.java:57)
    at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:93)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:280)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:275)
    at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1969)
    at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1940)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1875)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
    at org.hibernate.loader.Loader.doQuery(Loader.java:900)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
    at org.hibernate.loader.Loader.doList(Loader.java:2526)
    at org.hibernate.loader.Loader.doList(Loader.java:2512)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
    at org.hibernate.loader.Loader.list(Loader.java:2337)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:124)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1662)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
    at com.teste.hibernate.dao.CustomerDAO.getByName(CustomerDAO.java:77)
    at Teste.main(Teste.java:44)

谢谢:)

1 个答案:

答案 0 :(得分:1)

Postgres通常使用Serial(Integer)或BigSerial(Long)并自动生成序列

尝试以下方法:

  1. 将您的@GeneratedValue更改为@GeneratedValue(strategy=GenerationType.IDENTITY)并查看 如果它有效。
  2. 像这样创建一个SequenceGenerator
  3. 对于第二个选项

    SequenceGenerator

    @SequenceGenerator(name = "tbl_costumer_id_gen", sequenceName = "tbl_costumer_id_gen",allocationSize=1) 
    @Id 
    @GeneratedValue(GenerationType.SEQUENCE, generator="tbl_costumer_id_gen") 
    @Column(name="id") 
    private Long id;