Criteria not working as intended - retriving from two tables - spring

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.

Related

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.

What is the way to ensure #OneToOne relationship in Spring?

I have a entity relationship setup as #OneToOne. For example (User <--> Pet)
#Entity
public class Pet {
#OneToOne
#JoinColumn(name = "user_id", nullable = true)
User user;
}
#Entity
public class User {
#OneToOne(mappedBy = "user")
Pet pet;
}
To my surprise, Spring will allow you to assign multiple entities into the relationship (Multiple Pets associated with User) when you save via the repositories.
//for example:
pet.user = user1;
pet2.user = user1;
petRepository.save(pet);
petRepository.save(pet2); //allowed
But then after the save, the database will now be corrupted.
By calling petRepository.findAll or findById or anything really...will now yield this error
nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 1245, for class: package.models.Pet
So what is the proper way to ensure OneToOne relationship so as to not corrupt the db?

Query in arraylist by one element in spring boot h2

I have a ClassRoom class, in my Spring Boot application. Here is what it looks like :
public class ClassRoom {
#Id #GeneratedValue Long classRoomID;
ArrayList<User>adminList=new ArrayList<>();
}
And in my ClassRoomRepository class, I have :
public interface ClassRoomRepository extends JpaRepository<ClassRoom,Long> {
#Query("select ClassRoom from ClassRoom c where c.adminList = ?1")
ArrayList<ClassRoom> findByAdminList(ArrayList<User> adminList);
/*
#Query("select ClassRoom from ClassRoom c where c. = ?1")
ArrayList<ClassRoom> findByAdmin(User admin);
*/
}
I can query to select ClassRoom where ArrayList of ClassRoom gets passed parameter.
But I want to query to select ClassRoom where I pass only one User as parameter and returns ArrayList of ClassRoom.(Commented section-nothing done so far)
If it is possible in this interface, how can I do so?
Asuming you habe many-to-many association using join table, this is what you need,
#Query(value = "SELECT DISTINCT cr FROM ClassRoom cr JOIN cr.admins a WHERE a = ?1")
List<ClassRoom> findAllByAdmin(final Admin admin);
When mapping collection , Hibernate requires it to declare it using interface type such as List , Set , Map etc. But you are using ArrayList to declare the admin list , I am guessing the whole list will be stored to a single column with some binary data type in DB . No one would store the data in this funny way when using RDBMS unless you have strong reason to do it.
From what you describe , ClassRoom and User seem to be many to many. For demonstration convenience , I would map it as #ManyToMany:
#Entity
#Table
public class ClassRoom {
#ManyToMany
#JoinTable(name ="classroom_user",
joinColumns = #JoinColumn(name = "classroom_id"),
inverseJoinColumns = #JoinColumn(name = "user_id"))
private List<User> admins = new ArrayList();
}
#Entity
#Table
public class User{
#ManyToMany(mappedBy = "admins")
private List<ClassRoom> classRooms = Lists.newArrayList();
}
Then given an user admin ,to get all of his administrative class rooms :
#Query("select distinct cr from ClassRoom cr left join fetch cr.admins admin where admin = ?1 ")
public List<ClassRoom> findByAdmin(User admin);
Or :
#Query("select distinct cr from ClassRoom cr where ?1 member of cr.admins")
public List<ClassRoom> findByAdmin(User admin);

join between two table in spring and hibernate Mysql

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.

Spring MongoDB + QueryDSL query by #DBRef related object

I am using spring-data-mongodb and querydsl-mongodb to perform more flexible queries.
My application has users and orders.
An user can have multiple orders, so my models looks like this:
public class User {
#Id
private String id;
private String username;
//getters and setters
}
public class Order {
#Id
private String id;
#DBRef
private User user;
//getters and setters
}
As you can see, there is an has-many relationship between users and orders.
Each order is assigned to an user, and the user is stored in #DBRef public User user attribute.
Now, lets say that an user has 10,000 orders.
How can i make the query to get all orders that belongs to an specific user ?
I have the OrderRepository:
public interface OrderRepository extends MongoRepository<Order, String>,
QueryDslPredicateExecutor<Order> {
}
I tried this solution but it doesnt return anything:
QOrder order = new QOrder("order");
Pageable pageable = new PageRequest(0, 100);
return userRepository.findAll(order.user.id.eq(anUserId), pageable);
I need to use querydsl because i want to build a service that can query orders by more many prameters than userid. For example i want to get all orders that belongs to user with specific username.
No need for QueryDSL when searching by ID. In OrderRepository, create an interface method:
public List<Order> findByUser(String userId);
Request example: curl http://localhost:8080/orders/search/findByUser?userId=5a950ea0a0deb42729b570c0
* I'm stuck on how to query orders, for example, of all users from certain city (some mongo join with user and address).

Resources