hibernate path expected for join but path is set - java

I have an hql query:
"from User u inner join UserRole ur on ur.user_name = u.user_name and ur.user_role =ROLE_MANAGER "
And it shows an error though the path is set. I tried different variants of hql but error remains the same. I use those 2 entites for spring security login from db and it works fine. But when i'm trying to get user with specified role it doesn't work.
My entities:
#Entity
#Table(name = "USERS")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private int user_id;
#Column(name = "username", nullable = false, unique = true)
private String username;
#Column(name = "passwort", nullable = false)
private String password;
#Column(name = "email")
private String email = "hromnikforever#gmail.com";
#Column(name = "enabled", nullable = false)
private int enabled = 1;
#Autowired
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
UserRole entity:
#Entity
#Table(name = "USER_ROLES")
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id",unique = true, nullable = false)
private int user_role_id;
#Column(name = "username")
private String username;
#Column(name = "user_role")
private String user_role;
If i change my HQL query to:
from User u inner join u.userRole ur on ur.user_name = u.user_name
and ur.user_role =ROLE_MANAGER "
it shows an error that
could not resolve property: userRole of: com.webproject.User [from com.webproject.User u inner join u.userRole ur on ur.user_name = u.user_name and ur.user_role =ROLE_MANAGER ]

Instead explicit JOIN try with comma notation, and change the second JOIN table with UserRole, as follow:
from User u, UserRole ur
where ur.user_name = u.user_name
and ur.user_role = ROLE_MANAGER
If you want only User elements complete your query as follow:
select u from User u, UserRole ur
where ur.user_name = u.user_name
and ur.user_role = ROLE_MANAGER

You have a typo in your query, since your User entity doesn't have a userRole, but userRoles
from User u
inner join u.userRoles ur on ur.user_name = u.user_name
and ur.user_role = ROLE_MANAGER

Related

How to join two entities with ManyToMany relationship in the jpa query

I have two entities User and Role. Each user can have multiple roles.
User class
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
#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 = new HashSet<>();
}
Role class:
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
private String name;
}
So a new joined table is being created called: user_role
I want to create a query for returning a list of users with role_id of 4, for example.
The query that I already tried:
#Override
public List<User> getArtists() {
return em.createQuery(
"from User u, Role r where u.roles='4'",
User.class
).getResultList();
}
How can I fix this query in order to retrieve a list of users with role_id of 4?
You can do something like this:
List<User> users = em.createQuery(
"select distinct u from User u join fetch u.roles rl where rl.id = :id",
User.class)
.setHint( QueryHints.HINT_PASS_DISTINCT_THROUGH, false )
.setParameter("id", 1L)
.getResultList();
The QueryHints.HINT_PASS_DISTINCT_THROUGH is added as an additional performance optimization. But please note that this optimization will work only with hibernate 5.2.2.Final ... 5.2.11.Final. It was broken in the 5.2.12.Final.
If I were you, I will get the benfit of using SpringdataJpa with hibernate and just use this statment :
If you don't want to use query :
List<User> findByRoles_Id(Long id);
In your User Repository :
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByRoles_Id(Long id);
}

Passing Queries from Postgres to JPA

I'm newbie
I'm trying pass this Postgres query to JPA/JPQL
SELECT
DISTINCT(srv.code) AS Serv_Cod,
srv.id AS Serv_id,
srv.description AS Serv_Desc
FROM db.Category AS cat
join db.Classification AS cla ON cat.id = cla.cat_id
join db.Service AS srv ON srv.id = cla.srv_id
WHERE cat.id = 10
ORDER BY srv.id;
Now I want to write the same Query, I have the Entities with the same name Table.
Classification
#Entity
#Table(name = "Classification", schema = "db")
#Audited
public class Classification implements Identifiable<Long> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "srv_id", nullable = true)
private Service service;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "cat_id", nullable = true)
private Category category;
....
}
Service
#Entity
#Table(name = "Service", schema = "db")
#Audited
public class Service implements Identifiable<Long> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "code", nullable = false)
private String code;
#Column(name = "description", nullable = false)
private String description;
....
}
I was reading, but I'm very confused...
I don't know how to write the ON for the JOIN, and establish the DISTINCT for a Column/Field.
Long myID = 25L;
this.em.createQuery("SELECT NEW SomeDto(srv.id, srv.code, srv.description)"
+ " FROM Classification cla"
+ "JOIN cla·cat_id cat"
+ "JOIN cla·srv_id srv"
+ "WHERE cat.id = :id"
,BaseObjectDto.class).setParameter("id", myID).getResultList();
Thank you for you valuable Help.
The query is very simple. When you have ToOne relationships you can navigate to the related entity. There is no need to JOIN ON.
Even with ToMany there is no need for the ON because this is already defined in the mapping.
So the query will look like:
SELECT NEW SomeDto(cla.service.id, cla.service.code, cla.service.description)
FROM Classification cla
WHERE category.id = :id

