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

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

Null values not allowed in column - legacy database

问题

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

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

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

@OneToOne()
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "robj02", referencedColumnName = "objnr")
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.

@OneToOne()
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "robj02", referencedColumnName = "objnr")
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

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

@Entity
public class YourEntity
{

   @Column(name = "robj02")
   private Long objektId;

   @OneToOne
   @NotFound(action = NotFoundAction.IGNORE)
   @JoinColumn(name = "robj02", referencedColumnName = "objnr", insertable = false, updatable = false)
   private Objekt robj02;
   
   // 获取器/设置器
}

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

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

You can correct your mapping in the following way:

@Entity
public class YourEntity
{

   @Column(name = "robj02")
   private Long objektId;

   @OneToOne
   @NotFound(action = NotFoundAction.IGNORE)
   @JoinColumn(name = "robj02", referencedColumnName = "objnr", insertable = false, updatable = false)
   private Objekt robj02;
   
   // getters/setters
}

and then just persist it in the following way:

YourEntity entity = new YourEntity();
entity.setObjektId(0L);
// ...
entityManager.persist(entity);

答案2

得分: 0

脏代码但类似这样:

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

Dirty hack but something like

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

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:

确定