持久化@OneToMany后,子表中的外键为null

时间:2017-12-21 21:12:11

标签: java mysql spring hibernate hibernate-mapping

我试图将数据插入到@OneToMany关系的表中。在子表中持久保存外键是null

方案是:一个Employee可以有多个Address es。

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

1 个答案:

答案 0 :(得分:0)

添加

a.setEmployee(e)

在你的考试中。你必须明确地设置它