Currently I have the following 2 entities with a one to many relationship -
#Data
#Entity
#Table(name = "invoice_line")
#IdClass(InvoiceLinePK.class)
public class InvoiceLineEntity {
#Id
#Column(name = "line_id")
private String lineId;
#Id
#Column(name = "client_id")
private Integer clientId;
#Id
#Column(name = "invoice_id")
private String invoiceId;
#Column(name = "item_id")
private String itemId;
#Column(name = "amount")
private BigDecimal amount;
#ManyToOne
private InvoiceEntity invoice;
}
#Entity
#Table(name = "invoice")
#IdClass(InvoicePK.class)
#Data
public class InvoiceEntity {
#Id
#Column(name = "client_id")
private Integer clientId;
#Id
#Column(name = "invoice_id")
private String invoiceId;
#Column(name = "description")
private String description;
#Column(name = "txn_total_amount")
private BigDecimal txnTotalAmount;
#Column(name = "created_time", updatable = false)
#CreationTimestamp
private Date createdTime;
#Column(name = "updated_time")
#UpdateTimestamp
private Date updatedTime;
#OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "invoice")
private List<InvoiceLineEntity> invoiceLines;
}
In a case wherein let's say, one of my existing invoice has 3 lines and I receive a request that this particular invoice has been updated and it now has only 1 line instead of the previous 3 (so the other 2 have to be deleted), I would like to create a new Invoice object with this 1 InvoiceLineEntity and then do a invoiceRepository.save(invoice)
I am expecting that the other 2 InvoiceLine records would be automatically deleted because the orphanRemoval flag is enabled.
Can someone tell me how I can achieve this relationship by tweaking the entity relationship structure of the above 2 entities?
Your child entity must be the owner of the relationship, so that the orphans are allowed to be deleted
If you change and add mappedBy to that relation
#OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "bill")
private List<BillLine> billLines;
Then the BillLine must also hold a reference
public class BillLine {
#Id
#Column(name = "line_id")
private String lineId;
#Id
#Column(name = "company_id")
private Integer companyId;
#Id
#Column(name = "bill_id")
private String billId;
#Column(name = "item_id")
private String itemId;
#Column(name = "amount")
private BigDecimal amount;
#ManyToOne
private Bill bill;
}
Now it will remove the orphans
Also since you have multiple #Id on each entity. Do you know that you have to either declare a composite class or an embeddable class? Without one of those the multiple Ids are not valid.
Edit:
1) My bad mappedBy should be placed inside #OneToMany and not #JoinColumn. I have corrected it in my answer
2) Remove #JoinColumn. It is wrong in your configuration. By default #OneToMany inserts a column in the side of the #ManyToOne which holds the references to the primary table. You can override those default configurations and create a separate table for mappings but then you need the #JoinTable and I don't see any reason for that here.
This here
#JoinColumns(value = { #JoinColumn(name = "company_id", referencedColumnName = "company_id"),
#JoinColumn(name = "bill_id", referencedColumnName = "bill_id") })
definitely does not belong on #OneToMany
The following can be applied to #OneToMany but as said before I don't see any reason to do that and complicate a simple mapping which does not require a separate table.
#JoinTable(joinColumns = #JoinColumn(name = "company_id", referencedColumnName = "company_id"),
inverseJoinColumns = #JoinColumn(name = "bill_id", referencedColumnName = "bill_id") )
Check here for more information Jpa primary key
Related
I have two entities, each one pointing to one single table in an postgres. The entities belong to an Spring/graddle/JPA/Hibernate web application.
#Entity
#Table(name = "STAFF")
#AttributeOverride(name = "id", column = #Column(name = "ID"))
public class StaffEntity extends AbstractEntity {
#Column(name = "NAME")
private String name;
#Column(name = "SHORT_NAME")
private String shortName;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "STAFF_GROUP_ID", referencedColumnName = "ID")
private StaffGroupEntity staffGroup;
/* More attributes, getters and setters */
#Entity
#Table(name = "STAFF_GROUP")
#AttributeOverride(name = "id", column = #Column(name = "ID"))
public class StaffGroupEntity extends AbstractEntity {
#Column(name = "NAME")
private String name;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "LEAD_ID", referencedColumnName = "ID")
private StaffEntity lead;
/* More attributes, getters and setters */
When i update with swagger the group with a lead that is already in the group i get a stackOverFlowError
java.lang.StackOverflowError: null
mapping with mapstruct
I have a problem using JPA.
I want to the fatherId and father coexistence,When I query with join table.
#Entity
public class Son {
#Id
#Column(name = "id")
private String id;
#Column(name = "father_id")
private String fatherId;
#OneToOne
#JoinColumn(name = "father_id")
private Father father;
}
You have to set one to read-only.
For example:
#Column(name = "father_id", insertable = false, updatable = false)
private String fatherId;
#OneToOne
#JoinColumn(name = "father_id")
private Father father;
Otherwise Hibernate has two ways to write the foreign key.
There is a unidirectional ManyToMany mapping between Role and Privilege with Role as the owning entity like so
Role
#Entity
public class Role extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "role_id")
private Integer roleId;
#Size(max = 45)
#Column(name = "role")
private String role;
#JoinTable(name = "role_privilege", joinColumns = {
#JoinColumn(name = "role_role_id", referencedColumnName = "role_id")}, inverseJoinColumns = {
#JoinColumn(name = "privilege_privilege_id", referencedColumnName = "privilege_id")})
#ManyToMany(
cascade = {
CascadeType.DETACH,
CascadeType.MERGE,
CascadeType.REFRESH,
CascadeType.PERSIST }, fetch = FetchType.EAGER, targetEntity = Privilege.class)
private Collection<Privilege> privilegeCollection;
#Transient
private Collection<Privilege> parentPrivilegeCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "roleId")
#JsonIgnore
private Collection<User> userCollection;
public Role() {
}
//getters,setter,hashcode,equals removed for brevity
}
Privilege
#Entity
public class Privilege extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "privilege_id")
private Integer privilegeId;
#Size(max = 45)
#Column(name = "name")
private String name;
#Size(max = 150)
#Column(name = "description")
private String description;
#Size(max = 45)
#Column(name = "friendly_name")
private String friendlyName;
#JoinTable(name = "privilege_hierachy", joinColumns = {
#JoinColumn(name = "parent_privilege", referencedColumnName = "privilege_id")}, inverseJoinColumns = {
#JoinColumn(name = "child_privilege", referencedColumnName = "privilege_id")})
#ManyToMany
private Collection<Privilege> privilegeCollection;
public Privilege() {
}
}
The Problem
Whenever i set updated list of privileges in a role and update, the join table is successfully updated without removing either target or owning entity, and that is desired result. The problem is on update it also affect another self join table in Privilege called privilege_hierachy which is not what is expect.
Is it possible for hibernate to only update the Role-Privilege mant-to-many relationship and let other relation unchanged.
Spring Data Jpa is used for data persistence
It sounds like you are updating the privileges by (removing old privileges and) adding new ones. If you do that, clearly, the second join table (the self-referencing table) could be updated with new rows, based on what you are passing.
I see that for the self-referencing table, Privilege, you are not setting cascade type. It defaults to no operation, and that sounds like what you want. But my guess is based on what you said "Whenever i set updated list of privileges in a role", and that tells me you are creating new privileges for a role, instead of using existing privileges and associate them with the role.
I'm italian and i apologize for my english.
I have two POJO classes that rappresents a parent and a child table in my Db.
Parent. Persona.java
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "nome", length = 30, nullable = false)
private String nome;
#Column(name = "cognome", length = 30, nullable = false)
private String cognome;
#Column(name = "eta")
private int eta;
#OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy = "persona", orphanRemoval = false)
#Column(nullable = true)
private List<Telefono> numeriDiTelefono;
// Others getters and setters
Child. Telefono.java
#Id
#Column(name = "numero_telefono")
private String numeroDiTelefono;
#Column(name = "tipo")
private String tipo;
#ManyToOne(cascade = {CascadeType.REMOVE, CascadeType.PERSIST })
#JoinColumn(name = "persona_id", nullable = true)
private Persona persona;
// Others getters and setters
I have used annotations for mapping those classes in database.
When i try to delete a Persona from the database, hibernate delete the associated Telefono with that Persona, I don't want it.
I would that the child references to has a null value in the field persona_id in the Telefono table, how to obtaining that results? What annotations shoulds I used?
Thanks for everyone.
JPA is not magic.
As #Andy Dufresne suggested, remove the CascadeType.REMOVE annotation. Then you have to set Persona to null in the Telefono, and clear the Telefono collection of the Persona before removing the Persona from the persistence context. So you have to remove all associations.
You can even combine this with the #PreRemove annotation.
I use hibernate and spring-data. There are two tables with many-to-many relationship.
#Entity
#Table(name = "FirstEntity")
public class FirstEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "first_entity_id")
private Long id;
#Column(name = "first_entiry_name")
private String name;
/* getters and setters are below*/
}
#Entity
#Table(name = "SecondEntity")
public class SecondEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "second_entity_id")
private Long id;
#Column(name = "second_entiry_name")
private String name;
#Column(name = "second_entiry_desc")
private String description;
/* getters and setters are below*/
}
And entity for cross-reference table.
#Entity
#Table(name = "FirstSecondEntity")
public class FirstSecondEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "first_second_entity_id")
private Long id;
#Column(name = "first_entity_id")
private Long firstEntityId;
#Column(name = "second_entity_id")
private Long secondEntityId;
/* getters and setters are below*/
}
I need SELECT like this
SELECT FirstEntity.name, SecondEntity.name, SecondEntity.description FROM SecondEntity INNER JOIN FirstSecondEntity ON SecondEntity.id = FirstSecondEntity.secondEntityId INNER JOIN User ON FirstEntity.id = FirstSecondEntity.firstEntityId
i.e. I need all records from cross-reference table where instead of ids there is actual info from entities.
Inserting this query into #Query annotation in my CrudRepository-extended class doesn't work because of
ERROR [main][org.hibernate.hql.internal.ast.ErrorCounter] Path expected for join!
So I need your help.
Your join table is all screwed up. In this case, you actually don't even need the join table as a hibernate mapping:
In Second Entity add the following list:
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "FirstSecondEntity",
joinColumns = {
#JoinColumn(name = "first_entity_id",
nullable = false,
updatable = false) },
inverseJoinColumns = {
#JoinColumn(name = "second_entity_id",
nullable = false,
updatable = false) },
)
private List<FirstEntity> firstEntities;
In FirstEntity add the following list:
#ManyToMany(fetch = FetchType.LAZY,
mappedBy = "firstEntities")
private List<SecondEntity> secondEntities;