Not able to create query findByUserId(Long userId) - spring

Not able to create query findByUserId(Long userId)
I have tried
findByUserId(Long user_id)
findByuser_id(Long user_id)
findByUser_id(Long user_id)

Your JPA method, as currently named, expects a user ID variable name of userId, in camel case. Use this definition:
#Column(name="user_id")
private Long userId;
Then use findByUserId(Long userId) as the JPA repo method name as you were already doing. Note that the #Column annotation directs JPA/Hibernate to create the table column with the name user_id.

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.

how to map custom sql query to model to load on jsp view in spring

I am beginner in spring. I want to show SQL data to JSP view page.
This is my SQL table
create table customer(
id int primary key,
name varchar(250),
salary int,
manager_id int
)
and I am trying to show data from this query
select m.id, m.name, m.salary, n.name from customer m, customer n where n.id=m.manager_id
So basically from this query, I am trying to show ID int, name varchar, salary int, manager_name varchar.
I have create the entity java class as below
#Entity
#Table(name="customer")
public class Customer{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int id;
#Column
private String name;
#Column(name="manager_id")
private String manager;
#Column(name="salary")
private int salary;
............
............
}
This is the code of my DAO class
Session session= entityManager.unwrap(Session.class);
Query<Employee> query= session.createQuery(<above sql query need to add here?>,Customer.class);
return query.getResultList();
So the issues are,
This SQL query return the data which could not be matched to Customer Entity class. So do I need to create another Entity class for this? Is there any better way?
The above required SQL query is not able to execute. What the correct way to execute custom SQL query?
Regarding your first question: Yes there is better way. you can directly fetch the results in a projection dto class. take a at: https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/
About your second question: What Do you mean by saying the query does not execute?
Can you give us the Exception/Stacktrace? Did you try to execute the query (sql form of it) physically? Does it run then?

How to establish foreign key relationship with a non entity table in the database using Spring data JPA?

My spring boot project uses an existing database, I have a new model entity/table in my project that must have a foreign key constraint with an existing table in the database.
I've tried to find solution online but all the answers are for the case where both the tables are present as entities in that project and using some #ManyToOne, #OneToMany annotations.
I can't define those annotations because I don't have the reference table as an entity or model in my project.
Let's say I have class like:
#Entity(name = "user")
public class User {
#Id
#GeneratedValue
private long userId;
private long departmentId;
I want to put a foreign key contraint on the departmentId column to reference to id column of the existing department table that isn't defined as a model or entity in my project.
Thanks
Just do it as normal
example
#Column(name = "department_id")
private Department departmentId;
You can later access it Department.departmentId. Hope this helps.
Try it like this
#ManyToOne
#JoinColumn(name="(column name of current entity)", referencedColumnName="(column name in target entity)")
private Department departmentId;
you can skip the referencedColumnName if the column name is same in both the entities

Select self referencing table with spring data into new object

I have a self referencing employee table. An Employee reports to his immediate lead which also an Employee.
fields->
id, name, employee_type, lead_id
I have mapped this table into this class,
public Class Employee {
private Integer id;
private String name;
private Integer employeeType; // 1-manager, 2-project lead, 3-developer, etc
private List<Employee> reporters;
}
How can I load all managers with his reporters using Spring Data JPA custom mapping? (those reporting employees will have their own reporters)
Mainly, I don't know how to map the corresponding list.
#Query("SELECT new Employee(id, name, employee_type) FROM employee")
List<Employee> findAllManagers();

HQL join query: Path expected for join

I'm new to hql, I referred to a site to write hql query in Spring Framework, but it throws "Path expected for join!" exception
My query is
"from GaugeCateSelect cs inner join PreferredUrl purl on cs.survey=purl.survey where purl.uuid=:uuid"
I want to connect both table with "survey".
How can I sort it out?
Update
Two tables, names are GaugeCateSelect and PreferredUrl. The "survey" field is common for both table. uuid is in PreferredUrl. I want to get all data from GaugeCateSelect when I pass the uuid to PreferredUrl table. (In short, Pass uuid to PreferredUrl, then find the survey number from PreferredUrl and check the number with GaugeCateSelect table, if exists get all data)
Update 2
There is no primary/foreign key reference relationship between two tables. but common field survey is there
GaugeCateSelect class
class GaugeCateSelect {
private int id;
private String categoryName;
private int posNeg;
private Survey survey; //survey is in foreign key relationship of survey table
//Annotation, getters and setters were removed for easiness.
}
PreferredUrl class
public class PreferredUrl {
private int preferredUrlId;
private String uuid;
private int enabled;
private Survey survey; //survey is in foreign key relationship of survey table
//Annotation, getters and setters were removed for easiness.
}
Maybe you should check the Hibernate version you use as there is a difference when joining unrelated entities as discussed here: https://www.thoughts-on-java.org/how-to-join-unrelated-entities/

Resources