Issue in creating a Foreign Key relationship through Hibernate Annonations - java

I have 2 class Employee and Passport, then I tried to create a one to one mapping with Primary and Foreign Key Relationship with Annotations, but the foreign key relationship is not happening in Passport table.
Here Primary_Id is Emp_No in Employee table and must be a foreign Key in Passport table.
Below i have provided the 2 POJO classes for Employee and Passport and also the generated SQL from Hibernate.
Could somebody help me where I make mistake. Kindly let me know in case of further information.
Employee
package com.otr.hibernate;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
*
* #author SPAR
*/
#Entity
public class Employee implements Serializable {
#Id
private String emp_No;
private String first_Name;
private String second_Name;
private String designation;
public String getEmp_No() {
return emp_No;
}
public void setEmp_No(String emp_No) {
this.emp_No = emp_No;
}
public String getFirst_Name() {
return first_Name;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getSecond_Name() {
return second_Name;
}
public void setSecond_Name(String second_Name) {
this.second_Name = second_Name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
Passport.java
package com.otr.hibernate;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
*
* #author SPAR
*/
#Entity
public class Passport implements Serializable {
private String passport_No;
#Id #GeneratedValue(generator = "foreign")
#GenericGenerator(name= "foreign", strategy = "foreign", parameters = {#Parameter(value = "employee", name = "property")})
private String emp_RN_No;
#OneToOne (cascade = CascadeType.ALL)
#JoinColumn(name = "emp_RN_No")
private Employee employee;
public String getPassport_No() {
return passport_No;
}
public void setPassport_No(String passport_No) {
this.passport_No = passport_No;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getEmp_No() {
return emp_No;
}
public void setEmp_RN_No(String emp_No) {
this.emp_No = emp_No;
}
}
Hibernate Generation
Hibernate: create table Employee (emp_No varchar(255) not null, designation varchar(255), first_Name varchar(255), second_Name varchar(255), primary key (emp_No));
Hibernate: create table Passport (emp_No varchar(255) not null, passport_No varchar(255), primary key (emp_No));

You don't need the GenericGenerator to do that. There are two simpler alternatives:
Combine #Id and #OneToOne:
#Id #OneToOne (cascade = CascadeType.ALL)
#JoinColumn(name = "emp_RN_No")
private Employee employee;
Make sure you remove the previous #Id property emp_RN_No
Using #MapsId:
#Id
private String emp_RN_No;
#MapsId #OneToOne
#JoinColumn(name = "emp_RN_No")
private Employee employee;

Related

org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property while saving master child records

I have a master table and child table with one to one relationship. The child table id field is reference field of master table and it's a primary key too. The ID field to master table is not autogenerated and it will be set manually. While saving the object along with child reference it throws error below error "org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property
I have provided the code for reference.
Note:- If I make the ID key in master table as autogenerated then it works fine. But I want to pass the ID that we receive from JSON request.
package com.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.sql.Timestamp;
#Entity
#Table(name="MASTER")
public class Master {
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDER_ID", unique = true, nullable = false)
private long orderId;
#Column(name="MasterNumber", length = 17)
private String masterNumber;
#OneToOne(mappedBy = "master", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name="ORDER_ID", nullable=false, insertable=false, updatable=false)
private Child child;
#Column(name="Received_Date")
private Timestamp receivedDate;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public String getMasterNumber() {
return masterNumber;
}
public void setMasterNumber(String masterNumber) {
this.masterNumber = masterNumber;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
this.child.setMaster(this);
}
public Timestamp getReceivedDate() {
return receivedDate;
}
public void setReceivedDate(Timestamp receivedDate) {
this.receivedDate = receivedDate;
}
}
package com.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="CHILD")
public class Child {
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDER_ID")
private long orderId;
#MapsId
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="ORDER_ID", referencedColumnName = "ORDER_ID", foreignKey = #ForeignKey(name="FK_Master_Child_REF"), nullable = false)
private Master master;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public Master getMaster() {
return master;
}
public void setMaster(Master master) {
this.master = master;
this.setOrderId(master.getOrderId());
}
}
Repository class
package com.dao;
import com.entities.Master;
import org.springframework.data.repository.CrudRepository;
public interface MasterRepository extends CrudRepository<Master, Long> {
}
Helper method to save
public void Save(Master master)
{
masterRepository.save(master);
}
java.util.Date today = new java.util.Date();
java.sql.Timestamp currentTime = new java.sql.Timestamp(today.getTime());
Master master = new Master();
master.setOrderId(1212L);
master.setMasterNumber("M001");
master.setReceivedDate(currentTime);
Child child = new Child();
child.setMaster(master);
master.setChild(child);
Helper.Save(master);
I expect both master and child records to get inserted. But I am getting the below error.
"org.hibernate.id.IdentifierGenerationException: attempted to assign
id from null one-to-one property
Please help me on this. Thanks in advance.

hibernate search query from a list that match exactly from the child table with one-many relation ship

I am using spring-boot and hibernate. I am using one to many relationships.
In the main table, it has the details of the user logs like
jobId(pk), department, startDate. The child table is the category table(Id(pk),catId,catDesc,jobId(fk))
i.e each jobId in the parent table can have multiple categories. Now I want to get all the values from the main table and child table that exactly matches with the List of categories(child table values).
createQuery("select * from parent p, child c where p.jobId=c.jobId AND c.catId IN ("+catId+" ) )
here catId is a list of values. But I want to get only those values that match all the values and the query is dynamic.
package com.assorted.product.model;
import java.io.Serializable;
import java.util.Date;`enter code here`
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.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "parent")
public class Parent implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "JOB_ID")
private long jobId;
#Column(name = "USER_ID")
private String userId;
#Column(name = "COUNTRY_NAME")
private String countryName;
#Column(name = "DEPT_ID")
private long depId;
#Column(name = "DEPT_NAME")
private String depName;
#Column(name = "START_DATE")
#Temporal(TemporalType.DATE)
private Date startDate;
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinColumn(name="JOB_ID",referencedColumnName="JOB_ID")
private Set<CategoryLogs> categoryLogs;
public long getJobId() {
return jobId;
}
public void setJobId(long jobId) {
this.jobId = jobId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getDepId() {
return depId;
}
public void setDepId(long depId) {
this.depId = depId;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Set<CategoryLogs> getCategoryLogs() {
return categoryLogs;
}
public void setCategoryLogs(Set<CategoryLogs> categoryLogs) {
this.categoryLogs = categoryLogs;
}
}
package com.assorted.product.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.Table;
#Entity
#Table(name = "child")
public class CategoryLogs {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "ID")
private String id;
#Column(name = "CAT_ID")
private long catId;
#Column(name = "CAT_NAME")
private String catName;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "JOB_ID")
private Parent parent;
public CategoryLogs(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getCatId() {
return catId;
}
public void setCatId(long catId) {
this.catId = catId;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
JOIN FETCH.
The FETCH keyword of the JOIN FETCH statement is JPA-specific. It tells the persistence provider to not only join the 2 database tables within the query but to also initialize the association on the returned entity. You can use it with a JOIN and a LEFT JOIN statement.
List<Parent> parents = em.createQuery("SELECT p FROM Parent p JOIN FETCH p.categoryLogs c
WHERE c.catId IN (:cat_Ids) " , Parent.class)
.setParameterList("cat_Ids",your_cat_id_list )
.getResultList();

Hibernate mapping error: duplicate foreign key

Entity Class UserExtraDetails with having one to one relationship with APP_USER with column SSO_ID
package com.eportal.models;
import java.io.Serializable;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "userdetails")
public class userExtraDetails implements Serializable {
#Column(name = "Address", nullable = true)
private String Address;
#Id
#Column(name = "SSO_ID", nullable = false)
private String ssoId;
#Column(name = "City", nullable = true)
private String City;
#Column(name = "Country", nullable = true)
private String Country;
#Column(name = "Postal_Code", nullable = true)
private String Postal_Code;
#Column(name = "about_me", nullable = true)
private String about_me;
#OneToOne(fetch = FetchType.LAZY)
#JoinTable(name = "APP_USER", joinColumns = { #JoinColumn(name = "SSO_ID") })
private User user;
public String getAbout_me() {
return about_me;
}
public String getSsoId() {
return ssoId;
}
public void setSsoId(String ssoId) {
this.ssoId = ssoId;
}
public void setAbout_me(String about_me) {
this.about_me = about_me;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getPostal_Code() {
return Postal_Code;
}
public void setPostal_Code(String postal_Code) {
Postal_Code = postal_Code;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Entity Class User with a one to one relationship with userdetails with column SSO_ID
package com.eportal.models;
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.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.OneToOne;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "APP_USER")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty
#Column(name = "SSO_ID", unique = true, nullable = false)
private String ssoId;
#NotEmpty
#Column(name = "PASSWORD", nullable = false)
private String password;
#NotEmpty
#Column(name = "FIRST_NAME", nullable = false)
private String firstName;
#NotEmpty
#Column(name = "LAST_NAME", nullable = false)
private String lastName;
#NotEmpty
#Column(name = "EMAIL", nullable = false)
private String email;
#OneToOne(fetch = FetchType.LAZY)
#JoinTable(name = "userdetails", joinColumns = { #JoinColumn(name = "SSO_ID") })
private userExtraDetails details;
#NotEmpty
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "APP_USER_USER_PROFILE", joinColumns = { #JoinColumn(name = "USER_ID") }, inverseJoinColumns = {
#JoinColumn(name = "USER_PROFILE_ID") })
private Set<UserProfile> userProfiles = new HashSet<UserProfile>();
public userExtraDetails getDetails() {
return details;
}
public void setDetails(userExtraDetails details) {
this.details = details;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSsoId() {
return ssoId;
}
public void setSsoId(String ssoId) {
this.ssoId = ssoId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<UserProfile> getUserProfiles() {
return userProfiles;
}
public void setUserProfiles(Set<UserProfile> userProfiles) {
this.userProfiles = userProfiles;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((ssoId == null) ? 0 : ssoId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof User))
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (ssoId == null) {
if (other.ssoId != null)
return false;
} else if (!ssoId.equals(other.ssoId))
return false;
return true;
}
/*
* DO-NOT-INCLUDE passwords in toString function. It is done here just for
* convenience purpose.
*/
#Override
public String toString() {
return "User [id=" + id + ", ssoId=" + ssoId + ", password=" + password + ", firstName=" + firstName
+ ", lastName=" + lastName + ", email=" + email + "]";
}
}
18:31:55.434 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table APP_USER add constraint FK_1wjx4w75wu94ftp6jvt35krf0 foreign key (user_id) references APP_USER
18:31:55.434 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - There is already an object named 'FK_1wjx4w75wu94ftp6jvt35krf0' in the database.
18:31:55.438 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table APP_USER add constraint FK_hqk6uc88j3imq8u9jhro36vt3 foreign key (SSO_ID) references userdetails
18:31:55.438 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_hqk6uc88j3imq8u9jhro36vt3". The conflict occurred in database "CloudDB", table "dbo.userdetails", column 'SSO_ID'.
18:31:55.440 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table APP_USER_USER_PROFILE add constraint FK_brmce0t584euix4wb4rursf1q foreign key (USER_ID) references APP_USER
18:31:55.440 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - There is already an object named 'FK_brmce0t584euix4wb4rursf1q' in the database.
18:31:55.442 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table userdetails add constraint FK_pffebqmeoi5qdq5g63w450h1i foreign key (SSO_ID) references APP_USER
18:31:55.442 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaUpdate - Column 'APP_USER.id' is not the same data type as referencing column 'userdetails.SSO_ID' in foreign key 'FK_pffebqmeoi5qdq5g63w450h1i'.
18:31:55.442 [localhost-startStop-1] INFO o.h.tool.hbm2ddl.SchemaUpdate - HHH000232: Schema update complete
The following error is shown:
Unsuccessful: alter table APP_USER add constraint
FK_1wjx4w75wu94ftp6jvt35krf0 foreign key (user_id) references APP_USER
There is already an object named 'FK_1wjx4w75wu94ftp6jvt35krf0' in the
database.
Unsuccessful: alter table APP_USER add constraint
FK_hqk6uc88j3imq8u9jhro36vt3 foreign key (SSO_ID) references
userdetails
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"FK_hqk6uc88j3imq8u9jhro36vt3". The conflict occurred in database
"CloudDB", table "dbo.userdetails", column 'SSO_ID'.
Unsuccessful: alter table APP_USER_USER_PROFILE add constraint
FK_brmce0t584euix4wb4rursf1q foreign key (USER_ID) references APP_USER
There is already an object named 'FK_brmce0t584euix4wb4rursf1q' in the
database.
Unsuccessful: alter table userdetails add constraint
FK_pffebqmeoi5qdq5g63w450h1i foreign key (SSO_ID) references APP_USER
Column 'APP_USER.id' is not the same data type as referencing column
'userdetails.SSO_ID' in foreign key 'FK_pffebqmeoi5qdq5g63w450h1i'.

Update using one to one relationship hibernate

I have one parent object as Employee and child object as Address. I just need to update the both objects using Employee object. But when updating using employee object i just getting emp_id should not be null. Here is my table and entity
CREATE TABLE `employee` (
`employee_id` bigint(20) NOT NULL AUTO_INCREMENT,
`employee_name` varchar(30) NOT NULL,
`employee_desg` varchar(30) NOT NULL,
`salary` varchar(30) NOT NULL,
`employee_reference_id` varchar(10) NOT NULL,
PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
Address table
CREATE TABLE `address` (
`address_id` bigint(20) NOT NULL AUTO_INCREMENT,
`emp_id` bigint(20) NOT NULL,
`address` varchar(255) NOT NULL,
PRIMARY KEY (`address_id`),
KEY `employee_address` (`emp_id`),
CONSTRAINT `employee_address` FOREIGN KEY (`emp_id`) REFERENCES `employee` (`employee_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
Employee Object
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue
#Column(name = "EMPLOYEE_ID")
private int id;
#Column(name = "EMPLOYEE_NAME")
private String employeeName;
#Column(name = "EMPLOYEE_DESG")
private String employeeDesg;
#Column(name = "SALARY")
private String salary;
#Column(name = "EMPLOYEE_REFERENCE_ID")
private String employeeReferenceId;
public String getEmployeeReferenceId() {
return employeeReferenceId;
}
public void setEmployeeReferenceId(String employeeReferenceId) {
this.employeeReferenceId = employeeReferenceId;
}
#OneToOne(mappedBy="employee", cascade = CascadeType.ALL)
private Address address;
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeDesg() {
return employeeDesg;
}
public void setEmployeeDesg(String employeeDesg) {
this.employeeDesg = employeeDesg;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Address Object
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "ADDRESS")
public class Address {
#Id
#Column(name="ADDRESS_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name = "ADDRESS")
private String address;
#OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
#JoinColumn(name="emp_id",referencedColumnName="employee_id")
private Employee employee;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Address() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
My code is
public class StudentUtil1To1 {
public static void main(String args[]){
SessionFactory factory=null;
Configuration configuration=null;
ServiceRegistry registry=null;
Session session=null;
try{
configuration= new Configuration();
configuration.configure();
registry=new StandardServiceRegistryBuilder().configure().applySettings(configuration.getProperties()).build();
factory=configuration.configure("hibernate.cfg.xml").buildSessionFactory(registry);
session= factory.openSession();
session.beginTransaction();
Employee emp=new Employee();
emp.setId(1);
emp.setEmployeeReferenceId("CP001");
emp.setEmployeeName("Muthu");
emp.setEmployeeDesg("Developer");
emp.setSalary("15000");
Address address=new Address();
address.setAddress("3, Civil aerodrome, CBE");
emp.setAddress(address);
address.setEmployee(emp);
session.update(emp);
System.out.println("Successfuly Saved");
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null){
session.close();
}
if(factory!=null){
factory.close();
}
}
}
}
And the error is
09:40:48.815 [http-nio-8081-exec-7] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 1048, SQLState: 23000
09:40:48.816 [http-nio-8081-exec-7] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Column 'emp_id' cannot be null
What i need to for update. Correct my mistake.
Since you have already mapped Address entity in employee entity like this
#OneToOne(mappedBy="employee", cascade = CascadeType.ALL)
private Address address;
You dont have to do same thing in address class means
#OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
#JoinColumn(name="emp_id",referencedColumnName="employee_id")
private Employee employee;
Above code is not required in address entity.And remove the employee attribute from address class.
Now you already added the CascadeType.ALL in OneToOne annotation and save only employee object like this
Employee emp=new Employee();
Address address=new Address("your address");
emp.setAddress(address);
emp.setId(1);
emp.setEmployeeReferenceId("CP001");
emp.setEmployeeName("Muthu");
emp.setEmployeeDesg("Developer");
emp.setSalary("15000");
session.update(emp);
1.#MapppedBy annotation means:the entity annotationed by #MapppedBy,give up the reference of key,so in the employee table,dont have the column named "address_id".
the relation between Employee and Address controlled by "address" table.
2. when you use [session.update(emp);],you havent have the data of "Employee" table.but emp_id is the FOREIGN KEY,so will occur this problem
3. i can first insert Employee,then [session.update(emp);]

do i need extra coding in java side for hibernate one-to-many annotations

Here are my hibernate classes
package com.vaannila.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.web.bind.annotation.ModelAttribute;
#Entity
#Table(name = "countries")
public class Country {
#Id
#Column(name = "country_id")
#GeneratedValue
private Integer country_id;
#Column(name = "country_name")
private String country_name;
public Country(Integer country_id , String name ){
this.country_name = name;
this.country_id = country_id;
}
/**
* #param country_id the country_id to set
*/
public void setCountry_id(Integer country_id) {
this.country_id = country_id;
}
/**
* #return the country_id
*/
public Integer getCountry_id() {
return country_id;
}
/**
* #param country_name the country_name to set
*/
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
/**
* #return the country_name
*/
public String getCountry_name() {
return country_name;
}
}
Person java
package com.vaannila.domain;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
/**
* A simple POJO representing a Person
*/
#Entity
#Table(name = "PERSON")
public class Person implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
#Id
#Column(name = "ID")
#GeneratedValue
private Integer id;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "MONEY")
private Double money;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "person_countries", joinColumns = { #JoinColumn(name = "person_id") },
inverseJoinColumns = { #JoinColumn(name = "country_id") })
private List<Country> student_countries ;
public List<Country> getStudent_countries() {
return this.student_countries;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
jsp form
<tr><td>Country :</td>
<td><form:checkboxes path="student_countries" items="${countryList}" itemValue="country_id" itemLabel="country_name" /></td>
</tr>
</table>
DAO Logic
public void add(Person person) {
logger.debug("Adding new person");
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
// Save
session.save(person);
}
But my countries are not added in the database, all other things go in person table but not in relationship table.
Tested your code, works for me. Make sure your config settings are correct and not overridden.
I guess that the probem is that you do not have a 1:n Releationship, you have a n:m! Because your person have many studend contryies, and I guess that every country can have more than one person.
So replace the #OneToMany(cascade = CascadeType.ALL) in Person by an #ManyToMany relationship.

Categories