I am new with Spring jpa and I am trying to perform the deletion operation on spring jpa many to many database. My database has user and drug. I can delete an user and deletes also the rows associated to it from user_drug table, I can delete a drug that has no linking to the user_drug table, but i cannot delete a drug that is also in the user_drug table.
I had a look on this page but the solutions from there do not work for me.. How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?
Here is my code for User entity:
#ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
#JoinTable(name = "user_drug",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "drug_id", referencedColumnName = "id"))
private Set<Drug> drugs = new HashSet<>();
Here is the code for Drug entity:
#ManyToMany(mappedBy = "drugs", fetch=FetchType.EAGER)
private Set<User> users = new HashSet<>();
And here is the delet method from DrugServiceImpl:
public void delete(Drug drug)
{
drug.getUsers().clear();
drugRepository.delete(drug);
}
I have also printed the size of drug.getUsers() after clear operation and it is 0. Why isn't it delete the drug from database?
I've tried in many ways.. Can someone please send some help?
that is how the cascade works it deletes from the relation table only and in the ManyToMany the relation table here is the user_drug table
and for this cases there are many solution one of them is deleting the drug in the same transaction of the deleting user
but another solution that will save the effort that you create the ManyToMany table as entity and put cascade on the drug object in the relation table
like this
But this in the User entity
#ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user")
private Set<UserDrug> drugs = new HashSet<>();
the UserDrug entity
public class UserDrug {
#ManyToOne
#JoinColumn(name="user_id")
User user;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="drug_id")
Drug drug;
}
Related
I have 2 entities, one for a taskList and the other for users. The users can create tasks for themselves or their friends, so in the Tasks entity I have different columns referencing the User entity, one for createdBy another for createdFor and a last one for modifiedBy.
In the tasks entity I made the following #ManyToOne JPA relationships:
#ManyToOne(optional = false)
#JoinColumn(name = "created_by", nullable = false,
referencedColumnName = "id")
private User createdBy;
#ManyToOne
#JoinColumn(name = "created_for", nullable = false,
referencedColumnName = "id")
private User createdFor;
#ManyToOne
#JoinColumn(name = "modified_by", nullable = false,
referencedColumnName = "id")
private User modifiedBy;
But I am not sure how to do the linking in the Users side, I had the following #OneToMany relationship:
#OneToMany(mappedBy = "createdFor", cascade = CascadeType.ALL)
private List<Task> taskList;
But I am not sure how to proceed with the other relationships as I don't really need a taskList for the tasks that a user created, or what tasks did he modify.
You do not need to map all things in an Entity , and also do not need to configure every relationships as bi-directional.
So if you really do not need to access the Tasks that are created and modified from a given User , just ignore them and do not map them in User.
It is perfectly valid to configure a relationship as unidirectional. Your existing codes should already work perfectly.
I'm trying to link mysql tables (role, user, user_role).
UserModel entity contains a field 'roles'.
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_role", joinColumns = {#JoinColumn(name = "user_id")},
inverseJoinColumns = { #JoinColumn(name = "role_id") })
private Set<Role> roles;
Role entity contains a field 'users'
#Transient
#ManyToMany(mappedBy = "roles")
private UserModel users;
When i save a user, new rows are automatically created in the table 'roles'. How to cancel duplicate roles?
You are cascading all operations from the UserModel over the roles attribute to entity Role. So whenever you persist a user, it persists its roles as well. Try removing the cascade = CascadeType.ALL or replace the cascading to something less "brute force".
There's an Entity Class 'A' (supposed to be a Person),There's another Entity Class 'B' (supposed to be a Contract).
Entity 'A' has a relation #OneToMany to Class 'B' ( a person can sign alot of contracts). Entity 'B' also has a relation #OneToMany to Class 'A' (a contract can have many person signing it).
In this case, there's gonna be 2 JoinTable in database, but actually they both are somehow the same.
Is there anyway that i make them just using One JoinTable?
tnx for any help!
Looks like a #ManyToMany relation to me...
in class Person
#ManyToMany
#JoinTable(name="PERS_CONTRACTS")
public Set<Contract> getContracts() { return contracts; }
in class Contract
#ManyToMany(mappedBy="contracts")
public Set<Person> getSigners() { return signers; }
By using two #OneToMany there is no JoinTable.
you can use #ManyToMany like this
#ManyToMany
#JoinTable(
name="AB",
joinColumns=#JoinColumn(name="A_ID", referencedColumnName="ID"),
inverseJoinColumns=#JoinColumn(name="B_ID", referencedColumnName="ID"))
private List<B> bS;
Its a kind of Many to Many relationships. So it need just one junction table like person_contract in database. It will contains columns like:
Person_id
Contract_id
where both person_id & contract_id will be a composite unique key.
In hibernate it will be:
1. In Person table
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "person_contract ", joinColumns = {
#JoinColumn(name = "person_id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "contract_id",
nullable = false, updatable = false) })
public Set<Contract> contracts;
In Contract table
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "contracts")
public Set<Person> persons;
Situation:
You are complicating things here, the appropriate relationship between your Entities would be ManyToMany, because :
A person can sign many contracts.
And a contract can be signed by many persons.
And one JoinTable in this relationship is sufficient to give you all the requested details:
Who signed a given Contract.
Which Contracts have a Person signed.
Mapping:
So your mapping will be like this:
In your Person class:
#ManyToMany(mappedBy = "persons")
private Set<Contract> contracts= new HashSet<Contract>();
And in your Contract class:
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "PERSONS_CONTRACTS",
joinColumns = #JoinColumn(name = "CONTRACT_ID"),
inverseJoinColumns = #JoinColumn(name = "PERSON_ID")
)
private Set<Person> persons= new HashSet<Person>();
You can check this Hibernate Many-to-Many Association Annotations Example for further details.
I have a oneToMany and ManyToOne mapping in my models:
class college
#OneToMany(fetch = FetchType.EAGER)
#JoinTable(name = "collegecource", joinColumns = #JoinColumn(name = "college", referencedColumnName = "college"), inverseJoinColumns = #JoinColumn(name = "cource", referencedColumnName = "cource"))
private Set<course> course;
In a relation able table collegecource i have one extra column isActive
I want to audit all the tables with create/update/delete.
I added #Audited in collegecource
#Audited
public class collegecource
When i try to create/update parent with relational data Audit working fine.
But when i try to delete relational data (Child data) it is not auditing.
Can You please help me.
If you want audit field, Annotation your field with #Audited.
(Child data)
I am trying to setup and Many to Many relationship between users and roles. I am mostly using JPA Repositories but I also tried using and EntityManger.
I have the following in my main User object.
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "svcAuthUserRolev2", schema="dbo", joinColumns = {
#JoinColumn(name = "user_id", updatable=false,insertable=false, nullable = false) },
inverseJoinColumns = { #JoinColumn(name = "role_id",
updatable=false,insertable=false, nullable = false) })
private Set<AuthRoleEntity> roles;
And the following in my Roles object
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
private Set<AuthUserEntity> users;
No matter what I do if I make changes to the roles on a user when saving they are persisted and this is not what I would like. I want roles on the user object to be read only.
I'm not sure why updateable and insertable are not working, I haven't used those attributes much. One possible solution is to make AuthRoleEntity the owning entity of the many-to-many relationship. Just move the #JoinTable annotation to the AuthRoleEntity and put the mappedBy on the AuthUserEntity.