2283

Hibernate - Foreign key is empty while using mappedBy

Question:

I've 2 tables Employee & Vehicle, where one employee can have multiple vehicles. Below is the mapping that I've defined:

<strong>Employee.java</strong>

@Entity(name = "emp_details") public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int empId; @OneToMany(cascade = CascadeType.ALL, mappedBy="employee") private List<Vehicle> vehicles = new ArrayList<>(); public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public List<Vehicle> getVehicles() { return vehicles; } public void setVehicles(List<Vehicle> vehicles) { this.vehicles = vehicles; } }

<strong>Vehicle.java</strong>

@Entity public class Vehicle { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int vehicleId; @ManyToOne @JoinColumn(name="empId") private Employee employee; private String name; public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public int getVehicleId() { return vehicleId; } public void setVehicleId(int vehicleId) { this.vehicleId = vehicleId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

<strong>Main class</strong>

public class HibernateTest { public static void main(String[] args) { Employee emp = new Employee(); Vehicle vehicle = new Vehicle(); vehicle.setName("Honda"); emp.getVehicles().add(vehicle); SessionFactory sFactory = new Configuration().configure().buildSessionFactory(); Session session = sFactory.openSession(); session.beginTransaction(); session.save(emp); session.getTransaction().commit(); session.close(); StandardServiceRegistryBuilder.destroy(sFactory.getSessionFactoryOptions().getServiceRegistry()); } }

But when I execute this, Vehicle.employee_id is empty. I was expecting that my foreign key will be inserted there.

<a href="https://i.stack.imgur.com/l2oOz.jpg" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/l2oOz.jpg" data-original="https://i.stack.imgur.com/l2oOz.jpg" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

What am I missing?

Thank You

Answer1:

You need to show us the code that persists your entities, but my guess is that you are not setting the employee to the vehicle.

You need to manage both sides of bidirectional entity relationship. Your code should look something like this

employee.getVehicles().add(vehicle); vehicle.setEmployee(employee); session.save(employee);

<strong>UPDATE:</strong>

In this case, Vehicle is the owning side of the relation because the foreign key is in its database table. You just added the new vehicle to the employee's list of vehicles. When you save the employee, there's nothing to change in Employees database, and the save operation cascades to Vehicle. Vehicle does not have its employee set, it is null, so it puts null in empId column

Bottom line, you have to make sure both sides of bidirectional relationship are wired up correctly.

Answer2:

If you have a bidirectional relationship you have to set the relation on both sides.

That means you have to set the employee for your vehicle also.

You can do this by calling

vehicle.setEmployee(emp);

and then store or update your entity (if it's not attached to session already).

Usually to set a bidirectional relationship you provide special methods in your entities.

public class Vehicle { ... public void setEmployee(Employee employee) { this.employee = employee; employee.addVehicle(this) } ... } public class Employee { ... public void addVehicle(Vehicle v) { if(!vehicles.contains(v)) { vehicles.add(v); } if(!this.equals(v.getEmployee()) { v.setEmployee(this); } } ... }

Answer3:

In your Employee entity class, you haven't used @Column annotation on empId. In Vehicle class you are referencing Employee using @JoinColumn(name="employee_id"),so column <strong>employee_id</strong> must exist in emp_details table. So you need to modify your Employee class to something with

@Id @GeneratedValue @Column(name="employee_id") private int empId;

Answer4:

I think need to edit your code. you miss the entity jpa rule. you can some search jpa entity. you read description for you. link : <a href="http://www.tutorialspoint.com/jpa/index.htm" rel="nofollow">enter link description here</a>

(Modified your Employee.java)

@Entity(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int idx; @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "employee") private List<Vehicle> vehicle = new ArrayList<>(); ... }

(Modified your Vehicle.java)

@Entity public class Vehicle { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int idx; @ManyToOne @JoinColumn(name="employee_id") private Employee employee; ... }

Answer5:

You only need to cascade onetoMany from Employee Entity

Recommend

  • Android Intent to open Email application from separate class?
  • Include code in ASP.net
  • Java shuffle card deck
  • Custom login mechanism for a ASP.NET website
  • android: How to use asyncTask in Rest Web service?
  • TOO MANY THREADS ERROR EXCEPTION
  • EF Core to Mysql table binding
  • Reading data from a text file to compute and write the data in another text file
  • How do I store an object in ArrayList? [closed]
  • How to test a web api post method which receives a class
  • AlarmManager wont fire pending intent
  • Accessing controls between forms
  • ActionScript - Access List/DataProvider From Custom CellRenderer
  • remove row from another activity
  • retrofit 400 Bad Request
  • ListView to open hyperlinks in android
  • Why can't I catch EJB exceptions?
  • Problem serializing DecimalFormatSymbols in 2.3.4
  • Issue with static code in Android
  • renaming sheets with “full sheet” charts on them causes spreadsheet to reload
  • Cannot use an @IdClass attribute for a @ManyToOne relationship
  • Android getAssets in Common class gives “The method getAsssets() is undefined for the type Context”
  • Sort an arraylist of objects in java
  • Append Textarea result from another class
  • Problem with rejecting incoming call
  • $wpdb not working in file of WordPress plugin
  • why overloaded new operator is calling constructor even I am using malloc inside overloading functio
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • how to adjust image in a panel in Java swing?
  • Why value captured by reference in lambda is broken? [duplicate]
  • req.body is undefined - nodejs
  • Possible to stop flickering java tooltip in heavyweight mode?
  • output of program is not same as passed argument
  • sending/ receiving email in Java
  • Akka Routing: Reply's send to router ends up as dead letters
  • How to delete a row from a dynamic generate table using jquery?
  • Proper way to use connect-multiparty with express.js?
  • Getting error when using KSoap library to consume .NET web services
  • unknown Exception android
  • Checking variable from a different class in C#