Внешний ключ в дочерней таблице является нулевым после сохранения @OneToMany

0

Я пытаюсь вставить данные в таблицы, которые имеют отношения @OneToMany. После сохранения внешнего ключа в дочерней таблице значение null.

Сценарий: один Employee может иметь много Address.

Address.java

@Entity
@Table(name = "address")
public class Address {

   @Id
   @GenericGenerator(name = "incgenerator", strategy = "increment")
   @GeneratedValue(generator = "incgenerator")
   private int id;
   private String city;
   private int zipCode;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "empId")
   private Employee employee;

   // getters, setterd
}

Employee.java

@Entity
@Table(name = "employee")
public class Employee {

   @Id
   @GenericGenerator(name = "incgenerator", strategy = "increment")
   @GeneratedValue(generator = "incgenerator")
   private int id;
   private String name;

   @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
   private Set<Address> address;

   // getters, setters
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property 
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property 
name="hibernate.connection.url">jdbc:mysql://localhost/retail</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property 
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.show_sql_format">true</property>

    <mapping class="TestModel.Employee"/>
    <mapping class="TestModel.Address"/>
</session-factory>
</hibernate-configuration>

Test.java

public class Test {

   public static void main(String[] args) {

      Configuration c = new Configuration();
      c.configure("resources/hibernate.cfg.xml");

      SessionFactory sf = c.buildSessionFactory();
      Session s = sf.openSession();

      Transaction t = s.beginTransaction();

      Employee e = new Employee();
      e.setName("Farhaan");

      Address a = new Address();
      a.setCity("Kolonnawa");
      a.setZipCode(123);

      Set<Address> aa = new HashSet();
      aa.add(a);

      e.setAddress(aa);

      s.saveOrUpdate(e);

      t.commit();
   }
}
Теги:
spring
hibernate
hibernate-mapping

1 ответ

0
Лучший ответ

Добавить еще

a.setEmployee(e)

в вашем тесте. Вы должны установить его явно

  • 0
    Это сработало, спасибо! Плохо, что я забыл это сделать.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню