How to get Field Variable on Java Spring - java

I has a issue on my learn project, on case "if condition value is null and then else if condition value field is null" for example my code following these code :
For Entity Users.java :
#Entity
public class Users {
private Long id;
private String employeeId;
private String fullName;
private String username;
private String password;
...
public Users() {
}
Some Code Setter and Getter....
}
For Entity Employee.java :
#Entity
public Class Employee {
private Long id;
private String employeeId;
private String fullName;
...
public Employee() {
}
Some Code Setter and Getter....
}
and then for my Class Service i have case for insert data Employee with Repository. On case we have validation data before insert data to table Employee, we need to check table users not null and then on field employeeId should null. with my code following this :
For Repository UserRepo.java and EmployeeRepo.java :
#Repository
public interface EmployeeRepo extends CrudRepository<Employee, Long> {
}
#Repository
public interdace UsersRepo extends CrudRepository<Users, Long> {
#Transactional
#Modifying(clearAutomatically = true, flushAutomatically = true)
#Query("UPDATE Users u SET u.employeeId = :employeeId WHERE u.id = :id")
public void updateEmployeeIdUsers(#Param("id") Long id, #Param("employeeId") String employeeId);
}
For Service UsersService.java :
#Service("usersService")
public class UsersService {
#Autowired
private UsersRepo repo;
public Optional<Users> findById(Long id) {
return repo.findById(id);
}
public void updateEmployeeIdUsers(Long id, String employeeId) {
repo.updateEmployeeIdUsers(id, employeeId);
}
}
For Service EmployeeService.java :
#Service("employeeService")
public class EmployeeService {
#Autowired
private EmployeeRepo employeeRepo;
#Autowired
private UsersService userService;
public Employee insertEmployee(Employee employee) throws Exception {
Optional<Users> users = userService.findById(employee.getId());
Users userOptional = new Users(); **//on this my problem**
userOptional.getEmployeeId(); **//on this my problem**
if (!users.isPresent()) {
throw new Exception("User ID : "+ employee.getId() +" Not Founded");
}else if (!(userOptional == null)) { **//on this my problem**
throw new Exception("User employeID : "+ employee.getEmployeeId() +" Already Exist on Users");
}
String str1 = "TEST";
Long idUser = employee.getId();
userService.updateEmployeeIdUsers(idUser, str1);
return employeeRepo.save(employee);
}
}
on this code we have problem on else if userOptional is always NULL and i try to debug to see value on employeeId just i see always Null. so any idea with my problem because i try some case alway fail with my issue. please if any idea for my issue, can reply these my question. is very thank you of all about thing to answer my question.

For the proposed solution, I will assume the following:
There is relation between Employee and Users.
An Employee can be related with only one Users
username is the natural key of Users
employeeId is the natural key of Employee
So the entities:
#Entity
public class Users {
#Id
// This one is an example, you can use the configuration you need
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator= "users_seq")
#SequenceGenerator(name="users_seq", initialValue=1, allocationSize=1, sequenceName = "users_id_seq")
private Long id;
#Column(name = "fullname")
private String fullName;
// Probably this column should be unique and you need to configure in that way here and in your database
#Column
private String username;
#Column
private String password;
// Getter & setter & constructors
}
#Entity
public class Employee {
#Id
// This one is an example, you can use the configuration you need
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator= "employee_seq")
#SequenceGenerator(name="employee_seq", initialValue=1, allocationSize=1, sequenceName = "employee_id_seq")
private Long id;
/**
* Assuming this is your specific identifier for an employee (not related with database PK)
* If the assumption is correct, this column should be unique and you need to configure in
* that way here and in your database
*/
#Column(name = "employeeid")
private String employeeId;
/**
* Not sure if this relation could be nullable or not
*/
#OneToOne
#JoinColumn(name = "users_id")
private Users users;
// Getter & setter & constructors
}
As you can see, there are no "repeated columns" in both entities and there is an unidirectional OneToOne relation between Employee and Users. If you need a bidirectional one, this link will help you with it: Bidirectional OneToOne
The repositories:
#Repository
public interface UsersRepository extends CrudRepository<Users, Long> {
Optional<Users> findByUsername(String username);
}
#Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
Optional<Employee> findByEmployeeId(String employeeId);
}
The services:
#Service
public class UsersService {
#Autowired
private UsersRepository repository;
public Optional<Users> findByUsername(String username) {
return Optional.ofNullable(username)
.flatMap(repository::findByUsername);
}
public Optional<Users> save(Users user) {
return Optional.ofNullable(user)
.map(repository::save);
}
}
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository repository;
#Autowired
private UsersService usersService;
public Optional<Employee> insert(Employee newEmployee) {
/**
* The next line don't make sense:
*
* Optional<Users> users = userService.findById(employee.getId());
*
* I mean:
*
* 1. Usually, id column is configured with #GeneratedValue and manage by database. So you don't need to ask
* if that value exists or not in Users.
*
* 2. Even if you are including id's values manually in both entities what should be "asked" is:
*
* 2.1 Is there any Users in database with the same username than newEmployee.users.username
* 2.2 Is there any Employee in database with the same employeeId
*
* Both ones, are the natural keys of your entities (and tables in database).
*/
return Optional.ofNullable(newEmployee)
.filter(newEmp -> null != newEmp.getUsers())
.map(newEmp -> {
isNewEmployeeValid(newEmp);
// Required because newEmp.getUsers() is a new entity (taking into account the OneToOne relation)
usersService.save(newEmp.getUsers());
repository.save(newEmp);
return newEmp;
});
}
private void isNewEmployeeValid(Employee newEmployee) {
if (usersService.findByUsername(newEmployee.getUsers().getUsername()).isPresent()) {
throw new RuntimeException("Username: "+ newEmployee.getUsers().getUsername() +" exists in database");
}
if (repository.findByEmployeeId(newEmployee.getEmployeeId()).isPresent()) {
throw new RuntimeException("EmployeeId: "+ newEmployee.getEmployeeId() +" exists in database");
}
}
}

