Many to Many child removel JPA - many-to-many

Hi i have many to many relationship and entities are here:
#Entity
public class Company implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idcompany;
//bi-directional many-to-many association to Client
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name="company_client",
joinColumns=#JoinColumn(name="company_idcompany",
referencedColumnName="idcompany"),
inverseJoinColumns=#JoinColumn(name="client_idclient",
referencedColumnName="idclient"))
Set<Client> clients = new HashSet<Client>();
and second entity
#Entity
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int idclient;
#ManyToMany(mappedBy="clients",cascade = CascadeType.PERSIST , fetch =
FetchType.LAZY )
Set<Company> companies = new HashSet<Company>();
and here is details of date in all 3 tables
---------------------------------------------
company table client table company_client table
id name id name fk_compny fk_client
1 Oracle 1 Abc 1 1
2 XYZ 1 2
when i want to remove row from client table e.g "XYZ" id=2
Client cl = em.find(Client.class,2);
em.remove(cl);
it throws exception "Cannot delete or update a parent row: a foreign key constraint fails " .
How to remove this row

Related

Indexing for key which belongs to Primary key of other table

I have a two table as table as
#Entity
#Table(name = "product", uniqueConstraints=#UniqueConstraint(columnNames={"product_idn"}))
public class Product implements Serializable {
private static final long serialVersionUID = 21409635044L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String product_idn;
}
another table as
#Entity
#Table(name = "storage")
public class Storage implements Serializable {
private static final long serialVersionUID = -67165579239L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id", nullable = false)
#JsonBackReference
private Product product;
}
Now I am fetching record from storage table. Should create a index (Non-Unique)on product_id of storage table? I have to fetch storages count per on product/ featching storages based on product.
Just add #Index annoation like below and it should work fine.
#Entity
#Table(name = "storage", indexes = #Index(columnList = "product_id",name = "storage_productId_index"))
public class Storage implements Serializable

How can I use post method data in back end to save many to many relationship data with #JsonIgnore annotation.My joining table is not updating

How can I use the data send through post method, and save those data in a many to many relationship? I used #JsonIgnore annotation to stop the recursion.
I have implemented two entities.One is Employee and the other is Skills.In the Employee entity I used #JsonIgnore annotation to avoid the reccursion. But when I inserted the values Employee table got updated but the joining tabled is not updating.
This is my Employee entity class
#Entity
#Table(name = "Employee")
public class Employee implements Serializable{
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long emp_id;
#Column(name = "emp_fname")
private String emp_fname;
#Column(name = "emp_lname")
private String emp_lname;
#Column(name = "emp_email")
private String emp_email;
#Column(name = "emp_dob")
private Date emp_dob;
#ManyToMany(cascade = CascadeType.MERGE)
#JoinTable(name = "emp_skills",
joinColumns = #JoinColumn(name = "emp_id", referencedColumnName = "emp_id"),
inverseJoinColumns = #JoinColumn(name = "s_id",referencedColumnName = "s_id"))
#JsonIgnore
private Set<Skills> skills;
}
This is my Skills class
#Entity
#Table(name = "Skills")
public class Skills implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long s_id;
#Column(name = "s_name")
private String s_name;
#ManyToMany(mappedBy = "skills")
private Set<Employee> employees;
And this is my controller class method to save data
#RequestMapping("/save")
#PostMapping("/save")
#CrossOrigin
public void createEmployee(#RequestBody Employee employee, BindingResult bindingResult){
Employee emp = new Employee(employee.getEmp_fname(),employee.getEmp_lname(),employee.getEmp_email(),employee.getEmp_dob());
emp.setSkills(employee.getSkills());
empRepository.save(emp);
//empRepository.save(new Employee(employee.getEmp_fname(),employee.getEmp_lname(),employee.getEmp_email(),employee.getEmp_dob()));
}
I want to update both Employee and emp_skills (the joining table) when the save method is triggered.

Cannot delete parent and child

I have two entities using Spring and Hibernate
Entity A:
#Entity
#Table(name = "A")
public class A {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "a")
private B b;
Here i have a one to one relationship with Entity B, the owner of the relationship is Entity A.
Entity B:
#Entity
public class B{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne
#JoinColumn(name = "a_ID")
private A a;
Saving the entities gives no problem. Entity B gets the ID of entity A in the Database.
But when i delete Entity A, I also want to delete Entity B that belongs to A.
When I delete i get the error:
MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
I think my declarations in my entities are correct. What is the problem here?
Edit
When I inspect the table of Entity B and specifically the Foreign key to Entity A it says Restricted on Update en on Delete
set orphanRemoval property to true in class A
like this: #OneToOne(mappedBy = "a", cascade = CascadeType.ALL, orphanRemoval = true)

Alternative for #Formula?

I have two objects:
#Table(name = "user")
User
#Id
Integer id
Integer uuid;
and reservation:
#Table(name = "reservation")
Reservation
#Id
Integer id;
Integer uuid;
My goal is:
#Table(name = "reservation")
Reservation
#Id
Integer id;
Integer uuid;
#Formula("(SELECT * FROM user b WHERE b.uuid = uuid )")
List<User> users;
The problem is #Formula doesnt work with objects.
How to include list of all users in reservation with same uuid?
I found this but maybe there is better option
https://stackoverflow.com/a/37502703/3871754
Support of relationships that references non-PK columns is an optional feature. In simple cases it's supported by Hibernate
#NotAudited
#OneToMany
#JoinColumn(name = "uuid", referencedColumnName = "uuid")
private List<Barrier> barriers = new ArrayList<>();
and implemented Serializable for Reservation

How to fetch set of data using ID in hibernate if we have composite primary key?

I have Entities (Student,StudentSkills, StudentEmpSkills)
Student.java
#Entity
#Table(name = "Student", catalog = "dbs")
public class Student implements java.io.Serializable {
private int id;
...
...
private Set<StudentSkills> studentSkills= new HashSet<StudentSkills>(0);
private Set<StudentEmpSkills> studentEmpSkills= new HashSet<StudentEmpSkills>(0);
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Student")
public Set<StudentSkills> getStudentSkills() {
return this.studentEmpSkills;
}
public void setStudentSkills(
Set<StudentSkills> studentSkills) {
this.studentSkills = studentSkills;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Student")
public Set<StudentEmpSkills> getStudentEmpSkills() {
return this.StudentEmpSkills;
}
public void setStudentEmpSkills(
Set<StudentEmpSkills> studentEmpSkills) {
this.studentEmpSkills= studentEmpSkills;
}
}
in StudentEmpSkills.java
#Entity
#Table(name = "studentEmpSkills", catalog = "npdbs")
public class StudentEmpSkills implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private StudentEmpSkillsId id;
private Student Student ;
......
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "studentID", nullable = false, insertable = false, updatable = false)
public Student getStudent() {
return student;
}
In the above we are getting the Set of StudentEmpSkils from Student by one to many and many to one relation.
as we are getting Student from StudentEmpSkill
In JoinColumn we are giving studentID column to fetch the abject.
Now I want to get StudentSkill object from StudentEmpSkills.
StudentSkills - (studentID* | skillID*) | skillname
StudentEmpSkills - (studentID* | skillID* | empID*) | empName
(..) - composit primary key
So I want to fetch StudentSkills from StudentEmpSkill
What I need to write in StudentEmpSkills to fetch StudentSkill. because we have composit primary key in StudentSkill.
How to map the StudentSkill to StudentEmpSkills.
Can anyone please suggest?