I have two entities: Project.java and Employee.java that are ManyToMany mapped with each other (internally using the Hibernate generated table emp_project_mapping).
Now, I have a new one: Role.java that is to be mapped with above mentioned entities such that an employee in a project can have only one role. Also, this mapping should use that same mapping_table emp_project_mapping.
I have no idea how to achieve this scenario. Please help me out.
Employee.java
package com.ayush.springbootApp.bootCrudApi.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.ayush.springbootApp.bootCrudApi.model.Project;
import com.ayush.springbootApp.bootCrudApi.model.Workstation;
#Entity
#Table (name="employee_table")
//model class for Employee
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer id;
#Column
private String name;
#Column
private String gender;
#Column
private String department;
#Column
private String designation;
#Column
private Date dob;
#Column(name="empcode",nullable=false,unique=true)
private String empCode;
#OneToOne(mappedBy="emp")
private Workstation workStation;
#ManyToMany
#JoinTable(name="emp_project_mapping",joinColumns=#JoinColumn(name="emp_id"),inverseJoinColumns=#JoinColumn(name="project_id"))
private Set<Project> prj=new HashSet<Project>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public Set<Project> getProject()
{
return this.prj;
}
public void setProject(Set<Project> prj)
{
this.prj=prj;
}
#Override
public String toString() {
return "Employee [id=" + id + ", code="+ empCode + ", name=" + name + ", gender=" + gender + ", department=" + department
+ ", designation=" + designation + ", dob=" + dob + "]";
}
}
Project.java
package com.ayush.springbootApp.bootCrudApi.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import com.ayush.springbootApp.bootCrudApi.model.Employee;
#Entity
#Table(name="projects_table")
public class Project{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer id;
#Column(nullable=false)
private String oea_number;
#Column(nullable=false)
private String project_name;
#Column
private String client_name;
#Column
private String origin_country;
#Column(nullable=false)
private Integer po_amount;
#Column
private int project_active;
#ManyToMany(mappedBy="prj")
private Set<Employee> emp=new HashSet<Employee>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOea_number() {
return oea_number;
}
public void setOea_number(String oea_number) {
this.oea_number = oea_number;
}
public String getProject_name() {
return project_name;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public String getClient_name() {
return client_name;
}
public void setClient_name(String client_name) {
this.client_name = client_name;
}
public String getOrigin_country() {
return origin_country;
}
public void setOrigin_country(String origin_country) {
this.origin_country = origin_country;
}
public Integer getPo_amount() {
return po_amount;
}
public void setPo_amount(Integer po_amount) {
this.po_amount = po_amount;
}
public int getProject_active()
{
return this.project_active;
}
public void setProject_active(int project_active)
{
this.project_active=project_active;
}
public Set<Employee> getEmployee()
{
return this.emp;
}
public void setEmployee(Set<Employee> emp)
{
this.emp=emp;
}
#Override
public String toString() {
return "Project [id=" + id + ", oea_number=" + oea_number + ", project_name=" + project_name + ", client_name="
+ client_name + ", origin_country=" + origin_country + ", po_amount=" + po_amount + "]";
}
}
Role.java
package com.ayush.springbootApp.bootCrudApi.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="Employee_roles")
public class Role
{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="description",nullable=false)
private String desc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
emp_project_mapping table
Related
I have an entity Student and an entity Course, and they have many to many relationship, with the Student class being the owner. I'm able to add course for a student but I'm unable to remove a course for a student. I did create a utility method for deleting the connection but it does not work, and I'm not able to find the reason what is wrong. There is no error, it just does nothing.
Maybe anyone encounter anything similar? Thank you in advance
The database schema is a simple many to many relationship
Here is the Student entity:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})//(fetch = FetchType.LAZY)
#JoinTable(name = "student_course",
joinColumns = #JoinColumn(name = "student_id"),
inverseJoinColumns = #JoinColumn(name = "course_id"))
private Set<Course> courseTaken = new HashSet<>();
public Student() {
}
public Student(String firstName, String lastName, Set<Course> courseTaken) {
this.firstName = firstName;
this.lastName = lastName;
this.courseTaken = courseTaken;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Course> getCourseTaken() {
return courseTaken;
}
public void setCourseTaken(Set<Course> courseTaken) {
this.courseTaken = courseTaken;
}
public void removeCourse(Course tempCourse) {
courseTaken.remove(tempCourse);
tempCourse.getStudentAttending().remove(this);
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", courseTaken="
+ courseTaken + "]";
}
}
Here is a Course entity:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="course")
public class Course implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(name="course_name")
private String courseName;
#Column(name="course_description")
private String courseDescription;
#ManyToMany(mappedBy = "courseTaken")
private Set<Student> studentAttending = new HashSet<>();
public Course() {
}
public Course(String courseName, String courseDescription, Set<Student> studentAttending) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.studentAttending = studentAttending;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public Set<Student> getStudentAttending() {
return studentAttending;
}
public void setStudentAttending(Set<Student> studentAttending) {
this.studentAttending = studentAttending;
}
#Override
public String toString() {
return "Course [id=" + id + ", courseName=" + courseName + ", courseDescription=" + courseDescription + "]";
}
}
Oh, I found what I missed, I just forgot to save the changes into DB, student.save was missing. All works.
#GetMapping("/deleteCourse")
public String deleteCourseForStudent(#RequestParam("courseId") Long courseId, #RequestParam("studentId") Long studentId) {
Course tempCourse = courseService.findById(courseId);
Student tempStudent = studentService.findById(studentId);
tempStudent.removeCourse(tempCourse);
studentService.save(tempStudent);
return "redirect:/student/details?studentId=" + studentId;
}
I have two Entities CompanyDetail and DriverDetail
CompanyDetail
package com.javarnd.pns.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
#Entity
#Table(name="company_detail")
public class CompanyDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="company_id")
private long companyId;
#Column(name="company_name")
private String companyName;
#Column(name="pan_no")
private String panNo;
private String website;
private String email;
#Column(name="conntact_no")
private String contactNo;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name = "COMPANY_VEHICLE_DETAIL", joinColumns = #JoinColumn(name = "company_id"), inverseJoinColumns = #JoinColumn(name = "vehicle_id"))
private List<Vehicle> vehicleList;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name = "COMPANY_DRIVER_DETAIL", joinColumns = #JoinColumn(name = "company_id"), inverseJoinColumns = #JoinColumn(name = "driver_id"))
private List<DriverDetail> driverList;
#Column(name="type")
private String companyType;
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getPanNo() {
return panNo;
}
public void setPanNo(String panNo) {
this.panNo = panNo;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getCompanyType() {
return companyType;
}
public void setCompanyType(String companyType) {
this.companyType = companyType;
}
public List<Vehicle> getVehicleList() {
return vehicleList;
}
public void setVehicleList(List<Vehicle> vehicleList) {
this.vehicleList = vehicleList;
}
public List<DriverDetail> getDriverList() {
return driverList;
}
public void setDriverList(List<DriverDetail> driverList) {
this.driverList = driverList;
}
}
DriverDetail
package com.javarnd.pns.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
#Entity
public class DriverDetail {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="driver_id")
private long id;
private String name;
#Column(name="contact_no")
private String contactNo;
#Column(name="license_no")
private String licenseNo;
#ManyToMany(mappedBy="availableDriverList",cascade=CascadeType.ALL)
private List<Vehicle> asignedVehicle;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="company_id")
private CompanyDetails companyDetail;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactNo() {
return contactNo;
}
public String getLicenseNo() {
return licenseNo;
}
public void setLicenseNo(String licenseNo) {
this.licenseNo = licenseNo;
}
public List<Vehicle> getAsignedVehicle() {
return asignedVehicle;
}
public void setAsignedVehicle(List<Vehicle> asignedVehicle) {
this.asignedVehicle = asignedVehicle;
}
public CompanyDetails getCompanyDetail() {
return companyDetail;
}
public void setCompanyDetail(CompanyDetails companyDetail) {
this.companyDetail = companyDetail;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
}
MAIN TEST CLASS
package com.javarnd.pns.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.javarnd.pns.model.CompanyDetails;
import com.javarnd.pns.model.DriverDetail;
import com.javarnd.pns.service.CompanyDetailService;
import com.javarnd.pns.service.DriverDetailService;
public class TestPns {
public static void main(String[] args) {
CompanyDetailService cdService=new CompanyDetailService();
CompanyDetails cd=new CompanyDetails();
List<DriverDetail>ddList=new ArrayList<>();
DriverDetail driver=new DriverDetail();
DriverDetailService dds=new DriverDetailService();
Scanner kb=new Scanner(System.in);
System.out.println("Enter name:");
String cname=kb.nextLine();
driver.setName(cname);
System.out.println("Enter Compnay Id");
long companyId=kb.nextLong();
cd.setCompanyId(companyId);
System.out.println("Enter License:");
String license=kb.next();
driver.setLicenseNo(license);
System.out.println("Enter Contact");
String contact=kb.nextLine();
driver.setContactNo(contact);
ddList.add(driver);
cd.setDriverList(ddList);
driver.setCompanyDetail(cd);
dds.save(driver);
System.out.println("saved");
}
}
And now I tested that from my above main class, it printed the log in which it insert the values in DriverDetail table and update the company_detail table and at last then insert the values in COMPANY_DRIVER_DETAIL table
Finally the console LOG
Hibernate:
select
next_val as id_val
from
hibernate_sequence for update
Hibernate:
update
hibernate_sequence
set
next_val= ?
where
next_val=?
Hibernate:
/* insert com.javarnd.pns.model.DriverDetail
*/ insert
into
DriverDetail
(company_id, contact_no, license_no, name, driver_id)
values
(?, ?, ?, ?, ?)
Hibernate: //HERE IT IS UPDATING THE CompanyDetail , MAIKING ALL FIELDS NULL
/* update
com.javarnd.pns.model.CompanyDetails */ update
company_detail
set
company_name=?,
type=?,
conntact_no=?,
email=?,
pan_no=?,
website=?
where
company_id=?
Hibernate:
/* delete collection com.javarnd.pns.model.CompanyDetails.driverList */ delete
from
COMPANY_DRIVER_DETAIL
where
company_id=?
Hibernate:
/* delete collection com.javarnd.pns.model.CompanyDetails.vehicleList */ delete
from
COMPANY_VEHICLE_DETAIL
where
company_id=?
Hibernate:
/* insert collection
row com.javarnd.pns.model.CompanyDetails.driverList */ insert
into
COMPANY_DRIVER_DETAIL
(company_id, driver_id)
values
(?, ?)
After this everything goes fine except that the data corresponding of the particular id in Country_detail table is all NULL, and i don't want to fetch the data on behalf of id and then pass the object to driver.setCompanyDetail(cd); because it somehow degrades the performance, i need to know the way to resist this unnecessary update.
I have data model like below
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import org.hibernate.annotations.DiscriminatorOptions;
#SuppressWarnings("deprecation")
#Entity
#Table
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name="DTYPE", discriminatorType=DiscriminatorType.INTEGER)
#DiscriminatorValue("0")
#DiscriminatorOptions(force=true)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
public Employee() {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "EMPLOYEE_ID")
private int empID;
private String firstName;
private String lastName;
private Integer age;
private String email;
private String city;
private String phNum;
public String getPhNum() {
return phNum;
}
public void setPhNum(String phNum) {
this.phNum = phNum;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Patient.java
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.DiscriminatorOptions;
import org.hibernate.validator.constraints.NotEmpty;
#SuppressWarnings("deprecation")
#Entity
#Table
#PrimaryKeyJoinColumn(name = "EMPLOYEE_ID")
#DiscriminatorValue("6")
public class Patient extends Employee {
private static final long serialVersionUID = 1L;
#NotEmpty(message = "DOJ cannot be null")
private String doj;
private String primaryDoctor;
public String getPrimaryDoctor() {
return primaryDoctor;
}
public void setPrimaryDoctor(String primaryDoctor) {
this.primaryDoctor = primaryDoctor;
}
public String getDoj() {
return doj;
}
public void setDoj(String doj) {
this.doj = doj;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy = "patient", fetch = FetchType.LAZY)
private List<Encounter> encounterList;
public List<Encounter> getEncounterList() {
return encounterList;
}
public void setEncounterList(List<Encounter> encounterList) {
this.encounterList = encounterList;
}
}
Hibernate query at runtime
select useraccoun0_.empID as empID1_13_2_, useraccoun0_.EMPLOYEE_ID as EMPLOYEE6_13_2_,
useraccoun0_.fullName as fullName2_13_2_, useraccoun0_.password as password3_13_2_,
useraccoun0_.role as role4_13_2_, useraccoun0_.userName as userName5_13_2_,
employee1_.EMPLOYEE_ID as EMPLOYEE2_2_0_, employee1_.age as age3_2_0_,
employee1_.city as city4_2_0_, employee1_.email as email5_2_0_, employee1_.firstName as firstNam6_2_0_,
employee1_.lastName as lastName7_2_0_, employee1_.phNum as phNum8_2_0_, employee1_4_.doj as doj1_11_0_,
employee1_4_.primaryDoctor as primaryD2_11_0_, employee1_5_.specialization as speciali1_0_0_,
employee1_.DTYPE as DTYPE1_2_0_, encounterl2_.EMPLOYEE_ID as EMPLOYEE4_3_4_,
encounterl2_.EID as EID1_3_4_, encounterl2_.EID as EID1_3_1_, encounterl2_.labTest_testID as labTest_2_3_1_,
encounterl2_.medication_mid as medicati3_3_1_, encounterl2_.EMPLOYEE_ID as EMPLOYEE4_3_1_,
encounterl2_.vitalSign_EID as vitalSig5_3_1_ from UserAccount useraccoun0_
left outer join Employee employee1_ on useraccoun0_.EMPLOYEE_ID=employee1_.EMPLOYEE_ID
left outer join Pharmacist employee1_1_ on employee1_.EMPLOYEE_ID=employee1_1_.EMPLOYEE_ID
left outer join Nurse employee1_2_ on employee1_.EMPLOYEE_ID=employee1_2_.EMPLOYEE_ID
left outer join LabAssistant employee1_3_ on employee1_.EMPLOYEE_ID=employee1_3_.EMPLOYEE_ID
left outer join Patient employee1_4_ on employee1_.EMPLOYEE_ID=employee1_4_.EMPLOYEE_ID
left outer join Doctor employee1_5_ on employee1_.EMPLOYEE_ID=employee1_5_.EMPLOYEE_ID
left outer join Encounter encounterl2_ on employee1_.EMPLOYEE_ID=encounterl2_.EMPLOYEE_ID
where useraccoun0_.empID=4
In this query Discriminator column(DTYPE) is coming and its value is coming as 6. But it is giving me below exception
org.hibernate.WrongClassException: Object [id=null] was not of the specified subclass [com.*.*.Employee]: the class of the given object did not match the class of persistent copy
So not sure why it is giving me this exception and why id is coming as null.
-
I am trying to create mapped cart entity.but shows 404 error associated with Injection of autowired dependencies failed
Check my source and help me ro solve it..
Mapping plan:
Customer-----one to one------>Cart--------onetomany--->Product
Customer
package com.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class Customer {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Cid")
private int customerId;
#Column(name="password")
#NotEmpty(message="Name is mandatory")
private String password;
#Column(name="Email")
#NotEmpty(message="Name is mandatory")
private String email;
#NotEmpty(message="First Name is mandatory")
#Column(name="firstname")
private String firstName;
#NotEmpty(message="Last Name is mandatory")
#Column(name="lastname")
private String lastName;
#Column(name="Mobile")
#Size(min = 10)
#NotEmpty(message="Mobile is mandatory")
private String mobile;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="address_id")
private Address delAdderss;
private boolean enabled;
private String role;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="cart_id")
private Cart cart;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Address getDelAdderss() {
return delAdderss;
}
public void setDelAdderss(Address delAdderss) {
this.delAdderss = delAdderss;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
}
Cart
package com.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
#Entity
public class Cart {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int cart_id;
#Column
private double total;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="CID")
private Customer customer;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name="id")
private List<Product> product;
public int getCart_id() {
return cart_id;
}
public void setCart_id(int cart_id) {
this.cart_id = cart_id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
Product
package com.model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;
#Entity
public class Product {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column
private String product_Name;
#Column
private String descripction;
#Column
private int price;
#Column
private Date mfg_Date;
#Transient
private MultipartFile image;
#ManyToOne(cascade = CascadeType.ALL)
private List<Cart> cart;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_Name() {
return product_Name;
}
public void setProduct_Name(String product_Name) {
this.product_Name = product_Name;
}
public String getDescripction() {
return descripction;
}
public void setDescripction(String descripction) {
this.descripction = descripction;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getMfg_Date() {
return mfg_Date;
}
public void setMfg_Date(Date mfg_Date) {
this.mfg_Date = mfg_Date;
}
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public List<Cart> getCarts() {
return cart;
}
public void setCarts(List<Cart> carts) {
this.cart= carts;
}
}
After Searching stack overflow I came to this
Can I use hibernate query language for entities not mapped to a table?
But recently I was making a small project where the two entities were not mapped by any Mapped Annotations and still I got the result for the query.
So I am confused as the posts say it is not possible to query on Non-Mapped Entities.
Customer
package com.mayank.bitmesra.pojo;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String customerId;
private String name;
private String phoneNumber;
#Temporal(TemporalType.DATE)
private Date dateOfBirth;
#Temporal(TemporalType.DATE)
private Date createdDate;
//for rolling back of Data
//using date as such of now
#Temporal(TemporalType.DATE)
private Date updatedOn;
//for picking up only the data that is most recent
//like a customer can have save with same customer id
//but has different address as his address might have changed up in near future
//will try to handle this in near future
/* #Temporal
private Date lastPickedUpDate;*/
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", phoneNumber=" + phoneNumber + "]";
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#PrePersist
protected void onCreate() {
createdDate = new Date();
}
#PreUpdate
protected void onUpdate() {
updatedOn = new Date();
}
}
OrderDetails
package com.mayank.bitmesra.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class OrderDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String customerId;
private String orderId;
private String orderName;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
}
OrderDetailsDAOImpl
#Repository
#Transactional
public class OrderDetailsDAOImpl implements OrderDetailsDAO{
#PersistenceContext
EntityManager entityManager;
#Override
public List getAllOrderDetails() {
// return entityManager.createQuery("Select order from OrderDetails order ").getResultList();
return entityManager.createQuery("Select customer.name from OrderDetails order inner join Customer customer on order.customerId=customer.customerId").getResultList();
}
I think you are confused . #Entity is the annotation used by HQL to identify the so called mapped entities. Both of the entities are annotated by them.