Jpa-Jpql Query to Select All field from parent Entity and specific field from child Entity in OneToOneMapping - spring-boot

I have oneToOne RelationShip between Employee and student entity i want to fetch all field from Employee Entity and name and modelNumber From Laptop Entity
Employee Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "employee_name")
private String name;
#Column(name = "date_of_birth")
private String dob;
#Column(name = "gender")
private char gender;
#Column(name = "skills")
private String[] skills;
#OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name = "laptop_id")
private Laptop laptop;
//getter setter
Laptop Entity
#Entity
public class Laptop {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String ram;
private String modelNumber;
private String processor;
//getter Setter

select e.id, e.name, e.dob, e.gender, e.skills,
e.laptop.name, e.laptop.modelNumber
from Employee e
Please start by reading the docs: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#hql

Related

Lazy loading is not working in OnetoMany Jpa relations

Below are my entity classes Instructor and Courses having OnetoMany Relations, where all CRUD Operation is working but while fetching Instructor I don't want courses to be fetched. But when I execute GET instructor By Id, It also fetches courses in Postman. This should be avoided.
public class Instructor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
private String firstName;
private String lastName;
private String email;
#OneToMany(mappedBy = "instructor", cascade = {CascadeType.ALL})
#JsonManagedReference
private List < Course > courses;
}
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
#ManyToOne(fetch =FetchType.LAZY)
#JoinColumn(name = "instructor_id")
#JsonBackReference
private Instructor instructor;
}

How to get data from another table

#Entity
#Table(name="driver_duties")
public class Duties{
private String driverId;
private String hubName;
private String vehicleNumber;
// with getter and setters
}
another table
#Entity
#Table(name="driver_info")
public class Info{
private String driverId;
private String firstName;
private String lastName;
// with getter and setters
}
I want to get firstName and lastName in table driver_duties on the basis of driverId how can I get this. I am new to JPA I have tried #OnetoOne but not able to implement.
Add Duties as a data memeber in the class info
#Entity
#Table(name="driver_info")
public class Info{
private String driverId;
private String firstName;
private String lastName;
private Duties duties;
// with getter and setters
}
Ideally you need the following config, you should use an id attribute for every entity,
#Entity
#Table(name="driver_duties")
public class Duties{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String id;
#Column(name = "hubName")
private String hubName;
#Column(name = "vehicleNumber")
private String vehicleNumber;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "duty_id")
private Info info;
// with getter and setters
}
#Entity
#Table(name="driver_info")
public class Info{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#OneToOne(mappedBy = "info", cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private Duties duties;
// with getter and setters
}

SQL Joining tables Using Spring JPA

I have some trouble with joining tables using Spring Boot JPA
I need to do this kind of joining:
**book2user — book to user
id INT NOT NULL AUTO_INCREMENT
time DATETIME NOT NULL
type_id INT NOT NULL
book_id INT NOT NULL
user_id INT NOT NULL**
Here are my Entity classes:
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String hash;
private Date reg_time;
private Integer balance = 0;
private String name;
// getters and setters
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name = "author_id", referencedColumnName = "id")
private Author author;
#ManyToOne
#JoinColumn(name = "genre_id", referencedColumnName = "id")
private Genre genre;
private String title;
private String slug;
private String description;
private String priceOld;
private String price;
private String image;
private boolean is_bestseller;
private Date pub_date;
// getters and setters
In order to do this kind of joining I should create another entity class ??
Something like this should work:
#Entity
#Table("book2user")
public class Book2User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private LocalDateTime time;
private Integer typeId;
#OneToOne
private Book book;
#OneToOne
#JoinColumn(name = "user_id") //optional, if the name of the table and field matches.
private User user;
}

Insert in child and parent JSON Spring Boot

I have 3 entities in my spring boot App data rest, Appusers, Teacher, and Student
Appusers
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name= "appuserId", updatable=false)
private Long appuserId;
#Column(name = "username")
private String username;
#Column(name = "fullname")
private String fullName;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#OneToOne(mappedBy = "appuser")
private Teacher teacher;
#OneToOne(mappedBy = "appuser")
private Student student;
Teacher
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "teacherId" , updatable = false)
private Long teacherId;
#Column(name= "firstname")
private String firstName;
#Column(name = "lastname")
private String lastName;
#Column(name="designation")
private String designation;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "appuserId", nullable = true)
private Appuser appuser;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval=true ,mappedBy="teacher")
#JsonIgnore
private List<Course> courses;
Student
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name= "studentId", updatable=false)
private Long studentId;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "enrolledSince")
private String enrolledSince;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "appuserId", nullable = false)
private Appuser appuser;
#OneToMany(cascade = CascadeType.ALL,orphanRemoval=true, mappedBy="student")
#JsonIgnore
private List<CourseStudent> courseStudents;
i can insert in appusers table using json format in postman and it goes well. but when i try to insert in teacher or student table the result in appusers is null. it shouldnt be null because teacher and student foreign key to appusers.
This should not happen. When you save a teacher or a student you should specify appuser which is already in the database. And use appuserId instead Appuser, which is quite enough to identify to which appuser it belongs.
You can get your appuser after you save a teacher or a student and do request with join to the database.
when you try to insert in teacher or student table, please make sure that you are setting the value to appuser while persisting.
Student std =new Student();
// create an object of appuser,set its vaue and assign it to student object
Appuser ap = new Appuser();
// assigning values to the appuser object as ap.setfullname="...";... so on
std.setAppuser=ap;
now persist this student object the entries will be reflected in the mapped table
or you can set the id of appuser in std object that is already persisted .

SQL error or missing database / OneToMany SQLIte-Spring Boot

I have a problem with the relationship oneToMany. I created tables in SQLite DB, this is my tables:
My CategoryModel:
#Entity
#Table(name = "Category")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CategoryModel {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String category_name;
private String category_description;
private String image_path;
#JsonIgnore
#OneToMany( mappedBy = "category")
private Set<ProductModel> category;
My ProducCategory:
#Entity
#Table(name = "Product_Category")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class ProductModel {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long product_id;
private Long category_id;
private String name;
private String description;
private int numberOfProduct;
private String image;
private int price;
#ManyToOne
#JoinColumn(name = "country_id", nullable = false)
private CategoryModel category;
I can get data from the Category table well but when I call data from the Product_Category table I have the error:
SQL error or missing database (no such column: productmod0_.country_id)
country_id does not exist anywhere in your tables.
What you want is : #JoinColumn(name = "category_id", nullable = false)

Resources