OpenJPA:如何使用枚举持久化实体?

时间:2015-01-01 16:35:25

标签: java postgresql jpa enums openjpa

我有一个实体

@Entity
@Table(name = "product")
public class Product {

    @Id
    private Long id;

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

    @Column(name = "condition")
    @Enumerated(value = EnumType.STRING)
    private Condition condition;

    public enum Condition {
        NEW, USED
    }
    // default constructor and getters/setters omitted
}

坚持实体的Java代码

Product product = new Product();
product.setItemName("Gloves");
product.setCondition(Product.Condition.NEW);

entityManager.getTransaction().begin();
entityManager.persist(product);
entityManager.getTransaction().commit();
entityManager.close();

这是我的PostgreSQL数据库。

枚举类型。

CREATE TYPE product_condition AS ENUM ('NEW', 'USED');

和表。

CREATE TABLE product (
id     SERIAL            NOT NULL,
name   VARCHAR(255)      NOT NULL,
condition product_condition NOT NULL,
CONSTRAINT product_pk PRIMARY KEY (id)
);

但由于

,无法将新产品插入数据库
Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: ERROR: column "condition" is of type product_condition but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 55 {prepstmnt 1419086773 INSERT INTO product (id, condition, name) VALUES (?, ?, ?)} [code=0, state=42804]

我该如何解决?

0 个答案:

没有答案