【问题标题】:JPA 2.1 persist string as enum postgresJPA 2.1 将字符串持久化为枚举 postgres
【发布时间】:2019-01-07 01:06:14
【问题描述】:

我正在使用 JPA 2.1 在我的数据库上执行 CRUD 操作。我使用 JPA 工具 -> 从表选项生成实体 从预先存在的数据库生成实体。这创建了一个名为 Item 的 Java 实体。

DB 表 Item 有一个枚举类型的列 item_status,它是作为 Java 实体中的字符串类型创建的。现在我正在尝试使用以下方法将一列插入表 Item 并收到此错误

错误:列“状态”的类型为 item_status,但表达式的类型为字符变化。提示:您需要重写或转换表达式。

Item_Test_CRUD.java

//这里我尝试测试是否可以插入到数据库中

@Test
void test_insert_into_db() {
    DBConnection conx = new DBConnection(); // here I get the message login successful, so I assume the connection to the DB is okay

    Item it = new Item();

    it.setStatus("Rework");
    it.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
    it.setMetadata("{}");

    conx.insert(it);
}

// 我正在使用 EntityManager 连接数据库 DBConnection.java

public void insert(Object obj) {
    this.em.getTransaction().begin();
    this.em.persist(obj);
    this.em.getTransaction().commit();
}

// JPA 工具生成的实体 项目.java

@Entity
@Table(name="\"Items\"")
@NamedQuery(name="Item.findAll", query="SELECT i FROM Item i")
public class Item implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Convert(converter=UUIDConverter.class)
    private String id;

    .
    .

    @Column(name="status")
    private String status;
    .
    .
}

知道我在这里犯了什么错误吗?

【问题讨论】:

  • 这应该对你有帮助:stackoverflow.com/a/43125099/270371
  • 这有帮助。谢谢。
  • stringtype=unspecified 附加到连接字符串,并能够将 java 实体的列类型保持为 String 并进行插入。
  • 写一个可能有帮助的答案

标签: java jpa jpa-2.0 jpa-2.1


【解决方案1】:

通过将 stringtype=unspecified 添加到连接字符串解决了该问题。我不必将 java 实体列的类型更改为枚举。只是将其保留为 String 类型。 欲了解更多信息:stackoverflow.com/a/43125099/270371 https://jdbc.postgresql.org/documentation/94/connect.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多