Hibernate - One to one relation single table inheritance - java

I have 3 entities BaseFoo, FooAbc, FooAbcDetail. FooAbc extends base entity BaseFoo. I'm trying to do one to one relation between FooAbc and FooAbcDetail.
#Data
#EqualsAndHashCode(callSuper = true)
#Entity
#Table(name = "foo")
#Audited
#AuditOverride(forClass = Auditable.class)
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type_id", discriminatorType = DiscriminatorType.INTEGER)
public abstract class BaseFoo extends Auditable implements Serializable {
#Id
#Column(name = "id")
private Long id;
//other fields
}
#Data
#EqualsAndHashCode(callSuper = true)
#Entity
#Audited
#AuditOverride(forClass = BaseFoo.class)
#DiscriminatorValue("2")
public class FooAbc extends BaseFoo implements Serializable {
#EqualsAndHashCode.Exclude
#ToString.Exclude
#NotAudited
#OneToOne(mappedBy = "fooAbc",
fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
orphanRemoval = true,
optional = false)
private FooAbcDetail fooAbcDetail;
//other fields
}
#Data
#Entity
#Table(name = "foo_abc_detail")
public class FooAbcDetail implements Serializable {
#Id
#Column(name = "foo_id"/* foo_abc_id (I tried both) */)
private Long id;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#MapsId //also tried #MapsId("id")
#OneToOne(fetch = FetchType.LAZY)
private FooAbc fooAbc; //also tried BaseFoo
//other fields
}
While project starting up Hibernate throws:
org.hibernate.MappingException: Unable to find column with logical
name: id in org.hibernate.mapping.Table(public.foo_abc_detail) and its
related supertables and secondary tables
What is the problem here?
Environment
Hibernate 5.3.10.Final
Spring Boot 2.1.7.RELEASE

This error is telling you that there is no column on the foo_abc_detail table called foo_id.The column on foo_abc_detail is just called id.
#Data
#EqualsAndHashCode(callSuper = true)
#Entity
#Table(name = "foo")
#Audited
#AuditOverride(forClass = Auditable.class)
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type_id", discriminatorType = DiscriminatorType.INTEGER)
public abstract class BaseFoo extends Auditable implements Serializable {
#Id
#Column(name = "id")
private Long id;
//other fields
}
#Data
#EqualsAndHashCode(callSuper = true)
#Entity
#Audited
#AuditOverride(forClass = BaseFoo.class)
#DiscriminatorValue("2")
public class FooAbc extends BaseFoo implements Serializable {
#EqualsAndHashCode.Exclude
#ToString.Exclude
#NotAudited
#OneToOne(mappedBy = "fooAbc",
fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
orphanRemoval = true,
optional = false)
private FooAbcDetail fooAbcDetail;
//other fields
}
#Data
#Entity
#Table(name = "foo_abc_detail")
public class FooAbcDetail implements Serializable {
#Id
#Column(name = "id")
private Long id;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#MapsId //also tried #MapsId("id")
#OneToOne(fetch = FetchType.LAZY)
private FooAbc fooAbc; //also tried BaseFoo
//other fields
}

Okey I solved. I don't know if this is the best way to do it but it works! I replaced the #MapsId annotation via #JoinColumn. Final result of the FooAbcDetail class like as below.
#Data
#Entity
#Table(name = "foo_abc_detail")
public class FooAbcDetail implements Serializable {
#Id
#Column(name = "id")
private Long id;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
private FooAbc fooAbc;
}

Related

How to get parent entity with all child entities and child entities of children in Spring/JPA/Hibernate with Lombok

