Hibernate many-to-one mapping sets foreign key null - java

Student has multiple laptops. Student oneToMany Laptop mapping
Student.java
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Student {
#Id
private int id;
private StudentName studentName;
private String email;
#OneToMany(mappedBy = "student")
private List<Laptop> laptops = new ArrayList<Laptop>();
public Student() {
}
public Student(int id, StudentName studentName, String email) {
this.id = id;
this.studentName = studentName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public StudentName getStudentName() {
return studentName;
}
public void setStudentName(StudentName studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Laptop> getLaptop() {
return laptops;
}
public void setLaptop(List<Laptop> laptops) {
this.laptops = laptops;
}
#Override
public String toString() {
return "Student [id=" + id + ", studentName=" + studentName + ", email=" + email + "]";
}
}
Laptop.java
package com.practice.hibernateDemo.enity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Laptop {
#Id
private int lid;
private String lName;
#ManyToOne
#JoinColumn(name="student_id", referencedColumnName="id")
private Student student;
public Laptop() {
}
public int getLid() {
return lid;
}
public void setLid(int lid) {
this.lid = lid;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Laptop [id=" + lid + ", lName=" + lName + "]";
}
}
Main class
package com.practice.hibernateDemo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.practice.hibernateDemo.enity.Laptop;
import com.practice.hibernateDemo.enity.Student;
import com.practice.hibernateDemo.enity.StudentName;
public class CreateStudent {
public static void main(String[] args) {
Laptop laptop = new Laptop();
laptop.setLid(100);
laptop.setlName("HP");
Student student = new Student();
student.setId(101);
student.setEmail("test#gmail.com");
student.setStudentName(new StudentName("test1","test2", "test3"));
student.getLaptop().add(laptop);
Configuration con = new Configuration().configure().addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);
SessionFactory sf = con.buildSessionFactory();
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(laptop);
session.save(student);
tx.commit();
}
}
After saving the object , foreign key in laptop table is setting as null
lid lName student_id
100 HP NULL
Anyone know where I did wrong mapping due to which I am getting foreign key as null
Thanksin advance

The "many" side of a 1:many relationship is always the owning side. If the relationship is bidirectional, then the other side will carry a mappedBy attribute, just like the non-owning side of a bidirectional 1:1 relationship. It is the relationship field on the owning side that is meaningful for conveying the relationship to the persistence layer, and you have failed to set that.
For example,
laptop.setStudent(student);

Related

Spring Boot JPA many to many removing join table relationship

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

.DefaultHandlerExceptionResolver Im getting this error while uploading the data please help me out in this project its working properly on server

The contact class as an entity that would be linked with address class
package asmt1.demo.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
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.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import asmt1.demo.dto.UserStatus;
//#Entity annotation specifies that the class is an entity and is mapped to a database table.
//#Table annotation specifies the name of the database table to be used for mapping
#Entity
#Table(name="Contactdetail")
public class Contact {
//#Id is used to specify the primary key
#Id
//Generated value is used to generate pk value ie. id to be autogenerated and assign identity column(id)
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
//#column is used to specify the column condition
//#Column( unique = true)
private String firstName;
private String lastName;
//#Column(unique = true)
private long contactNo;
private String mailId;
//list of named constant ie. status
#Enumerated(EnumType.STRING)
private UserStatus status;
//it is used to create one-to-one relationship between the contact and address table
//fetch type.lazy tells Hibernate to only fetch the related entities from the database when you use the relationship
#ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinTable(name="conadd",
joinColumns = {#JoinColumn(name="id")},
inverseJoinColumns = {#JoinColumn(name="addid")})
//To handle the problem related to the serialization of the model using Jackson API when the model attributes have a lazy loading defined,
//we have to tell the serializer to ignore the chain or helpful garbage that Hibernate adds to classes, so it can manage lazy loading of data by declaring #JsonIgnoreProperties
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private Set<Address> address=new HashSet<>();
//generate getters,setters, toString() and constructor using fields
public Contact() {}
public Contact(String firstName, String lastName, long contactNo, String mailId, UserStatus status,
Set<Address> address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.contactNo = contactNo;
this.mailId = mailId;
this.status = status;
this.address = address;
}
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
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 long getContactNo() {
return contactNo;
}
public void setContactNo(long contactNo) {
this.contactNo = contactNo;
}
public String getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
#Override
public String toString() {
return "Contact [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", contactNo=" + contactNo
+ ", mailId=" + mailId + "]";
}
}
the address class which is the entity
package asmt1.demo.entity;
import java.util.HashSet;
import java.util.Set;
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.ManyToMany;
import javax.persistence.Table;
//#Entity annotation specifies that the class is an entity and is mapped to a database table.
//#Table annotation specifies the name of the database table to be used for mapping
#Entity
#Table(name="addressDetail")
public class Address {
//#Id is used to specify the primarykey
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long addid;
private String street1;
private String street2;
private long zipcode;
private String city;
private String state;
private String Country;
//mappedby is used to specify to relationship
#ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "address")
private Set<Contact> contact=new HashSet<>();
//generate getters,setters, toString() and constructor using fields
public long getId() {
return addid;
}
public Set<Contact> getContact() {
return contact;
}
public void setContact(Set<Contact> contact) {
this.contact = contact;
}
public void setId(long id) {
this.addid = id;
}
public String getStreet1() {
return street1;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
public long getZipcode() {
return zipcode;
}
public void setZipcode(long zipcode) {
this.zipcode = zipcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public Address(String street1, String street2, long zipcode, String city, String state, String country) {
super();
this.street1 = street1;
this.street2 = street2;
this.zipcode = zipcode;
this.city = city;
this.state = state;
Country = country;
}
public Address() {}
}
a request class where I was calling both for data uploading
package asmt1.demo.dto;
import java.util.HashSet;
import java.util.Set;
import asmt1.demo.entity.Address;
import asmt1.demo.entity.Contact;
public class AddressReq {
private Set<Address> address=new HashSet<>();
private Set<Contact> contact=new HashSet<>();
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
public Set<Contact> getContact() {
return contact;
}
public void setContact(Set<Contact> contact) {
this.contact = contact;
}
public AddressReq(Set<Address> address, Set<Contact> contact) {
super();
this.address = address;
this.contact = contact;
}
public AddressReq() {}
#Override
public String toString() {
return "AddressReq [address=" + address + ", contact=" + contact + "]";
}
}
enum class for status
package asmt1.demo.dto;
//constant value for userstatus class
public enum UserStatus {
ACTIVE,INACTIVE
}
controller class
package asmt1.demo.controller;
import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import asmt1.demo.converter.ContactConverter;
import asmt1.demo.dto.AddressReq;
import asmt1.demo.dto.ContactDto;
import asmt1.demo.entity.Contact;
import asmt1.demo.repository.AddressRepo;
import asmt1.demo.repository.ContactRepo;
//#restcontroller is used for restful services
#RestController
//#RequestMapping is used for creating baseurl for controller will be used
#RequestMapping("/contact")
public class ContactController {
//#Autowired will search the object of class
#Autowired
private ContactRepo ctrepo;
#Autowired
private AddressRepo addrepo;;
#Autowired
private ContactConverter converter;
//#Requestbody is used to map/bind methods with pojo pr value to return value to the web
//#postmapping is used to add data to database from web
#PostMapping("/add")
public List<Contact> newcontact(#RequestBody AddressReq req) {
return ctrepo.saveAll(req.getContact());
}
//#getmapping is used to get the details/records from database on web page
#GetMapping("/contactlist")
public List<Contact> getcontactlist(){
return ctrepo.findAll(Sort.by(Sort.Direction.ASC, "firstName","lastName"));
}
#GetMapping("/contactdto")
public List<ContactDto> getcontactlistdto(){
List<Contact> findAll=ctrepo.findAll();
return converter.entitytodto(findAll);
}
#GetMapping("/contactlist/{id}")
public ResponseEntity<Contact> get(#PathVariable Long id) {
try {
Contact contact = ctrepo.getOne(id);
return new ResponseEntity<Contact>(contact, HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<Contact>(HttpStatus.NOT_FOUND);
}
}
#GetMapping("/contactdto/{id}")
public ContactDto getbyid(#PathVariable Long id) {
Contact orElse=ctrepo.findById(id).orElse(null);
return converter.entitytodto(orElse);
}
#GetMapping("/orderlist")
public List<Contact> getcontactlistbyorder(){
return ctrepo.findAllByOrderByIdDesc();
}
#PostMapping("/save")
public ContactDto savedto(#RequestBody ContactDto dto) {
Contact contact=converter.dtotoentity(dto);
contact=ctrepo.save(contact);
return converter.entitytodto(contact);
}
//#deletemapping is used to delete the records/details from database by web page
#DeleteMapping("/delete/{id}")
public String deletebyid(#PathVariable long id){
if (ctrepo.findById(id)==null) {
return "Id not found.....Please enter correct id";
}
ctrepo.deleteById(id);
return "Successfully deleted "+id;
}
//#putmapping is used to change/update the records/details in database by web page
#PutMapping("/edit")
public List<Contact> editcontactbyid(#RequestBody AddressReq req ){
return ctrepo.saveAll(req.getContact());
}
}
here is the Json format which I was uploading the data but its showing me error that
at [Source: (PushbackInputStream); line: 1, column: 2]]
2021-05-04 12:57:07.799 WARN 876 --- [nio-9090-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.util.HashSet<asmt1.demo.entity.Contact> out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.HashSet<asmt1.demo.entity.Contact> out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 13] (through reference chain: asmt1.demo.dto.AddressReq["contact"])]
{"contact":{
"firstName":"tomu",
"lastName":"shawn",
"contactNo":9124245,
"mailId":"ggia#gmail.com",
"status":"INACTIVE",
"address":{
"street1":"A/wing-24",
"street2":"plotno-4",
"city":"Mumbai",
"state":"Maharashtra",
"country":"India",
"zipcode":705
}}}
In your AddressReq class contact is set that is collection but in your pay load you are sending an object which should be collection of object.
Based on the AddressReq class the pay load should be
{["contact":{
"firstName":"tomu",
"lastName":"shawn",
"contactNo":9124245,
"mailId":"ggia#gmail.com",
"status":"INACTIVE",
"address":{
"street1":"A/wing-24",
"street2":"plotno-4",
"city":"Mumbai",
"state":"Maharashtra",
"country":"India",
"zipcode":705
}
}]
}
or if your request is always single entry of contact then you can change the contact property to single instance not the collection of Contact instance.

New entity required in an existing ManyToMany

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

Repeated column in mapping for entity should be mapped with insert="false" update="false"

I am having a pojo class Address and I am trying build a database table where there should be different home address and office address. I am using AttributeOverride annotation to get make the address class to show property of office address and home address seperately, however I am getting the below issue.
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: org.blogPost.Employee column: CITY_NAME (should be mapped with insert="false" update="false")
Please see the below code and suggest the corrrect fix for this.
Main Class.
package org.blogPost;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class TestEmployee {
public static void main(String[] args) {
SessionFactory sessionfactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
Date date= new Date();
Employee emp1= new Employee();
Address addr= new Address();
Address home_addr= new Address();
addr.setStreet("This is a test street");
addr.setCity("test city");
addr.setPincode("test Pin");
home_addr.setStreet("Home Street Test");
home_addr.setCity("Home test home");
home_addr.setPincode("Test_home pin");
//emp1.setEmpId(101);
emp1.setEmpName("Employee five");
emp1.setEmpLastName("Employee five SirName");
emp1.setNumber(7755);
emp1.setEmail("emp55#hibernate.com");
emp1.setAddress(home_addr);
emp1.setOfficeAddress(addr);
emp1.setEmpLoginTime(date);
session.save(emp1);
session.getTransaction().commit();
emp1= null;
session=sessionfactory.openSession();
session.beginTransaction();
emp1=(Employee)session.get(Employee.class, 1);
System.out.println("Below is the user details");
System.out.println("Employee ID : "+emp1.getEmpId());
System.out.println("Employee Name : "+emp1.getEmpName());
System.out.println("Employee Address : "+emp1.getAddress());
System.out.println("Employee email ID : "+emp1.getEmail());
}
}
Employee Class where I am facing the issue.
package org.blogPost;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="EmployeeInfo")
public class Employee {
private int empId;
private String empName;
private String empLastName;
private long number;
private String email;
private Date empLoginTime;
private Address address;
#AttributeOverrides({
#AttributeOverride
(name="street",column=#Column(name="HOME_STREET_ADDRESS")),
#AttributeOverride
(name="city",column=#Column(name="HOME_CITY_ADDRESS")),
#AttributeOverride
(name="pincode",column=#Column(name="HOME_PIN_CODE"))
})
private Address officeAddress;
#Id
#GeneratedValue(strategy=GenerationType.TABLE,generator="empID")
#TableGenerator(name="empID",table="empPrimaryKey",pkColumnName="empKey",pkColumnValue="empValue",allocationSize=1)
#Column(name="EmployeeId",nullable=false)
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
#Column(name="First_Name",nullable=false)
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
#Column(name="Last_Name",nullable=false)
public String getEmpLastName() {
return empLastName;
}
public void setEmpLastName(String empLastName) {
this.empLastName = empLastName;
}
#Column(name="Phone_number")
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
#Column(name="Email_Address",nullable=false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Temporal(TemporalType.TIMESTAMP)
public Date getEmpLoginTime() {
return empLoginTime;
}
public void setEmpLoginTime(Date empLoginTime) {
this.empLoginTime = empLoginTime;
}
#Embedded
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Embedded
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
}
Address class.
package org.blogPost;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String street;
private String city;
private String pincode;
#Column(name="STREET_NAME")
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
#Column(name="CITY_NAME")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name="PIN_CODE")
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Below is the exception I am getting when I run the code.
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: org.blogPost.Employee column: CITY_NAME (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:670)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:692)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:688)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:714)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:468)
at org.hibernate.mapping.RootClass.validate(RootClass.java:215)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1149)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1334)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
at org.blogPost.TestEmployee.main(TestEmployee.java:12)
Please keep #AttributeOverrides annotation on getter method(public Address getOfficeAddress()) just like you have used annotations on getter methods of other member variables(public int getEmpId()). It will work.

