0

我正在使用 Hibernate 4.2 和 PostgreSQL。

我在 postgres 中有这张表:

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

我的实体是:

@Entity @Table(name="customer") public class Customer { @Id @GeneratedValue() @Column(name="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)

谢谢 :)

4

1 回答 1

1

Postgres 通常与 Serial (Integer) 或 BigSerial(Long) 一起使用,并且还会自动生成序列

试试这些方法:

  1. 改变你@GeneratedValue@GeneratedValue(strategy=GenerationType.IDENTITY),看看它是否有效。
  2. 像这样创建一个 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;
于 2013-10-31T12:33:24.690 回答