I have these entities where Shop entity is parent:
#Data
#NoArgsConstructor
#Entity
#DynamicUpdate
#Table(name = "Shop", schema = "public")
public class ShopDao {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
private String name;
private String processedStatus;
#OneToMany(mappedBy = "shopDao", cascade = CascadeType.ALL, orphanRemoval = true)
private List<BookDao> bookDaoList;
}
#Data
#NoArgsConstructor
#Entity
#ToString(exclude = {"shopDao"})
#Table(name = "Book", schema = "public")
public class BookDao {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
private String name;
private String author;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "other_id", referencedColumnName = "id")
private OtherDao otherDao;
#ManyToOne
#JoinColumn(name = "shop_id", nullable = false)
private ShopDao shopDao;
}
#Data
#NoArgsConstructor
#Entity
#ToString(exclude = {"bookDao"})
#Table(name = "Other", schema = "public")
public class OtherDao {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
private String metadata;
#OneToOne(mappedBy = "otherDao", fetch = FetchType.EAGER)
private BookDao bookDao;
}
And these are repos:
#Repository
public interface ShopRepo extends JpaRepository<ShopDao, Long> {
#EntityGraph(attributePaths = {"bookDaoList"})
List<ShopDao> findAllByProcessedStatus(String processedStatus);
}
#Repository
public interface BookRepo extends JpaRepository<BookDao, Long> {
}
#Repository
public interface OtherRepo extends JpaRepository<OtherDao, Long> {
}
When i'm using findAllByProcessedStatus() function, i get BookList inside Shop object correctly, but each Book can't reach their Other objects and i get LazyInitializationException:
screenshot
How do i fix that problem?
Actually, with spring data's #EntityGraph all you need is :
#Repository
public interface ShopRepo extends JpaRepository<ShopDao, Long> {
#EntityGraph(attributePaths = {"bookDaoList.otherDao"})
List<ShopDao> findAllByProcessedStatus(String processedStatus);
}
This is the most convenient way.
For more complex relations, you could define a #NamedEntityGraph, and provide subgraphs, like so.
What I find intriguing, is that the BookDao is the owner of this relation, so I would expect it to be eagerly loaded, since you haven't specified a the Lazy fetch mode explicitly ...

Problems with identifiing entity in another entity using Hibernate

Here is the code:
#Entity
#Table(name = "students")
public class BotUser {
...
#Id
#Column(name = "id", updatable = false)
private int id;
#OneToOne
private Equipment equipment;
...
}
#Entity
#Table(name = "students")
public class Equipment {
...
#Id
#Column(name = "id")
private int id;
...
}
When Hibernate is fetching equipment data from PostrgeSQL table, he requests "equipment_id" field, not "id". How to solve this problem?
I must use #JoinColumn annotation. And to be sure I added CascadeType.ALL
#Entity
#Table(name = "students")
public class BotUser {
...
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private Equipment equipment;
...
}
The same problem: AnnotationException Referenced property not a (One|Many)ToOne

Hibernate #embededId containing a foreign key of an entity with inheritance

Used this as my base point: https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/
I have an entity named Attendance that has an and emebedid AttendacneId that has two columns lectureId (string) and studenId(UUID). The attendance entity also has other properties as well containing a ManyToOne relationship with student and lecture enity using the #MapsId on them. The student extends user entity where the id resides. now when I try to save anything I get this error.
java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:860)
at org.hibernate.cfg.annotations.TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit(TableBinder.java:724)
at org.hibernate.cfg.PkDrivenByDefaultMapsIdSecondPass.doSecondPass(PkDrivenByDefaultMapsIdSecondPass.java:37)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1684)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1641)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:286)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:473)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:84)
at utility.Utils.<clinit>(Utils.java:60)
at utility.Testing.main(Testing.java:21)
My AttendanceId class
#Embeddable
public class AttendanceId implements Serializable {
#Column(name = "lecture_fid")
#Getter
#Setter
private String lectureId;
#Column(name = "student_fid", columnDefinition = "uuid")
#Getter
#Setter
private UUID studentId;
public AttendanceId() {}
}
My Attendance class
#Entity
#Table(name = "attendance")
public class Attendance implements Serializable {
#EmbeddedId
#Getter
#Setter(AccessLevel.PRIVATE)
private AttendanceId id;
// other fields
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("lectureId")
private Lecture lecture;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("studentId")
private Student student;
}
My Student Class
#Entity
#PrimaryKeyJoinColumn(name = "id")
public class Student extends User implements Serializable,
Comparable<Student> {
// other fields
#OneToMany(mappedBy = "student", fetch = FetchType.LAZY)
#Getter
private List<Attendance> attendances = new ArrayList<>();
}
My User class
#Entity
#Table(name = "users", uniqueConstraints = {
#UniqueConstraint(columnNames = {"email", "username"})})
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class User implements Serializable {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
#Column(columnDefinition = "UUID")
#Getter(AccessLevel.PUBLIC)
#Setter(AccessLevel.PUBLIC)
private UUID id;
// other fields.
}
My Lecture Class
#NamedNativeQueries(
#NamedNativeQuery(name = "getLectureId", query = "select
get_lecture_id()")
)
#Entity
#Table(name = "lecture")
public class Lecture implements Serializable {
#Id
#Column(name = "id")
#GenericGenerator(name = "lectureIdGenerator",
strategy = "entities.LectureIdGenerator")
#GeneratedValue(generator = "lectureIdGenerator")
#Getter
#Setter
private String id;
#OneToMany(mappedBy = "lecture", fetch = FetchType.LAZY)
#Getter
private List<Attendance> attendances = new ArrayList<>();
// other fields
}
I think the inheritance is causing an issue. There are other classes/entities as well that extends the user entity. If anyone could help me find the problem that will be great. Thank you.
This issue is caused by the HHH-7135 Hibernate issue.