how to write hql query for hibernate OneToMany relationship?

I have the following classes laid out like so:
class User {
#Id
private long id;
#OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
Set<UserRole> userRoles;
}
class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "role", nullable = false, length = 45)
private String role;
}
I'm attempting to query for users that have a specific role (in this case, all users with the role ROLE_ADMIN), using the following query:
org.hibernate.query.Query<User> userQuery=session.createQuery("from User as mc where mc.userRoles in (from UserRole as ur where ur.role in (:uRoles))",User.class);
Set<String> roles = new HashSet<String>();
roles.add("ROLE_ADMIN");
userQuery.setParameterList("uRoles", roles);
List<User> admins = userQuery.getResultList();
However, the query is not returning any results.
session.createQuery(
"from User as user join user.userRoles as userRole where userRole.role in :roles")
.setParameter("roles", Arrays.asList("ROLE_ADMIN"))
.getResultList();

How corectly select entity with ManyToMany realationship in Hibernate jpa

I have two tables(entities):
#Entity
#Table(name = "users")
#NamedQuery(name = "User.getAll", query = "SELECT c from User c")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#NotNull
#Column(name = "LOGIN")
private String login;
#Column(name = "PASSWORD", length = 64)
private String password;
#Column(name = "SALT", length = 80)
private String salt;
#ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Role> roles;
#OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Permission> permissions;
And
#Entity
#Table(name = "roles")
#NamedQuery(name = "Role.getAll", query = "SELECT c from Role c")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "ROLE_NAME", length = 100)
private String roleName;
#ManyToMany(mappedBy = "roles")
private Set<User> users;
And method for select Users:
#Override
public List<User> getUsersList() {
Criteria criteria = getSession().createCriteria(User.class);
return (List<User>)criteria.list();
}
I have 2 users. First user has 2 roles and second user has 1 role.
But this method return me 3 users. User who has 2 role is dublicate.
Itried criteria.createCriteria("", JoinType.NONE);
but it not helped.
You need to use criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY), check:
criteria-distinct-root-entity-vs-projections-distinct

JPQL join condition in linked Entity class

I'm using the following SQL to join employees, user_projects and project_master
SELECT DISTINCT usr.user_number,
emp.emp_name
FROM employees emp
LEFT JOIN user_projects usr
ON (emp.user_number = usr.user_number)
JOIN project_master mast
ON (usr.project_id = mast.project_id)
WHERE mast.active = 'Y'
AND emp.user_number = 'SMITH'
In Employee entity, I have the following JPQL defined as namedQuery
#NamedQuery(name = "Employee.findProjects", query = " select DISTINCT u.userNumber,e.empName" +
" from Employee e LEFT JOIN e.userProjectsList u where e.userNumber='SMITH' ")
Not sure how to link UserProjects and ProjectMaster to create a where condition
mast.active = 'Y' in Employee entity's findProjects namedQuery
How to join UserProjects and ProjectMaster in Employee Entity class?
Entities
Entity Employee
#Table(name = "EMPLOYEES")
public class Employee implements Serializable {
#Id
#Column(name = "USER_NUMBER", nullable = false)
private String userNumber;
#Column(name = "EMP_NAME")
private String empName;
#OneToMany(mappedBy = "employee")
private List<UserProjects> userProjectsList;
Entity UserProjects
#Table(name = "USER_PROJECTS")
public class UserProjects implements Serializable {
#Id
#Column(name="PROJECT_ID", nullable = false, insertable = false,
updatable = false)
private String projectId;
#Id
#Column(name="USER_NUMBER", nullable = false, insertable = false, updatable = false)
private String userNumber;
#ManyToOne
#JoinColumn(name = "PROJECT_ID", referencedColumnName = "PROJECT_ID")
private ProjectMaster projectMaster;
Entity ProjectMaster
#Table(name = "PROJECTMASTER")
public class ProjectMaster implements Serializable {
#Id
#Column(name="PROJECT_ID", nullable = false)
private String projectId;
#Column(name="PROJECT_DESCRIPTION")
private String projectDesc;
#Column(name="ACTIVE")
private String active;
select DISTINCT u.userNumber,e.empName from Employee e LEFT JOIN
e.userProjectsList u JOIN u.projectMaster pm
where e.userNumber='SMITH' AND pm.active='Y'
Isn't this work?

Categories