【问题标题】:OpenJPA Entity not updated when value is zero值为零时未更新 OpenJPA 实体
【发布时间】:2017-12-06 08:22:27
【问题描述】:

我遇到了一个实体的问题,该实体的字段映射到 DB 中的 INT 类型。问题是,当我将字段更新为一个值时,例如 1337,它会正确地保存在数据库中,但当我将其设置为零时,情况并非如此。

更具体一点:

  • 我的数据库中有一行“记录”字段为 INT 类型且值为 NULL
  • 我将该行检索为托管实体“anEntity”
  • 当我执行“anEntity.setRecord(1337)”时,DB 中的记录值会发生变化,但当我执行“anEntity.setRecord(0)”时情况并非如此(它在 DB 中保持 NULL)。

有办法解决吗?

一点代码,更新的人:

@Stateless
public class AClass {

    @EJB
    ARepository arepository;

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void produceOutgoingMessage(int idOfOutputToProduce) {
        AnEntity anEntity = arepository.find(idOfOutputToProduce);
        //...
        doSomething(anEntity);
    }

    private void doSomething(AnEntity anEntity) {
        //...
        anEntity.setRecord(0); // record stays NULL in DB
        anEntity.setRecord(1337); // record is correctly set in DB
    }
}

还有实体:

@Entity
@Table(name = "MY_TABLE")
public class AnEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "C_I_IDF")
    private Long id;

    @Column(name = "N_I_RECORD")
    private int record;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getRecord() {
        return record;
    }

    public void setRecord(int record) {
        this.record = record;
    }
}

【问题讨论】:

  • 我添加了一个代码示例,因为我不允许发布原始代码:(
  • 我添加了实体
  • 首先一个“int”不应该在数据库中允许“NULL”,所以模式与类不一致。其次,如果将该字段设置为 0 意味着没有触发更新,那么这是您的 JPA 提供程序中的一个错误......但是您可能会发现修复第一部分(可空性)会处理第二部分。
  • 是的,我在实体定义中将 int 更改为 Integer,它现在可以工作了。谢谢你:)
  • 好。添加为您接受的答案。

标签: jpa entity openjpa


【解决方案1】:

不应将“int”字段配置为允许在数据库中使用NULL。这可能是问题的原因。修复它,它应该可以工作。

如果没有,则在OpenJPA 中报告错误。

【讨论】:

    猜你喜欢
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多