MappedBy reference an unknown target entity

I design a system of tables in the database for the film service. So far I have designed them in this way.
#Entity
#Table(name = "movies")
#Data
public class MovieEntity {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
private Set<MovieDescription> description;
}
#Entity
#Table(name = "movies_info")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type")
public abstract class MovieInfo {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#ManyToOne
public MovieEntity movie;
}
#Entity
#DiscriminatorValue(value = EditType.Values.DESCRIPTION)
public class MovieDescription extends MovieInfo {
private String description;
private String language;
}
When compiling, it sends me a mistake
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.core.jpa.entity.MovieDescription.movie in com.core.jpa.entity.MovieEntity.description
Something related to MovieEnity mapping, but I don't know what it is all about.
use targetEntity attribute to target the super class field that you want to map with.
#Entity
#Table(name = "movies")
#Data
public class MovieEntity {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "movie", cascade = CascadeType.ALL, targetEntity= MovieInfo.class)
private Set<MovieDescription> description;
}
More detail: one to many mapping to a property of superclass

JPA, inheritance JOINED, multiple ID's

I have a little JPA question.
Assume you have such tables: (structure is fixed)
PERSON
--
ID,
DEPARTMENT_ID
...
SPECIALWORKER
------
ID, PERSON_ID, SPECIALDEPARTMENT_ID
...
DEPARTMENT
-------
ID,
...
SPECIALDEPARTMENT
-------
ID,
...
In Java I would build it with a simple hierarchy: SpecialWorker extends Person and SpecialDepartment extends Department. We will have "simple" Persons as well as "simple" Departments.
In JPA I try to build that scenario with a JOINED_Table inheritance, but I can't get it working. Any ideas?
edit
the coding, i hope i missed nothing.
I got a integrity exception when i try to insert a specialworker.
When i insert a specialworker jpa has to set the fk to departement (baseclass person) as well as the fk to the special departement (from the concrete current class)
#Entity
#Table(name = "DEPARTEMENT")
#Access(AccessType.FIELD)
#Inheritance(strategy = InheritanceType.JOINED)
public class Departement
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Integer id;
...
}
#Entity
#Table(name = "SPECIALDEPARTEMENT")
#Access(AccessType.FIELD)
#PrimaryKeyJoinColumn(name = "ID_DEPARTEMENT", referencedColumnName = "ID")
public class SpecialDepartement
extends Departement
implements Serializable
{
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", updatable = false, insertable = false)
private Integer id01;
#OneToMany(mappedBy = "specialDepartement", cascade = CascadeType.ALL, orphanRemoval = true)
private List<SpecialWorker> workers;
...
}
#Entity
#Table(name = "PERSON")
#Access(AccessType.FIELD)
#Inheritance(strategy = InheritanceType.JOINED)
public class Person
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
#Max(19)
private Long id;
#ManyToOne
#JoinColumn(name = "ID_DEPARTEMENT", referencedColumnName = "ID", nullable = false)
private Departement departement;
...
}
#Entity
#Table(name = "SWORKER")
#Access(AccessType.FIELD)
#PrimaryKeyJoinColumn(name = "ID_PERSON", referencedColumnName = "ID")
public class SpecialWorker
extends Person
{
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", updatable = false, insertable = false)
private Integer id01;
#ManyToOne
#JoinColumn(name = "ID_SPECIALDEPARTEMENT", referencedColumnName = "ID", nullable = false)
private SpecialDepartement specialdepartement;

Categories