Two ManyToMany relationships in one JPA entity - mysql

I have an entity called User with two many-to-many relationships: User -mtm - Role and User -mtm - Course
public class User {
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "users_roles",
joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "role_id", referencedColumnName = "id")})
private List<Role> userRoles;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "users_courses",
joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "course_id", referencedColumnName = "id")})
private List<Course> orderedCourses;
}
In Course entity:
public class Course {
#ManyToMany(mappedBy = "orderedCourses")
private List<User> participants;
}
It looks similar in the Role entity.
When user with e.g. two roles assigned enrolls himself to some course (means that course is added to his orderedCourses list), he gets this course twice.
So the user with two roles gets registered for the same course twice, user with 3 roles gets it three times etc.
It is noticeable in the junction table in the database. (one user has the same course few times which is unacceptable).
Looks like one ManyToMany relationship has an impact on another. But I don't know what is wrong.
Everything is persisted to MySQL database by Hibernate (via Spring Data JPA)

Related

Spring delete row of join table

I have two entities User:
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userID;
#Column(name = "userHashedPassword")
private String password;
#Column(name = "userName")
private String userName;
#Column(name = "userEmail")
private String email;
#Transient
private List<String> groups = new LinkedList<>();
#ManyToMany
#JoinTable(name = "UserRoles",
joinColumns = #JoinColumn(
name = "userID"),
inverseJoinColumns = #JoinColumn(
name = "roleID"))
private Set<Role> roles = new HashSet<>();
#OneToMany(mappedBy = "user")
private Set<Rating> ratings;
protected User(){}
public User(String userHashedPassword, String userName, String email, Set<Role> roles){
this.password = userHashedPassword;
this.userName = userName;
this.email = email;
this.roles = roles;
}
//getters and setters
}
And Group:
#Table(name="FocusGroups")
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
property = "groupID")
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long groupID;
private String groupName;
#ManyToMany
#JoinTable(name = "GroupMembers",
joinColumns = #JoinColumn(
name = "groupID"),
inverseJoinColumns = #JoinColumn(
name = "userID"))
private Set<User> groupMembers = new HashSet<>();
#ManyToOne(fetch = FetchType.EAGER, optional = true)
#JoinColumn(name="frameworkID", nullable = true)
private Framework framework;
public Group(){}
public Group(String groupName, Set<User> groupMembers, Framework framework) {
this.groupName = groupName;
this.groupMembers = groupMembers;
this.framework = framework;
}
//getters setters
}
When I delete a User, I want to remove them from group members, however it fails due to foreign key constraint: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (capripol.groupmembers, CONSTRAINT FK98tbu0sjfsn1m5p340dn0v8wo FOREIGN KEY (userID) REFERENCES users (userID))
How do I work around this?
Well, I will try to answer: First of all, it is rather strange you refer on Groups in user
entity like that:
#Transient
private List<String> groups = new LinkedList<>();
It this case, you will not have a column group in user table in database, hence you have to first perform removal from group_members for an all groups:
delete from group_members where userid = <user_id_you_want_to_remove>;
And only after your JoinTable table does not contain any refers to user with <user_id_you_want_to_remove>, than you can execute
delete from users where userid = 1;
Note: there is no matter you do it by spring data (e.g. deleteById(Long id) and using #Query annotation specify the query above in SQL or HQL, up to you) - this will work. But I highly recommend you to reconsider you database structure - it is not cute to store only one entity.

Get children for any level in tree structure but without theirs children using Hibernate?

I have a Folder entity in Hibernate, like so:
#Entity
#Table(name = "folders")
public class Folder {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "folder_id", unique = true, nullable = false)
private int id;
#NonNull
#Column(name = "name", length = 100, unique = true, nullable = false)
private String name;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", orphanRemoval = true)
#Column(name = "sub_folders")
private Set<Folder> childFolders = new HashSet<>();
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JsonIgnore
#JoinColumn(name = "parent", referencedColumnName = "folder_id", nullable = true)
private Folder parent;
public Folder() {
}
}
I'm trying to write a finder method or custom query which will do what I wrote in the subject.
So if I send a request going like folders/{parent_folder_id}, let's say value being 1, I should get objects 4 and 5, but without their children, so not including 6,7,8 and 9.
Ideally, hibernate query would be preferred. If not, any sql language is also fine. I'll try to tumble it up to hibernate.
This is what I got, I still get children...
#Query(value = "Select * from folders f where f.parent = ?1 ", nativeQuery = true)
Set<Folder> getFolders(int folder_id);
I think this should work:
make the default fetchtype lazy:
#OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", orphanRemoval = true)
#Column(name = "sub_folders")
private Set<Folder> childFolders = new HashSet<>();
Use a JOIN FETCH in order to eagerly fetch the relationships you want.
SELECT f FROM folders f JOIN FETCH f.childFolders
You probably can achieve something similar with entity graphs but I'm not sure about their interaction with queries.
I got what I need with following query:
#Query(value = "Select folder_id, name, parent From folders f Where f.parent = ?1", nativeQuery = true)
This will give me just name of the folder and its Id.