After read comments I already understand your problem.
Users users = userService.findById(employee.getId()).orElseThrow(() -> new Exception("User ID : "+ employee.getId() +" Not Founded"));
And now you can get your employeeId from users from returned userService.findById(employee.getId());
Example:
String employeeId = users.getEmployeeId(); // reference to your code
But in this case in my opinion you should make relation #OneToOne between users and employee or extend users in employee class.
One-To-One relation in JPA,
hibernate-inheritance

Related

How to map relationship while testing spring data jpa

Issue
I'm writing test code for a simple service layer using jpa data entity, but entity's relationship doesn't seem to work properly.
I googled but couldn't find an answer. I'm not sure what's wrong.
Please check the code below
Codes
(0) test property
spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false;MODE=MySQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
(1) entities
#Entity
#Getter
#Setter
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;
private String username;
private String password;
#OneToMany(mappedBy = "user")
private List<Authority> authList;
public Set<String> getAuthName() {
if (this.authList == null || this.authList.isEmpty()) return null;
Set<String> authNameSet = new HashSet<>();
authList.forEach(e -> authNameSet.add(e.getStringName()));
return authNameSet;
}
}
//----------
#Entity
#Getter
#Setter
#Table(name = "authorities")
public class Authority implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#Enumerated(EnumType.STRING)
#Column(length = 10)
private AuthorityName name;
}
(2) repositories
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByUsername(String username);
Optional<User> findByEmail(String email);
}
//----------
#Repository
public interface AuthorityRepository extends CrudRepository<Authority, Long> {
List<Authority> findByUser(User user);
}
(3) service layer to test
#Service
public class AuthorityService {
// this is the method i want to test
public boolean isUserHaveAuthorityOf(User user, AuthorityName authOf) {
if (user == null || authOf == null) throw new InternalError("msg");
if (user.getAuthName() == null) return false;
return user.getAuthName().contains(authOf.name());
}
}
(4) test code
import static org.junit.jupiter.api.Assertions.*;
#TestPropertySource("/application-test.properties")
#SpringBootTest
#Transactional
class AuthorityServiceTest {
#Autowired private UserRepository userRepository;
#Autowired private AuthorityRepository authorityRepository;
#Autowired private AuthorityService authorityService;
private User sampleUser;
#BeforeEach
void setupDB() {
User user = new User();
user.setId(1);
user.setUsername("name");
user.setPassword("passwd");
user.setEmail("email#dot.com");
user.setBirth("20000101");
user.setAddress("addr");
user.setAddressDetail("addrDetail");
user.setZipCode("12345");
user.setDeleted(false);
user.setDisabled(false);
user.setBlock(false);
userRepository.save(user);
sampleUser = user;
}
#Test
void testIsUserHaveAuthorityOfNormalCase() {
assertFalse(authorityService.isUserHaveAuthorityOf(sampleUser, AuthorityName.USER));
assertFalse(authorityService.isUserHaveAuthorityOf(sampleUser, AuthorityName.ADMIN));
Authority auth = new Authority();
auth.setUser(sampleUser);
auth.setName(AuthorityName.USER);
authorityRepository.save(auth);
assertNotNull(sampleUser.getAuthName()); // it is null!
// I thought it was because of a caching, so I get a new user from the db.
User flushedUser = userRepository.findById(sampleUser.getId()).get();
assertNotNull(flushedUser.getAuthName()); // but still null
}
#AfterEach
void cleanDB() {
authorityRepository.deleteAll();
userRepository.deleteAll();
}
}
Thank you
You have a bidirectional relationship between User and Authority so you should keep the relationship in sync. As well as setting the User in an Authority you should also add the Authority to the the User
public void addAuthority(Authority authority) {
if (authList == null) {
authList = new ArrayList<>();
}
authList.add(authority);
authority.setUser(this);
}
It would also be helpful to see how you are persisting the sampleUser

