How to get data from another table - spring-boot

#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
}

Related

One to one bi direction mapping is not working

My code contains two entities, that have relation with each other.
Student Class :
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "student_detail_id")
private StudentDetail studentDetail;
public Student() {}
//getters setters
StudentDetail Class :
#Entity
#Table(name = "student_detail")
public class StudentDetail {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "college")
private String college;
#Column(name = "no_of_problems_solved")
private int noOfProblemsSolved;
public StudentDetail() {}
#Column(name = "college")
private String college;
#Column(name = "no_of_problems_solved")
private int noOfProblemsSolved;
public StudentDetail() {}
Why is the one to one bi direction mapping not working?
In Student_Detail you have to specify #OntToOne Annotation also.
#Entity
#Table(name = "student_detail")
public class StudentDetail {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "college")
private String college;
#Column(name = "no_of_problems_solved")
private int noOfProblemsSolved;
#OneToOne(mappedBy = "studentDetail", cascade = CascadeType.ALL)
private Student student;
//Getters setters
}
This should work for you.

Hibernate Enver - Listening for only one change in referenced class

I have an entity as shown below that I am auditing using Hibernate Enver
#Entity
#Table(name = "watch_item")
#Audited
public class WatchItemEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Type(type = "uuid-char")
#Column(name = "watch_item_id", columnDefinition = "VARCHAR(36)")
private UUID watchItemId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "watch_model_id")
private WatchModelEntity watchModel;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "private_user_id")
private PrivateUserEntity privateUser;
private String serialNumber;
private Integer productionYear;
private String generalCondition;
private Boolean isMovementFullyFunctional;
private Boolean isInOriginalCondition;
private String comment;
private Boolean isProofOfPurchaseAvailable;
private String country;
private Boolean isCustomsDeclared;
private Boolean hasPaper;
private Boolean hasBox;
private String otherAccessories;
#CreatedDate private LocalDateTime createdDate;
#LastModifiedDate private LocalDateTime modifiedDate;
private String lastServiceProvider;
private LocalDate lastServiceDate;
private BigDecimal lastServiceCost;
private BigDecimal purchasedPrice;
private LocalDate purchasedOn;
...
}
As you can see, it has a PrivateUserEntity field. I want Hibernate Envers to record a change when the privateUser changes (and not record changes in PrivateUserEntity that correspond to the privateUser). However, I don't want to create a Private_User_Aud table. To give some context, a WatchItem can only be owned by one PrivateUser and hence, when the PrivateUser field changes, that means that the WatchItem's owner changed. The entity can be seen below
#Entity
#Table(name = "private_user")
public class PrivateUserEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Type(type = "uuid-char")
#Column(name = "private_user_id", columnDefinition = "VARCHAR(36)")
private UUID privateUserId;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private UserEntity user;
#LastModifiedDate private LocalDate modifiedDate;
private String title;
private String firstName;
private String lastName;
private String phone;
private LocalDate dateOfBirth;
private String email;
private String gender;
private String nationality;
private String residencyPermitType;
private LocalDate residencyPermitValidSince;
private String preferredLanguage;
...
}
Is this possible? And if so, how?
You can disable audit for it, doesn't work?
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "private_user_id")
#NotAudited
private PrivateUserEntity privateUser;

Error creating bean with name 'jpaMappingContext': Invocation of init method failed;

Click Link for pic
Please help I am stuck in error after error
Need to create a spring data model and pass the test case
Spring data models are
#Entity
public class Cart {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer cartId;
private Double totalAmount;
#OneToOne
#JoinColumn(name = "userId")
private User user;
#OneToMany(mappedBy = "cart")
private List<CartProduct> cartProducts;
//getter and setter and constructor
}
#Entity
public class CartProduct {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer cpId;
#ManyToOne
#JoinColumn(name = "cartId")
private Cart cart;
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
private Integer quantity = 1;
//getter and setter and constructor
}
#Entity
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer categoryId;
private String categoryName;
//getter and setter and constructor
}
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer productId;
private String productName;
private Double price;
#ManyToOne
#JoinColumn(name ="userId")
private User seller;
#ManyToOne
#JoinColumn(name ="userId")
private Category category;
//getter and setter and constructor
}
The main issue is role and user can't able to create
many-to-many relations
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Integer roleId;
String role;
#ManyToMany(mappedBy = "roles")
Set<User> users = new HashSet<>();
//getter setter and constructor
}
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;
private String username;
private String password;
// Implement Roles
#ManyToMany
#JoinTable(name="user_Role",joinColumns = #JoinColumn(name="userId")
,inverseJoinColumns = #JoinColumn(name="roleId"))
private Set<Role> roles = new HashSet<Role>();
}
https://pastebin.com/T34SbwMy
the test case is in the link and can't able to pass the test case.
Thanks in advance.

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;
}

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

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

Resources