user2281204
user2281204

Reputation: 83

Reusing entities in JPA/Spring Boot

I have an existing entity that cannot be modified as below:

@Entity
public class ChildEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
private String id;
@Column(name="name")
private String name;
//getters, setters, et al.

I have a new query that returns the same data as above with an extra column as below:

@Entity
public class ParentEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Column(name="extra")
private String extra;
@Id
@Column(name="id")
private String id;
@Column(name="name")
private String name;
//getters, setters, et al. from child

As visible above, I want to reduce the above class to something like this:

@Entity
public class ParentEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Column(name="extra")
private String extra;
@Embedded
private ChildEntity entity; //ChildEntity will have annotation @Embeddable
//getters, setters, of extra param

But when I run the native query that assigns data to a list of ParentEntity, it does not recognize ChildEntity.

My queries would be something like this:

ChildEntity: select name,id from table where (/*some condition*/)
ParentEntity: select extra,name,id from table where (/*some condition*/)

How do I do this?

Upvotes: 0

Views: 1377

Answers (1)

Luay Abdulraheem
Luay Abdulraheem

Reputation: 761

If you read 37.1.6 Embeddable Classes in Entities

Embeddable classes are used to represent the state of an entity but don't have a persistent identity of their own, unlike entity classes.

Looking back at your entities, you might either need @MappedSuperclass or @Inheritance depending on your model associations. This thread explains the point clearly.

Upvotes: 1

Related Questions