Spring-Hibernate, Many to Many relationship query

I have two bean classes Student and Course which has many to many relationship with each other. For eg. one student can register for multiple courses and vice versa. I have used HibernateTemplate to save objects into Oracle DB. Following are Student, Course and StudentDao classes.
Student Class
package com.springhibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
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 {
private int studentId;
private String firstName;
private String lastName;
private Set<Course> courses;
#Id
#Column(name="student_id")
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
#Column(name="first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "Student_Course", joinColumns = #JoinColumn(name = "student_id"), inverseJoinColumns = #JoinColumn(name = "course_id"))
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
StudentDao class
package com.springhibernate;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class StudentDao {
private static Helper helper = new Helper();
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
// method to save student
public void saveStudent(Student s) {
template.save(s);
}
// method to return one employee of given id
public Student getById(int id) {
Student s = (Student) template.get(Student.class, id);
return s;
}
public List<Course> findCourse(){
List<Course> list = template.find("from Course");
return list;
}
}
Course Class
package com.springhibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="Course")
public class Course {
private int courseId;
private String courseName;
private Set<Student> students;
#Id
#Column(name="course_id")
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
#Column(name="course_name")
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
#ManyToMany(cascade=CascadeType.ALL,mappedBy="courses")
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return this.courseId;
}
#Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
Course temp = (Course) o;
return (this.courseId==temp.courseId);
}
}
I have following two queries
I am able to save data in student_course table successfully. I was wondering if I want to retrieve data from student_course table, how can I do it using HibernateTemplate or is there any other way to do so?
For example, query is like
select course_id from student_course where student_id=1
Please note I want just the course id column not complete row.
If in student_course table I want one more column say course_name (from course table), how can I do that?
You can do it in the following way, but keep in mind that the HibernateTemplate is an old API and you should use for example the EntityManager(Factory).
You can get it via the Peristence class.
hibernateTemplate.execute(new HibernateCallback<List>() {
public String doInHibernate(Session s)
throws HibernateException, SQLException {
SQLQuery sql=s.createSQLQuery("select course_id from student_course where student_id=?");
sql.setParameter(0, adventureId);
sql.addScalar(studentID);
return sql.list();
}
});

Categories

Resources