I’m working on a Spring Boot application where I need to handle a polymorphic association between a ‘Session’ entity and two types of users: ‘User’ and ‘VirtualUser’. Both User and VirtualUser inherit from an abstract class UserRepresentation. I am using Hibernate for ORM, Jackson for JSON serialization, and Lombok for boilerplate code reduction.
Here are my entity classes:
UserRepresentation (abstract class):
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
@Audited
public abstract class UserRepresentation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
}
User Entity:
@Entity
@Audited
@Table(name = "user")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonTypeName("user")
public class User extends UserRepresentation {
private String username;
private String email;
// Other fields and methods
}
VirtualUser Entity:
@Entity
@Audited
@Table(name = "virtual_user")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonTypeName("virtualUser")
public class VirtualUser extends UserRepresentation {
private String virtualId;
private String details;
// Other fields and methods
}
Session Entity:
@Entity
@Audited
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Session {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "driver_id")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class")
@JsonSubTypes({
@JsonSubTypes.Type(value = User.class, name = "user"),
@JsonSubTypes.Type(value = VirtualUser.class, name = "virtualUser")
})
private UserRepresentation driver;
// Other fields and methods
}
Error:
When trying to run the application, I encounter the following error:
Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Association 'com.tgrwrt.customer.motorsport.operationmanagement.models.operations.Session.driver' targets an unknown entity named 'com.tgrwrt.customer.motorsport.operationmanagement.models.identity.UserRepresentation'
-
How can I properly configure Hibernate to recognize the polymorphic relationship between Session and the UserRepresentation subclasses?
-
How can I ensure that Jackson correctly serializes and deserializes the driver property in Session?
-
Are there any additional configurations or annotations required to handle this scenario in Spring Boot with Hibernate and Jackson?
-
How can I verify the correct serialization and deserialization of polymorphic types using Jackson?
Anish Maharjan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.