Spring MVC Transactional in dao service and controller layers

I'm using Spring MVC with Spring data.
Simple example of my problem:
My dao Service class:
#Service
#AllArgsConstructor
#Transactional
public class FooService{
private FooRepository fooRepo;
public Foo save(Foo foo){
return fooRepo.save(foo);
}
}
and controller:
#Controller
#AllArgsConstructor
#Transactional //if I remove this, method add does not save a foo.
//But I don't understand why, because FooService already has #Transactional annotation
public class FooController{
private FooService fooService;
#PostMapping("/add")
public String add(#RequestParam("programName") String programName, #RequestParam("id") long id){
Foo foo = fooService.findById(id).get();
foo.setProgramName(programName);
fooService.save(foo);
return "somePage";
}
}
If I remove #Transaction annotation from controller class, method save will not update foo object.
And I don't understand why I should mark controller by #Transactional annotation if I already mark service class by this annotation?
############ UPDATE ####################
Simple detailed description:
I have Program and Education entities. One Program has many Education, Education entity has foreign key program_id.
There is a page with Program form, there are fields: program id, program theme,..., and field with a list of education id separated by commas.
I'm trying to update the education list at the program, so I add a new education id at the page form and click save. Through debugger I see, that new education has appeared in the program, but changes do not appear in the database.
#Controller
#RequestMapping("/admin/program")
#AllArgsConstructor //this is lombok, all services autowired by lombok with through constructor parameters
#Transactional//if I remove this, method add does not save a foo.
//But I don't understand why, because FooService already has #Transactional annotation
public class AdminProgramController {
private final ProgramService programService;
private final EducationService educationService;
#PostMapping("/add")
public String add(#RequestParam("themeName") String themeName, #RequestParam("orderIndex") int orderIndex,
#RequestParam(value = "educationList", defaultValue = "") String educationList,
#RequestParam(value = "practicalTestId") long practicalTestId){
saveProgram(themeName, orderIndex, educationList, practicalTestId);
return "adminProgramAdd";
private Program saveProgram(long programId, String themeName, int orderIndex, String educationList, long practicalTestId){
List<Long> longEducationList = Util.longParseEducationList(parsedEducationList); //this is list of Education id separeted by commas that I load from page form
//creating new program and set data from page form
Program program = new Program();
program.setId(programId);
program.setThemeName(themeName);
program.setOrderIndex(orderIndex);
//starting loop by education id list
longEducationList.stream()
.map(educationRepo::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(edu->{
//linking program and education
program.getEducationList().add(edu);
edu.setProgram(program);
});
//saving new program or updating by service if there is one already
Program savedProgram = programService.save(program);
//saving education with updated program
for(Education edu : savedProgram.getEducationList())
{
educationService.save(edu);
}
return savedProgram;
}
}
ProgramService:
#Service
#AllArgsConstructor //this is lombok, all services autowired by lombok with throught constructor parameters
#Transactional
public class ProgramService {
private ProgramRepo programRepo;
//other code here.....
public Program save(Program program) {
Optional<Program> programOpt = programRepo.findById(program.getId());
//checking if the program is already exist, then update it paramateres
if(programOpt.isPresent()){
Program prgm = programOpt.get();
prgm.setThemeName(program.getThemeName());
prgm.setOrderIndex(program.getOrderIndex());
prgm.setPracticalTest(program.getPracticalTest());
prgm.setEducationList(program.getEducationList());
return programRepo.save(prgm);
}
//if not exist then just save new program
else{
return programRepo.save(program);
}
}
}
Education service
#Service
#AllArgsConstructor //this is lombok, all services autowired by lombok with throught constructor parameters
#Transactional
public class EducationService {
private EducationRepo educationRepo;
//other code here....
public Education save(Education education){
return educationRepo.save(education);
}
}
Program entity:
#Entity
#ToString(exclude = {"myUserList", "educationList", "practicalTest"})
#Getter
#Setter
#NoArgsConstructor
public class Program implements Comparable<Program>{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "theme_name")
private String themeName;
#Column(name = "order_index")
private int orderIndex; //from 1 to infinity
#OneToMany(mappedBy = "program", fetch = FetchType.LAZY)
#OrderBy("orderIndex asc")
private List<Education> educationList = new ArrayList<>();
#OneToMany(mappedBy = "program", fetch = FetchType.LAZY)
private List<MyUser> myUserList = new ArrayList<>();
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "test_id")
private PracticalTest practicalTest;
public Program(int orderIndex, String themeName) {
this.orderIndex = orderIndex;
this.themeName = themeName;
}
public Program(long id) {
this.id = id;
}
//other code here....
}
Education entity:
#Entity
#ToString(exclude = {"program", "myUserList"})
#Getter
#Setter
#NoArgsConstructor
public class Education implements Comparable<Education>{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String link;
#Column(name = "order_index")
private int orderIndex;
private String type;
private String task;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "program_id")
private Program program;
#OneToMany(mappedBy = "education", fetch = FetchType.LAZY)
private List<MyUser> myUserList = new ArrayList<>();
public Education(String link, int orderIndex, String task, Program program) {
this.link = link;
this.orderIndex = orderIndex;
this.task = task;
this.program = program;
}
//other code here....
}
Program repo:
#Repository
public interface ProgramRepo extends CrudRepository<Program, Long> {
Optional<Program> findByPracticalTest(PracticalTest practicalTest);
Optional<Program> findByOrderIndex(int orderIndex);
List<Program> findByIdBetween(long start, long end);
}
Education repo:
#Repository
public interface EducationRepo extends CrudRepository<Education, Long> {
Optional<Education> findByProgramAndOrderIndex(Program program, int orderIndex);
#Query("select MAX(e.orderIndex) from Education e where e.program.id = ?1")
int findLastEducationIndexByProgramId(long programId);
}
I think the problem is program object created in one transaction and saved in another. That's why if I put Transactional on controller it works. There are two ways to solve the problem:
Without transactional on the controller: then I must save education object at first, because it has program id field and then save the program object.
With transactional on controller: then saving order has no matter, because saving object occurs in one transaction

how to find the data by an attribute (name_techno) in jpql

I am developing an application that allows managing candidates in a company, for that I use spring-boot, in order to select the employees who master such a technology (Techno) I used a request JPQL.
So, How can I find a candidate by techno?
In my project I used this code:
1 - the class candidat.java
#Entity
public class Candidat {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "candidat_id")
private int id;
private String nom;
private String prenom;
private String ville;
private int numTel;
private String mail;
private String pseudo;
private String roleCible;
private String typeContrat;
private String villeRecherchee;
#OneToMany(mappedBy="candidat")
private List<Techno> techno;
#Temporal(TemporalType.DATE)
private Date date;
#OneToMany
private List<SecteurActivites> secteurActivites;
public Candidat() {
// TODO Auto-generated constructor stub
}
2- the class Techno.java
#Entity
public class Techno {
#Id
#GeneratedValue
#Column(name = "techno_id")
private int id ;
private String nomTechno;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "candidat_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private Candidat candidat;
public Techno() {
// TODO Auto-generated constructor stub
}
/**
* #param nomTechno
* #param candidat
*/
public Techno(String nomTechno, Candidat candidat) {
super();
this.nomTechno = nomTechno;
this.candidat = candidat;
}
3- My CandidatController
#GetMapping(value = "/GetAllCandidats/{nomTechno}")
public List<Candidat> afficherCandidat(#PathVariable ("nomTechno") String nomTechno){
return candidatdao.findByTechno(nomTechno);
}
4- the repository:
#Repository
public interface CandidatDao extends JpaRepository <Candidat, String>{
List<Candidat> findByDate(Date date);
#Query("SELECT DISTINCT e FROM Candidat e INNER JOIN e.Techno t")
List<Candidat> findByTechno(String nomTechno);
}
5- app.properties
server.port= 9090
spring.jpa.show-sql = true
spring.datasource.url= jdbc:mysql://localhost:3306/database
spring.datasource.username=??
spring.datasource.password=??
spring.jpa.hibernate.ddl-auto=update
The result in console is:
"Validation failed for query for method public abstract java.util.List com.avatar.dao.CandidatDao.findByTechno(java.lang.String)!"
You can declare the following method into your JpaRepository (also remove the #Query, it is not needed).
List<Candidat> findDistinctByTechnoNomTechno(String nomTechno);
Also in Techno.java you should add the #Column annotation and map it with the DB schema.
I am not sure if you have pasted incomplete code of your entities on purpose. If not your entities are not correct. You should create setters/getters as the following
private String nomTechno;
#Column(name = "NOM_TECHNO")
public String getNomTechno() {
return nomTechno;
}
public void setNomTechno(String nomTechno){
this.nomTechno = nomTechno;
}
Do the above for all variables in your entities.
You do not need to add explicit #Query for this, Spring data can formulate a query if you have right method names
Instead of
#Query("SELECT DISTINCT e FROM Candidat e INNER JOIN e.Techno t")
List<Candidat> findByTechno(String nomTechno);
Try this
List<Candidat> findDistinctByTechno_NomTechno(String nomTechno);

Springdata JPA repository findAllByXXX() return null instead of an empty list

I'm using springboot 2.1.2 and I encounter some problems with repository.
Here are my entity classes:
#Entity
#Getter
#Setter
#NoArgsConstructor
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue
private long id;
#ManyToOne(targetEntity = User.class)
private User user;
//other fields and getters and setters are ignored
}
#Entity
#Getter
#Setter
#NoArgsConstructor
public class User {
#Id
private String email;
//other fields and getters and setters are ignored
}
And my OrderRepository:
#Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
#Query("select o from Order o where o.user.email = ?1")
List<Order> findAllByUserId(String userId);
List<Order> findAllByUser(User user);
}
When I invoke findAllByUserId or findAllByUser, the repository returns a null value instead of an empty list, this is so strange since I'm sure that my database has data.
I've read other similar questions, and they don't seem to help.
I try to fix the problem with debugger, and I track into the AsyncExecutionInterceptor class:
#Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
Class<?> targetClass = invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null;
Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
AsyncTaskExecutor executor = this.determineAsyncExecutor(userDeclaredMethod);
if (executor == null) {
throw new IllegalStateException("No executor specified and no default executor set on AsyncExecutionInterceptor either");
} else {
Callable<Object> task = () -> {
try {
Object result = invocation.proceed();
if (result instanceof Future) {
return ((Future)result).get();
}
} catch (ExecutionException var4) {
this.handleError(var4.getCause(), userDeclaredMethod, invocation.getArguments());
} catch (Throwable var5) {
this.handleError(var5, userDeclaredMethod, invocation.getArguments());
}
return null;
};
return this.doSubmit(task, executor, invocation.getMethod().getReturnType());
}
}
And I notice that in the 13rd line of this method, the variable result is the List with proper Order objects, but the if clause fails and thus return a null value.
So does anyone know how to solve the problem?
===========================================================
To make it more clear, I'll show my db schema:
and here are the sql generated by the Hibernate:
Hibernate: select order0_.id as id1_8_, order0_.address_id as address_6_8_, order0_.date as date2_8_, order0_.deliver_time as deliver_3_8_, order0_.restaurant_id as restaura7_8_, order0_.status as status4_8_, order0_.total as total5_8_, order0_.user_email as user_ema8_8_ from orders order0_ where order0_.user_email=?
Hibernate: select address0_.id as id1_1_0_, address0_.location as location2_1_0_, address0_.name as name3_1_0_, address0_.phone as phone4_1_0_, address0_.user_email as user_ema5_1_0_, user1_.email as email1_14_1_, user1_.password as password2_14_1_, user1_.pts as pts3_14_1_, user1_.status as status4_14_1_, user1_.user_name as user_nam5_14_1_ from address address0_ left outer join user user1_ on address0_.user_email=user1_.email where address0_.id=?
Hibernate: select restaurant0_.id as id1_9_0_, restaurant0_.email as email2_9_0_, restaurant0_.location as location3_9_0_, restaurant0_.name as name4_9_0_, restaurant0_.password as password5_9_0_, restaurant0_.phone as phone6_9_0_, restaurant0_.status as status7_9_0_, restaurant0_.type as type8_9_0_, restaurant0_.vcode as vcode9_9_0_ from restaurant restaurant0_ where restaurant0_.id=?
Hibernate: select address0_.id as id1_1_0_, address0_.location as location2_1_0_, address0_.name as name3_1_0_, address0_.phone as phone4_1_0_, address0_.user_email as user_ema5_1_0_, user1_.email as email1_14_1_, user1_.password as password2_14_1_, user1_.pts as pts3_14_1_, user1_.status as status4_14_1_, user1_.user_name as user_nam5_14_1_ from address address0_ left outer join user user1_ on address0_.user_email=user1_.email where address0_.id=?
Your code is ambiguous. if you want to get order list by email then just write like below. There is no need of #Query
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findAllByUserEmail(String email);
}
and entity class like below
I'm using springboot 2.1.2 and I encounter some problems with repository. Here are my entity classes:
#Entity
#Getter
#Setter
#NoArgsConstructor
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue
private Long id;
#ManyToOne(targetEntity = User.class)
private User user;
//other fields and getters and setters are ignored
}
#Entity
#Getter
#Setter
#NoArgsConstructor
public class User {
#Id
private Long userId;
private String email;
//other fields and getters and setters are ignored
}
The following method signature in your OrderRepository interface should work:
List<Order> findByUser_UserEmail(String email);
Also, you can add the next one:
#Query("select o from Order o join User u where u.email = :email") List<Order> findAllByUserEmail(String email);
UPDATE
Try to query all entities, trying executing findAll from repository, if it is also null, you have some problem in codebase or configuration.
Try to update your class map definition:
public class Order {
#ManyToOne
#JoinColumn(name="user_email")
private User user;
}
public class User {
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Order> orders;
}

