join between two table in spring and hibernate Mysql - spring

Table 1 name is users field name is userid ,roleid and username
Table 2 name is roles field name is roleid and rolename
I want to create relation between these two table.
I have follows more than 10 example. but i have not got any result.
Please help me and create the code according to me
Thanks

In order to create a relation between two entities/tables, you need to determine the type of relation you want to represent, whether that is a one-to-one, one-to-many, many-to-one, or many-to-many.
For your use case between a User and Role, this is typically a many-to-many because a User is associated to many roles and a role may be associated to many differing users.
User.java:
#Entity
public class User {
/* other things */
#ManyToMany
#JoinTable(name = "user_roles")
private List<Role> roles;
}
Role.java
#Entity
public class Role {
#ManyToMany(mappedBy="roles")
private List<User> users;
}
In this particular example, the relationship is owned by the User beacuse typically you would have roles created separately and then you associate a user to a set of roles.

Related

How can I reuse an #Id column for a composite key in a JPA Repository?

I have an Activity object. An Activity belongs to a User. An Activity can be assigned a Category. A Category also belongs to a User.
#Entity
public class Activity {
// id column omitted
#ManyToOne(cascade = CascadeType.ALL)
private User user;
#ManyToOne(cascade = CascadeType.ALL)
private Category category;
// other properties omitted ...
}
This creates a table
Activity
id
user_id
etc...
The Category is essentially just a name, so I want [name + user] to be its composite key.
#Entity
public class Category {
#Id
#ManyToOne
private User user;
#Id
private String name;
}
This creates a table
Category
name
user_id
But then also adds the composite key to the Activity table
Activity
id
user_id
category_name
category_user_id
which is of course needed, and functional, but not ideal.
I would like to use the existing user_id column in the Activity table to be used for the foreign composite key. Functionally, the Activity's User will always be the Category's User, and my application logic will make it so.
Activity
id
user_id
category_name
where [user_id + category_name] forms the foreign composite key.
How do I structure this in my objects? and how do I annotate it using JPA so the tables are how I want them?

ForeignKey between User and UserRole with Spring Security

Actually i have an authentication that works with rbac.
The problem is that, i encoutered a case where a user was deleted, but in the database, the user id and role were still present.
When the user was recreated he got the roles of a former user who had this id.
Acutally i can't delete user role of a user that has been delete because it's an enum..
Is it possible to create a relationship between users and roles while keeping this enumeration principle? Or another solution ?
public class AppUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
....
#ElementCollection(fetch = FetchType.EAGER)
#Enumerated(EnumType.STRING)
List<AppUserRole> appUserRoles;
}
public enum AppUserRole implements GrantedAuthority {
ROLE_ADMIN, ROLE_DEMO;
public String getAuthority() {
return name();
}
}
When deleting an entity with an #ElementCollection the delete is cascaded automatically. When doing this through SQL this (might) not be the case, depending on how cascade rules are applied in your database.
But with your setup that should happen automatically.
See also https://stackoverflow.com/a/7696147/2696260
Here is an example of how the roles table for the #ElementCollection can be created (PostgreSQL syntax):
CREATE TABLE user_roles (
user_id int,
role text,
PRIMARY KEY (user_id, role),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
The foreign key with the ON DELETE CASCADE makes sure that the associated roles are deleted when user is deleted.

Fetch a parent by a child in Many-to-Many unidirectional relationship JPA

I have two entities Estate and PropertyTags in a Spring Boot application. The Estate entity has a many-to-many relationship with the PropertyTag (PropertyTag is also used by other entities)
This is the Estate entity:
#Entity
public class Estate{
#Id
private Long id;
.
.
#ManyToMany
private Set<PropertyTag> propertyTags;
.
.
// other properties
}
And the PropertyTag class:
#Entity
public class PropertyTag{
#Id
private Long id;
private String tagName;
// getters and setters
}
The above relationship created 3 database tables with one table for foreign keys of the relationship.
I need a repository method (or query) that will retrieve an Estate that will take and argument of an estate Id and property tag object.
I tried using the hibernate keywords as below:
public interface EstateRepository extends JpaRepository<Estate, Long> {
Optional<Estate> findByIdAndPropertyTagsContaining(Long estateId, PropertyTag childTag);
}
But that did not work.
I do not want to retrieve an estate via its ID and manually loop through its property tags to check if a tag exists in its collection. I feel this can be done with a query of the database
I am not so good at writing custom queries. I need help with the query to do that.
Thank you.
To get an Estate entity by the PropertyTag entity you can also just use the id of the PropertyTag and try
Optional<Estate> findByIdAndPropertyTags_Id(Long estateId, Long propertyTagId);
Which should return the Estate containing a tag with the given ID.
Containing is used for String searching

Must I create a mapping relationship between two entities in hibernate?

For example, if you have an order table in Hibernate and a product table that receives an order, it is mapped as a one to many relationship.Then,Must I write the mapping relationship in code here? In my project, I permanently store order information in a database I have, but in that case, does it need to be a mapping relationship?There's nothing else to do except delete cascade i think.
If you want to use the association in your business code, you also need to model in your domain model. In the described example, I would expect a many-to-many association between the Order and the Product entity. You could model it as a uni- (= only on 1 entity) or bidirectional (= on both entities) association.
Here is a quick example. I provide a very detailed description of all kinds of associations in my guide to association mappings.
public class Order {
#ManyToMany
private Set<Product> products;
...
}
public class Product {
#ManyToMany(mappedBy = "products")
private Set<Order> orders;
...
}

Criteria not working as intended - retriving from two tables

I have two classes which are associated with each other as OneToOne
User {
int user_id
#OneToOne
UserAccount useraccount
Role role;
}
UserAccount {
int useraccount_id
#OneToOne
User user;
}
What I am trying to do is to retrieve a list of UserAccount where User role does not equal manager. The following is the query I set up and I can't get it working.
Criteria userCriteria = getSession().createCriteria(User.class);
userCriteria.add(Restrictions.ne("role", Role.MANAGER));
userList = (List<User>) userCriteria.list();
It retrieves a list of User.class object ignoring the restriction.

Resources