【问题标题】:Foreign key in the child table is null after persisting @OneToMany持久化@OneToMany 后子表中的外键为空
【发布时间】:2018-06-04 14:12:45
【问题描述】:

我正在尝试将数据插入到具有@OneToMany 关系的表中。将子表中的外键持久化后为null

场景是:一个Employee可以有多个Addresses。

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

【问题讨论】:

    标签: java mysql spring hibernate hibernate-mapping


    【解决方案1】:

    添加

    a.setEmployee(e)
    

    在您的测试中。您必须明确设置它

    【讨论】:

    • 成功了,谢谢!可惜我忘了这样做。
    猜你喜欢
    • 1970-01-01
    • 2022-07-29
    • 2017-04-20
    • 1970-01-01
    • 2020-09-14
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    相关资源
    最近更新 更多