I have two tables: users and userdetails as follows:
package com.example.easynotes.model;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "users")
#IdClass(UserID.class)
public class User implements Serializable {
#Id
int id;
#Id
String name;
String department;
//getters and setters
}
The userdetails classes will be this:
public class UserDetails implements Serializable{
int id;
String name;
String address;
String otherFields;
//getters and setters
}
id and name in users is a composite primary and I want the same fields in userdetails to be the foreign key. How can I achieve this in hibernate ?
We need to put both key in #Embeddable to detach compound key thenafter, put it in User Entity using #EmbeddedId and map both primary key using Hibernate Relational Mapping...
There are two option to Composite Primary Key:
Using #EmbeddedId
Using #IdClass()
Here down is example:
----------------------------------- Using EmbeddedId -----------------------------------
Compound primary key:
#Embeddable
public class UserIdName implements Serializable {
int id;
String name;
// getter and setter
}
User:
#Entity
#Table(name = "users")
public class USER{
#EmbeddedId
private UserIdName id;
String department;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Set<Userdetail> userdetail;
// getter and setter
}
UserDetails:
#Entity
#Table(name = "Userdetail")
public class Userdetail {
#Id
private int detail_id;
#ManyToOne
#JoinColumns({ #JoinColumn(name = "id", referencedColumnName = "id"),
#JoinColumn(name = "name", referencedColumnName = "name") })
private USER user;
String address;
String otherFields;
// getter setter
}
----------------------------------- Using IdClass -----------------------------------
Compound primary key:
public class UserIdName implements Serializable {
int id;
String name;
// getter and setter
}
User:
#Entity
#Table(name = "users")
#IdClass(UserIdName.class)
public class USER{
#Id
int id;
#Id
String name;
String department;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Set<Userdetail> userdetail;
// getter and setter
}
UserDetails:
#Entity
#Table(name = "Userdetail")
public class Userdetail {
#Id
private int detail_id;
#ManyToOne
#JoinColumns({ #JoinColumn(name = "id", referencedColumnName = "id"),
#JoinColumn(name = "name", referencedColumnName = "name") })
private USER user;
String address;
String otherFields;
// getter setter
}
-> If you wanna insert both foreign key manually try below code
Put this code in UserDetails
#ManyToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
#JoinColumn(name = "name", referencedColumnName = "name", insertable = false, updatable = false)
private USER user;
#Column(name="id")
private int id;
#Column(name="name")
private String name
// don't forget to put getter setter
User Table:
User Detail Table:
Related
I have a two table as table as
#Entity
#Table(name = "product", uniqueConstraints=#UniqueConstraint(columnNames={"product_idn"}))
public class Product implements Serializable {
private static final long serialVersionUID = 21409635044L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String product_idn;
}
another table as
#Entity
#Table(name = "storage")
public class Storage implements Serializable {
private static final long serialVersionUID = -67165579239L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id", nullable = false)
#JsonBackReference
private Product product;
}
Now I am fetching record from storage table. Should create a index (Non-Unique)on product_id of storage table? I have to fetch storages count per on product/ featching storages based on product.
Just add #Index annoation like below and it should work fine.
#Entity
#Table(name = "storage", indexes = #Index(columnList = "product_id",name = "storage_productId_index"))
public class Storage implements Serializable
I have spring boot project using JPA/Hibernate, MySQL. I have three dao classes that have a many to many relationship.
The Poko classes look like this
Product
#Entity
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "price")
private Double price;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(
name = "product_extra",
joinColumns = #JoinColumn(name="product_id"),
inverseJoinColumns = #JoinColumn(name="extra_id")
)
private List<Extra> extras = new ArrayList<>();
//constructor getters and setters
}
ProductExtra
#Entity
#Table(name = "product_extra")
public class ProductExtra {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
#Column(name = "product_id")
private Integer productId;
#Column(name = "extra_id")
private Integer extraId;
//constructor getters and setter
}
Extra
#Entity
#Table(name = "extra")
public class Extra {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "price")
private Double price;
#ManyToMany(mappedBy = "extras")
private List<Product> products = new ArrayList<>();
//constructor getters and setters
}
The Extra repository with the query
public interface ExtraRepository extends JpaRepository<Extra, Integer> {
#Query("SELECT e.id, e.name, e.price FROM Extra e INNER JOIN ProductExtra pe ON e.id = pe.extraId WHERE pe.productId = ?1")
List<Extra> findExtraById(Integer productId);
}
The mapping in my controller
#GetMapping("/product/{productId}")
public List<Extra>getExtraById(#PathVariable("productId") final Integer productId){
return extraRepository.findExtraById(productId);
}
I am trying to make a many to many query to select The extras in each product, i am however getting this error Failed to convert from type [java.lang.Object[]] to type [#org.springframework.data.jpa.repository.Query the error message surprisingly also contains the results i want. Not sure what am doing wrong
Remove the SELECT clause:
#Query("FROM Extra join e.productExtra WHERE pe.productId = ?1")
Also keep in mind, that you not write an SQL Query, You work on Object, so for join you use the mapped property
I am creating two tables using Spring boot and JPA:
Apartment table:
id, name, address_id, website
Address table:
id, street_num, street, city, .....
the address_id should be the foreign key and pointing to id in address table.
I couldn't get my code working. Here are my two Entity classes:
Apartment.java:
#Entity
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
#OneToOne(cascade = CascadeType.ALL)
#JoinTable(name = "address",
joinColumns = #JoinColumn(name = "apt_id"))
private Address address;
private String website;
//getters and setters
Address.java:
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer apt_id;
private String streetNum;
private String street;
private String city;
private String state;
private String zipCode;
//getters and setters
what I am getting is an extra column called address_id in address table....and missing address_id in apartment table....
Many Thanks!
Hibernate one to one mapping with foreign key association
In this kind of association, a foreign key column is created in owner entity
The join column is declared with the #JoinColumn annotation which looks like the #Column annotation. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
Replace Your Apartment Class with this:
#Entity
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "apt_id"))
private Address address;
private String website;
//getters and setters
I'm using composite PK in my app with 2 tables and one joining table.
I wrote this query for function:
#Repository
public interface HospitalDoctorDao extends JpaRepository<HospitalDoctor, Integer>{
#Query("select hd from HospitalDoctor hd join hospital on hd.hospital_id=hospital.id join doctor on hd.doctor_id = doctor.id where hospital_id = ?1 and doctor_id = ?1")
HospitalDoctor findByHospitalIdAndDoctorId(int hospital_id, int doctor_id);
}
and I am getting error Path expected for file! In MySQL everything is working. How Hibernate works in this case? How I should write this query? Here is my #Entity of join table:
#Entity
#Table(name = "hospital_doctor")
public class HospitalDoctor {
#Embeddable
static class HosdocPK implements Serializable {
private int hospitalId;
private int doctorId;
}
#EmbeddedId
#JsonBackReference
public HosdocPK hosdocPK;
#JsonManagedReference
#MapsId("DoctorId")
#ManyToOne(optional = false)
#JoinColumn(name = "doctorId", referencedColumnName = "id")
private Doctor doctor;
#JsonManagedReference
#MapsId("HospitalId")
#ManyToOne(optional = false)
#JoinColumn(name = "hospitalId", referencedColumnName = "id")
private Hospital hospital;
#Column(name = "Id")
private int id;
#Temporal(TemporalType.DATE)
private Date contract_start_date;
#Temporal(TemporalType.DATE)
private Date contract_end_date;
private String position;
private String supervisor;
private boolean part_time;
Getters and setters
}
Your query is incorrect.
Try:
select hd from HospitalDoctor hd where hd.hospital.id = ?1 and hd.doctor.id = ?2
I have Entities (Student,StudentSkills, StudentEmpSkills)
Student.java
#Entity
#Table(name = "Student", catalog = "dbs")
public class Student implements java.io.Serializable {
private int id;
...
...
private Set<StudentSkills> studentSkills= new HashSet<StudentSkills>(0);
private Set<StudentEmpSkills> studentEmpSkills= new HashSet<StudentEmpSkills>(0);
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Student")
public Set<StudentSkills> getStudentSkills() {
return this.studentEmpSkills;
}
public void setStudentSkills(
Set<StudentSkills> studentSkills) {
this.studentSkills = studentSkills;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Student")
public Set<StudentEmpSkills> getStudentEmpSkills() {
return this.StudentEmpSkills;
}
public void setStudentEmpSkills(
Set<StudentEmpSkills> studentEmpSkills) {
this.studentEmpSkills= studentEmpSkills;
}
}
in StudentEmpSkills.java
#Entity
#Table(name = "studentEmpSkills", catalog = "npdbs")
public class StudentEmpSkills implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private StudentEmpSkillsId id;
private Student Student ;
......
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "studentID", nullable = false, insertable = false, updatable = false)
public Student getStudent() {
return student;
}
In the above we are getting the Set of StudentEmpSkils from Student by one to many and many to one relation.
as we are getting Student from StudentEmpSkill
In JoinColumn we are giving studentID column to fetch the abject.
Now I want to get StudentSkill object from StudentEmpSkills.
StudentSkills - (studentID* | skillID*) | skillname
StudentEmpSkills - (studentID* | skillID* | empID*) | empName
(..) - composit primary key
So I want to fetch StudentSkills from StudentEmpSkill
What I need to write in StudentEmpSkills to fetch StudentSkill. because we have composit primary key in StudentSkill.
How to map the StudentSkill to StudentEmpSkills.
Can anyone please suggest?