Spring Data JPA Projection Collections - spring

How can I get all permissions related to user using projections while keeping projection closed?
User
#ElementCollection
#Enumerated(EnumType.STRING)
private List<Permission> permissions;
Permission
public enum Permission {
ADD, UPDATE, DELETE
}
UserRepository query
#Query("select u.username as username, p as permissions from User u "
+ "inner join u.permissions p"
List<UserWithPermissions> findAllProjection();
UserWithPermissions projection
public interface UserWithPermissions {
String getUsername();
List<Permission> getPermissions();
}
Output I want to get
User1 : ADD
User2 : ADD DELETE
Output I get
User1 : ADD
User2 : ADD
User2 : DELETE

Just change your query to
#Query("select u from User u")
List<UserWithPermissions> findAllProjection();
This should work.

Related

How to get payload display as below? I wanted to join multiple roles access into one array(Native Query) as shown in the second example

I a intern student,I tried join table use native query (user, role ,access)it success but when I use get mapping to display role_name and access by email, the payload display not like I want.
Payload when I get by email,I don't display like this. Example 1
Payload I want to get. I want to be display like this. Example 2
Here is my code:
UserRepository.java
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
#Query(value = "SELECT users.name, users.email, role.role_name, access.acc_name FROM users LEFT JOIN user_role ON user_role.user_id = users.id LEFT JOIN role ON role.rid = user_role.role_id LEFT JOIN role_access ON role_access.role_id = role.rid LEFT JOIN access ON role_access.access_id = access.id WHERE users.email= :email", nativeQuery = true)
List<Map<String, Object>> findUserByRoleIdByAccessById(#Param("email") String email);
}
--
UserController.java
#GetMapping("/users/access/{email}")
public List<Map<String, Object>> getuserAccess(#PathVariable(value = "email") String email) {
return userRepository.findUserByRoleIdByAccessById(email);
}

How to fetch a list from document using n1ql with spring-data-couchbase

I want to fetch actions list in user class by username with this query but its not working
#Repository
public interface IUserRepository extends CouchbaseRepository<User,Long> {
#Query("SELECT actions from #{#n1ql.bucket} where #{#n1ql.filter} and userName = $1 ")
List<Action> getActionsByUserName(String userName);
where am ı doing wrong?
__id and __cas must be projected. They are included in n1ql.selectEntity
#Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and userName = $1 ")
Or you can project them yourself :
#Query("SELECT actions, meta().id as __id, meta().cas as __cas from #{#n1ql.bucket} where#{#n1ql.selectEntity} where where #{#n1ql.filter} and userName = $1 ")

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);

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.

JPA #Query annotation does not seem to be using paramter

I have a Spring Boot application using JPA/Hibernate as entity management/modeling. I have the following user class:
#Entity
public class User {
#Id
private Long Id;
private String name;
//more fields, getters and setters below
}
I want users of my application to be able to search for users by name. So in my repository interface, I have:
public interface UserRepository extends JpaRepository<User, Long> {
#Query(value = "SELECT u from User u WHERE lower(u.name) LIKE lower(:name)")
List<User> findByNameLike(#Param(value="name") String nmae);
}
Then in my UserController, I have:
#GetMapping(value = "/users/")
public #ResponseBody List<User> search(#RequestParam String name) {
return this.userRepository.findByNameLike(name);
}
This always returns an empty list. I know the name parameter is coming in correctly.
Moreover, I do know that it is recognizing the #Query annotation, because if I change the query to something like
SELECT u FROM User u
it will return me all users. Or if I change it to
SELECT u from User u WHERE u.name = '%Bob%'
and remove the parameter from the method, it will return all users whose name is Bob. I've tried other variations of the query, such as
SELECT u FROM User u WHERE lower(u.name) LIKE CONCAT('%', lower(:name), '%')
SELECT u FROM User u WHERE u.name = :name (even a simple equals doesn't work)
and so on and so forth. Every source I look at whose syntax I copy seems to say I'm writing the query right, so I think something else must be going on.
I've also tried letting Spring generate the query for me, using
public List<User> findByNameLike(String name);
public List<User> findByNameContaining(String name);
which also don't seem to work. Any help would be appreciated here!

Resources