简体   繁体   中英

Upcast a POJO to a JPA Entity Class

Consider an @Entity class A , and another class B that is a POJO and extends A .

Is there any way to force an upcast of B to A (Without Reflection)?

I have a method that receive an object of class A and persist that object. Passing a reference to an object B , will cause JPA to fail because it still consider the object as an instance of class B , and B is not annotated with @Entity .

Look into the @Inheritance annotation which allow inheritance relationships in object models, it can be setup in a number of ways (table per class, single table).

I have created video tutorials detailing these two strategies. The first video covers the single table strategy and the other covers table per class .

Using the single table strategy you would annotate class A as follows:

@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@Table(name="TABLE_NAME")
@DiscriminatorColumn(name="DISCRIMINATOR_COLUMN", discriminatorType=DiscriminatorType.STRING)
@Entity
public class A {}

Then annotate class B:

@Entity
@Table(name = "TABLE_NAME")
@DiscriminatorValue(value="VALUE_TO_DISTINGUISH_B")
public class B{}

One thing to note is that in this case B is made an entity, which I believe will be required in any scenario.

Probably you do not want/can not add the B entity to the persistence.xml file. If so, you could use Jackson like this:

1.Create B 's JSON representation:

ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(instanceB);

2.Create an A -instance from the JSON String, ignoring the unknown properties. Use this setting for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM