How to Join multple table in R2DBC and Spring WebFlux? - spring-boot

//1. Person Entity
class Person {
private Integer id;
private String name;
Private Address addId;
}
//2. Address Entity
class Address {
private Integer addId;
private String city;
Private String state;
Private String country;
Private Integer zip;
}
How to Join multple table in R2DBC and Spring WebFlux?

Currently R2DBC doesnt support annotation such as #OneToMany. So in Address you shuld have a property called userId of type Integer and pertsist Person and then persist Address. And to get them you should first get the Person and find the Address by the userId

Related

Want to implement Search function in springboot restapi

So i have two entity classes Employee and Address and they are in #OneToOne Relation I'm able to search a Employee's with different parameter like name,designation,department. But i want to search a employee using address fields like Areaname,pincode, phone etc.. How to implement this functionality i'm currently using JpaRepo with Mysql.
#Entity
public class Employee{
#Id#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String Name;
private String Designation;
private String Department;
#OneToOne(cascade=CascadeType.ALL)
private Address address;}
#Entity
public class Address{
private String Streetname;
private String Areaname;
private String City;
private Long pincode;
#Id
private Long phone;
}
try like this:
#Query("FROM Employee AS emp LEFT JOIN emp.address AS adr WHERE adr.areaname= ?1")
public List<Employee > FindAllEmployeeByAreaName(String areaname);

How to Inner Join using Spring Boot JPA / Hibernate in Repository?

I am currently learning spring boot , hibernate and Spring Boot JPA
I developing a Classroom App for coaching centers and institutes .
In it, students enrolled to multiple courses in a single institute
The Student Entity class :
#Entity
#Table(name = "student")
public class Student {
private String name;
private String dob;
private String gender;
private String address;
private String email;
private Integer mobile;
private String joined;
private Integer instID;
#Id
private String studentid;
getters and setters()....
}
Course Table Entity class
#Entity
#Table(name = "courses")
public class Course {
private String name;
private String description;
private String logo;
private String start;
private String end;
private Integer fee;
#Id
private String courseid;
private Integer instID;
getters and setters();
}
Enrolled Classes Table's Entity class
public class EnrolledCourses {
#Id
String enrollID;
String courseid;
String studentid;
Date joined;
getters and setters()...
}
JPA Repository
#Repository
public interface StudentRepository extends CrudRepository<Student, String> {
Student findTopByInstIDOrderByStudentidDesc(int instID);
}
#Repository
public interface CourseRepository extends CrudRepository<Course,String> {
}
#Repository
public interface EnrolledRepository extends CrudRepository<Course,String> {
}
My Need
Now I am retrieving enrolled students for a given course in a given institute... by using this MySQL query
SELECT
`enrolled_courses.enrollID`,
`student.name`, `student.studentid`
FROM `enrolled_courses`
INNER JOIN `student`
WHERE
`enrolled_courses.studentid` = `student.studentid`
AND
`student.instID` = 13
AND
`enrolled_courses.courseid` = '13I01C' ;
Now I need to implement this Inner join query in CourseRepository (or enrolledstudent repo)
How to achieve this ?
Please guide me
If we use hibernate mapping in EnrolledCourses entity like
#Entity
public class EnrolledCourses {
#Id
String enrolledId;
#ManyToOne
Student student;
#ManyToOne
Course course;
Date joined;
getters and setters()...
}
from the above mappings without using any SQL queries, you can retrieve all student who comes under a particular course
By using the method in the interface
#Repository
public interface EnrolledRepository extends CrudRepository<EnrolledCourses,String> {
List<EnrolledCourses> findByCourse_CourseId(String courseId);
}
if we have some relations between the entities we can easily retrieve all the fields using Jpa.

Reference Column throwing error in Hibernate

