不允许在列中使用空值 – 传统数据库

huangapple go评论85阅读模式
英文:

Null values not allowed in column - legacy database

问题

我有一个无法更改的传统DB2数据库。它无法保存空值,因此所有空的外键都被设置为零(0)。

在读取时,这没有问题,我只是将未找到的操作设置为忽略,它会将子对象返回给我null。

但是我有另一个问题。当我想保存一个空对象时,它应该将我的表中的外键设置为0,但它不知道如何做,会抛出“不允许空值”的异常。

  1. @OneToOne()
  2. @NotFound(action = NotFoundAction.IGNORE)
  3. @JoinColumn(name = "robj02", referencedColumnName = "objnr")
  4. private Objekt robj02;

有没有办法定义默认值或类似的东西?有没有人有想帮助我的想法?

英文:

I've got a legacy DB2 database which I can't change. It can't save null-values so all foreign keys which are empty are set to zero (0).

While reading this is no problem, I just set the not found action to ignore and it returns me null instead of the child-object.

But I have a problem the other way around. When I want to save a null-object it should set the foreign key in my table to 0, but it doesn't know how to do that and throws me an "null value not allowed"-exception.

  1. @OneToOne()
  2. @NotFound(action = NotFoundAction.IGNORE)
  3. @JoinColumn(name = "robj02", referencedColumnName = "objnr")
  4. private Objekt robj02;

Is there a way to define a default value or something similar? Does anyone have an idea to help me?

答案1

得分: 1

你可以通过以下方式纠正你的映射:

  1. @Entity
  2. public class YourEntity
  3. {
  4. @Column(name = "robj02")
  5. private Long objektId;
  6. @OneToOne
  7. @NotFound(action = NotFoundAction.IGNORE)
  8. @JoinColumn(name = "robj02", referencedColumnName = "objnr", insertable = false, updatable = false)
  9. private Objekt robj02;
  10. // 获取器/设置器
  11. }

然后可以按以下方式进行持久化操作:

  1. YourEntity entity = new YourEntity();
  2. entity.setObjektId(0L);
  3. // ...
  4. entityManager.persist(entity);
英文:

You can correct your mapping in the following way:

  1. @Entity
  2. public class YourEntity
  3. {
  4. @Column(name = "robj02")
  5. private Long objektId;
  6. @OneToOne
  7. @NotFound(action = NotFoundAction.IGNORE)
  8. @JoinColumn(name = "robj02", referencedColumnName = "objnr", insertable = false, updatable = false)
  9. private Objekt robj02;
  10. // getters/setters
  11. }

and then just persist it in the following way:

  1. YourEntity entity = new YourEntity();
  2. entity.setObjektId(0L);
  3. // ...
  4. entityManager.persist(entity);

答案2

得分: 0

脏代码但类似这样:

  1. void setRobj02(Objeckt robj02) {
  2. this.robj02 = (robj02 != null)
  3. ? robj02
  4. : Objekt.ZERO // 你应该先创建它
  5. }
英文:

Dirty hack but something like

  1. void setRobj02(Objeckt robj02) {
  2. this.robj02 = (robj02 != null)
  3. ? robj02
  4. : Objekt.ZERO // you should create it first
  5. }

huangapple
  • 本文由 发表于 2020年10月23日 17:10:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64497169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定