Spring : How to delete entry from junction table?

I have a junction table of user_id and favorite_property_id And now I want to delete the favorite property of the user , I tried the following method in repository but its not working , Does anybody have any idea that how can i delete he entry from junction table?
User.java
#Entity
public class User implements Serializable, UserGetters {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToMany(fetch = FetchType.EAGER)
private Set<Property> favouriteProperty;
public Set<Property> getFavouriteProperty() {
return favouriteProperty;
}
public void setFavouriteProperty(Set<Property> favouriteProperty) {
this.favouriteProperty = favouriteProperty;
}
}
UserRepository
public interface UserRepository extends JpaRepository<User, Long> {
//#Transactional
// Long deleteByFavouritePropertyId(#Param("favoriteProperty") Long favoriteProperty);
// #Query("delete favouriteProperty from user u where u.favouriteProperty.id=:favouriteProperty")
// void unmarkFavouriteProperty(#Param("favouriteProperty") Long favouriteProperty);
}
You can do it like:
1. Load user object
User user = userRepository.findOne(userId);
2. Remove required object from list
user.getFavouriteProperty().remove(id);
3. Save User Object
userRepository.save(user);
Try using :
Query query = session.createQuery("delete Category where id = :favorite_property_id ");
query.setParameter("favorite_property_id ", new Long(favoriteProperty));
int result = query.executeUpdate();
in your repository file. It will work fine.
This was so simple :P
I can delete by using following API
API : http://localhost:8555/api/users/2/favouriteProperty/3
METHOD : DELETE

Categories

Resources