gpt4 book ai didi

java - hibernate/JPA : Is it possible to Override @Id field?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:17 25 4
gpt4 key购买 nike

@Id 分配给父实体中的某个字段后,是否有方法重新分配子实体中的 @Id

例如:

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class Parent implements Serializable {

@Id
protected Integer parentId;

public Integer getId() {
return parentId;
}

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


@Entity
@Access(AccessType.FIELD)
public class Child extends Parent implements Serializable {

/*
What should be added to this entity to re assign the @Id to a new field and
make the parentId field just an ordianry field in the Child, not the entity Id
*/
@Id
private Long childId;

}

我试过使用@AttributeOverride , 但它所能提供的只是重命名 id 列名称。

最佳答案

这听起来像是一个设计问题。

实现这一目标的正确方法可能是定义另一个类:@MappedSuperclass GenericEntity 具有 Parent 除了 parentId 的所有属性:

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class GenericEntity implements Serializable {
... all your common attributes without parentId
}

@MappedSuperclass
public abstract class Parent extends GenericEntity implements Serializable {

@Id
protected Integer parentId;

public Integer getId() {
return parentId;
}

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

//nothing more in this class
}

@Entity
public class Child extends GenericEntity implements Serializable {

@Id
private Long childId;

private Integer parentId; //if you need it

...
}

另一种实验性解决方案是隐藏 Child 类中的 parentId 字段。

免责声明:我不推荐这种方法,我不确定它是否有效!

@Entity
@Access(AccessType.FIELD)
public class Child extends GenericEntity implements Serializable {

@Id
private Long childId;

private Integer parentId;

...
}

关于java - hibernate/JPA : Is it possible to Override @Id field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com