Problem
- I have a parent entity with a one-to-many relationship with child entities.
- Mapstruct is being used to map entities to DTOs, so just fetching all (even lazily) will result in every instance being instantiated/fetched from persistence (which we do not want, I only care about IDs outside of the Spring JPA/Hibernate classes)
- Both parent and child's tables have no reference of the other, the relationship is handled by a join table
I only care about the IDs for the associations. I do not want the DTO to have the respective associated class as an attribute. I want Parent to have Set<String> childIds and Child to have String parentId in the DTOs. Because of this, I do not want to load the entire object in the persistence layer just to map away everything else.
Attempts
- Having the entity classes reference the other entity class. Entity → DTO is ok, but DTO → Entity Hibernate/Spring JPA complains that the entity is detached (because it just came from an ID). One solution I thought of is calling
EntityManager.getReferencebut that throws an error if it's a new entity, so how can I save new ones? I'd have to do anexistsByIdbut now we're making even more database calls, this is getting expensive - A bunch of combinations of
JoinColumn,JoinColumns,JoinTable, etc.
Java classes
Entities
@Entity
@(LombokGettersAndSetters)
public class ParentEntity {
@Id
private Long id;
@(???)
private Set<Long> childIds; || private Set<ChildEntity> children;
}
@Entity
@(LombokGettersAndSetters)
public class ChildEntity {
@Id
private Long id;
@(???)
private Long parentId; || private ParentEntity parent;
}
Mappers
(Mapstruct mappers)
DTOs
public class ParentDTO {
private Long id;
private Set<Long> childIds;
}
public class ChildDTO {
private Long id;
private Long parentId;
}
Tables
Parent Child Parent_join_Child
------- ----- -----------------
id id parent_id
child_id
Thanks in advance!
Edit @ +1m: I should note, I removed some annotations in my examples such as the below
@Column(name = "parent_id", columnDefinition = CustomColumnDefinition.UNSIGNED_INT)
@GeneratedValue(strategy = GenerationType.IDENTITY)