User entity has OneToMany mapping with UserRole entity i.e 1 user can have many Role ids .
I am getting the below error : -
Caused by: org.hibernate.cfg.RecoverableException: Unable to find
column with logical name: USER_ID in
org.hibernate.mapping.Table(t_users) and its related supertables and
secondary tables
#Entity
#Table(name="T_USERS")
public class User {
#Column(name="ID_COL")
#Id
#SequenceGenerator(name="s")
private Integer userId;
#Column(name="USER_NAME ")
private String userName;
#Column(name="USER_EMAIL")
private String userEmail;
#Column(name="PASSWORD")
private String password;
#Column(name="IS_ACTIVE")
private Integer isActive;
#OneToMany
#JoinColumns(
{
#JoinColumn(updatable=false,insertable=false, name="ID_COL", referencedColumnName="USER_ID"),
}
)
private List<UserRole> userRole ;
// removed getters n setters for brevity
}
#Entity
#Table(name="T_MAP_USER_ROLES")
public class UserRole {
#Column(name="MAP_ID")
#Id
#SequenceGenerator(name="seq_user_role")
private Integer mapId;
#Column(name="USER_ID")
private Integer userId;
#Column(name="ROLE_ID ")
private Integer roleId;
#Column(name="IS_ACTIVE")
private Integer isActive;
#OneToOne
#JoinColumns(
{
#JoinColumn(updatable=false,insertable=false, name="ROLE_ID", referencedColumnName="ROLE_ID"),
}
)
private Role role;
What is the cause of the issue and how can I resolve it?
the mapping between UserRole and Role entity is working fine
#JoinColumns is only used for composite foreign keys. In this case, you just need #JoinColumn:
#OneToMany #JoinColumn(updatable=false,insertable=false, name="ID_COL")
Also, please note that you don't need "referencedColumnName" for single column foreign keys.

Couchbase spring data jpa to generate composite primary key

Using Couchbase with Spring Data and JPA,
In my entity class How to create a Composite Key using two fields.
currently in Person class id is the primary key #Id
where I want combination of id and name will be primary key.
#Document
public class Person {
#Id
private String id;
#Field
private String name;
#Field
private String city;
I think you should be able to achieve what you want using the following -
#Document
public class Person {
#Id
#GeneratedValue()
String key;
#IdPrefix
String id;
#Field
#IdAttribute
String name;
#Field
private String city;
}
Use #IdSuffix if you want the value in id to be after the name . When constructing the above object don't assign a value to key variable yourself as the value doesn't get autogenerated if you provide one of your own as per docs - https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#couchbase.autokeygeneration.configuration .

Spring + hibernate one to one mapping

I am developing web application using spring and hibernate. I am using one to one mapping between two tables employee and PersonelDetails.
below are my bean classes
=======================Employee=====================================
#Entity
#Table(name="employee")
public class Employee {
#Id
#Column
#GeneratedValue
private int empid;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
#Column
private String password;
#Column
private boolean isAdmin;
#Column
private boolean isActive;
#Column
private boolean isLocked;
//getter setters
====================PersonalDetails class====================
#Entity
#Table(name="PersonalDetails")
public class PersonalDetails {
#Column
#Id
private int empid;
#Column
private String personalEmail;
#Column
private String mob;
#Column
private String permenantAdress;
#Column
private String currentAddress;
#Column
private String gender;
#Column
private String maritialStatus;
#MapsId
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "empid", referencedColumnName = "empid")
#ForeignKey(name="empid")
private Employee employee;
//getter setters
In my application table employee is filled by Admin user while creating new employee after that employyee himself fill personalDetails table by login to his accountCreated by Admin)
Now when I try to send personal details bean to hibernate layer first I have to get the employee bean from employee table then call setEmployee method over personalDetails class and save employee bean in personalDetails and send to hibernate layer for saving in database.
So while getting employee bean from database and again send back through personalDetails bean leads to a performance issue.
Can anyone help here to clarify while saving data in child table(PersonalDetails) is it really mandatory to pass parent object(Employee) ?
=======================code to store personalDetails===============
#RequestMapping(value="addpersonal")
public ModelAndView addPersonalDetails(#ModelAttribute("personalDetails") PersonalDetails personalDetails) {
//personalDetails.setEmpid(1);
personalDetails.setCurrentAddress("niljyoti");
personalDetails.setMob("9405715872");
personalDetails.setPermenantAdress("address");
Employee e = empService.getEmployeebyUserName(uname);
personalDetails.setEmployee(e);
personalDetailsService.addPersonalDetails(personalDetails);
return new ModelAndView("home");
}
On read:
You can change fetch strategy if you are worried.
Based od JPA spec, default fetch type for #OneToOne is EAGER.
By setting fetch = FetchType.LAZY, instead of real PersonalDetails object, an object of a subclass behaving as a proxy is returned. Hence, selecting from employee table starts only after getEmployee is called.
On write:
You need to specify connection between entities, in your model, the only way is the employee field. However, you can specify mappedBy, see answer to this question:
Java: Hibernate #OneToOne mapping

Resources