Hibernate Annotations : Many-to-Many relationship using Join table having common attribute in PK

Is it possible to define a many to many relationship between two tables using a join table which has composite key, having a common attribute between the two tables?
Let's say, we have a table structure like below and am trying to define association between kit and business_product using kit_business_product table. Here are the table definitions (simplified for this question).
Table 1 : kit
PK1 : kit_id, business_id
Table 2 (Join Table) : kit_business_product
PK2 : kit_id, business_id, manufacturer_id, product_id, name
Table 3 : business_product
PK3 : business_id, manufacturer_id, product_id, name
Here are the java classes for these tables (simplified for this question).
Kit.java
#Entity
#Table (name= "kit")
public class Kit
{
#EmbeddedId
private KitId id;
#ManyToMany
#JoinTable(name = "kit_business_product",
joinColumns = {#JoinColumn(name = "kit_id", referencedColumnName = "kit_id", nullable = false, insertable = false, updatable = false),
#JoinColumn(name = "business_id", referencedColumnName = "business_id", nullable = false, insertable = false, updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "business_id", referencedColumnName = "business_id", nullable = false),
#JoinColumn(name = "manufacturer_id", referencedColumnName = "manufacturer_id", nullable = false),
#JoinColumn(name = "product_id", referencedColumnName = "product_id", nullable = false),
#JoinColumn(name = "name", referencedColumnName = "name", nullable = false)
})
private Set<BusinessProduct> businessProducts = new HashSet<BusinessProduct>();
}
KitId.java
#Embeddable
public class KitId
{
#Column (name = "kit_id")
private String kitId;
#Column (name = "business_id")
private long businessId;
}
BusinessProduct.java
#Entity
#Table(name = "business_product")
public class BusinessProduct
{
#EmbeddedId
private BusinessProductId id;
}
BusinessProductId.java
#Embeddable
public class BusinessProductId
{
#Column(name = "business_id")
private long businessId;
#Column(name = "manufacturer_id")
private long manufacturerId;
#Column(name = "product_id")
private String productId;
#Column(name = "name")
private String name;
}
With this code, I get the below given error.
[RMI TCP Connection(3)-127.0.0.1] 2017-03-17 14:17:54,767 ERROR com.common.DatabaseSession [] Repeated column in mapping for collection: com.hibernate.Kit.businessProducts column: business_id
org.hibernate.MappingException: Repeated column in mapping for collection: com.hibernate.Kit.businessProducts column: business_id
at org.hibernate.mapping.Collection.checkColumnDuplication(Collection.java:341) ~[hibernate3.jar:3.6.10.Final]
at org.hibernate.mapping.Collection.checkColumnDuplication(Collection.java:364) ~[hibernate3.jar:3.6.10.Final]
What would be the correct annotation for such a scenario? Any insight would be greatly appreciated. Thanks!

Data lost when trying to edit record

I'm currently having this issue: I have 3 tables: users, roles and users_roles as in the picture below:
whenever I edit any of the record in users table, the record of that user in the users_roles table will be lost.
For example, I changed the username of the user which holds the userId = 2, then in the users_roles table, the row of userId = 2 will be lost.
Anybody has any ideas of this problem? I'm using Spring with Hibernate
*UPDATE
In my Role.java
#ManyToMany(fetch = FetchType.EAGER, mappedBy = "roles")
private List<User> users;
In my User.java
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "userId", nullable = false) , inverseJoinColumns = #JoinColumn(name = "roleId", nullable = false) )
private List<Role> roles;
And in my UsersRoles.java
#Id
#Column(name="userId")
private int userId;
#Id
#Column(name="roleId")
private int roleId;
This is the DAO implementation method I used for Edit
#Override
public void edit(User user) {
session.getCurrentSession().saveOrUpdate(user);
}
P/S: this not only happens when I edit with my web-app, but also happens when I edit directly in MySQL environment. I don't know...

Null not allowed, but should be nullable

I have two tables joining with a mapping table. I am getting a null constraint issue though. Below is the error message and the two mappings. Since both are manyTomany my assumption is that the many could be none, how can I make it so either product_id or category_id can be null?
Error Message
Caused by: org.h2.jdbc.JdbcBatchUpdateException: NULL not allowed for column "PRODUCT_OPTION_ID"; SQL statement:
insert into ImageMapping (product_id, image_id) values (?, ?) [23502-168]
Categories
#JoinTable(
name = "ImageMapping",
joinColumns = #JoinColumn(name = "category_id"),
inverseJoinColumns = #JoinColumn(name = "image_id")
)
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Set<Image> categoryImageId;
Products
#JoinTable(
name="ImageMapping",
joinColumns = #JoinColumn(name = "product_id"),
inverseJoinColumns = #JoinColumn(name = "image_id")
)
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Set<Image> productImageGroup;
Product Options
#JoinTable(
name="ImageMapping",
joinColumns = #JoinColumn(name = "product_option_id"),
inverseJoinColumns = #JoinColumn(name = "image_id")
)
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Image> productOptionImageGroup;
You should have a separate join table for each of your associations instead of trying to use the same one for all.