Reputation: 5274
Is there a method to reassign the @Id
in child entity after it was assigned to some field in the parent entity
For example:
@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;
}
I have tried to use @AttributeOverride
, but all it could provide is to rename the id column name.
Upvotes: 4
Views: 6478
Reputation: 28746
It sounds like a design problem.
The proper way to achieve this is probably to define another class : @MappedSuperclass GenericEntity
with all attributes of Parent
except the 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
...
}
An alternative experimental solution can be to hide the parentId
field in the Child
class.
Disclaimer : I don't recommend this approach, and I'm not sure it will work !
@Entity
@Access(AccessType.FIELD)
public class Child extends GenericEntity implements Serializable {
@Id
private Long childId;
private Integer parentId;
...
}
Upvotes: 4