【问题标题】:How to save in database a hierarchy class?如何在数据库中保存层次结构类?
【发布时间】:2014-07-01 08:12:29
【问题描述】:

我使用 Java 和 Hibernate 将我的实体保存在数据库中,但它没有按需要工作。 我有一个实体企业:

@Entity
public class Entreprise{

@Id
private long identifier;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Person>  persons;

...
// getters and setters

} 

这里的Person实体是其他实体的超类:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person{

@Id
private long identifier;

@Column
private String name;

...
 // constructors,getter and setter

} 

还有我的两个子类:

@Entity
public class Employed extends Person{

 @Column
 private String actualJob;

 // constructors,getter and setter
}


@Entity
public class Unemployed extends Person{

 @Column
 private String lastJob;

// constructors,getter and setter
}

这是我在数据库中保存实体的方法:

Person person = new Employed();
person.setName("John");
Employed employed = (Employed) person;
employed.setActualJob("electrician");
Entreprise myEntreprise = new Entreprise();
entreprise.getPersons().addPerson(person);
entrepriseDao.save(entreprise);

但是在数据库中,插入只是在表 Entreprise 和 Person 中进行的。 Employed 表中没有插入任何内容。我不知道为什么有人可以解释一下吗?

我尝试下面的代码也不行:

Employed employed = new Employed();
employed.setActualJob("electrician");
employed.setName("John");
Entreprise myEntreprise = new Entreprise();
entreprise.getPersons().addPerson(employed);
entrepriseDao.save(entreprise);

我不明白为什么即使我使用子类来设置数据它也不起作用。

这里是ddl

Hibernate: insert into Entreprise_Person (Entreprise_identifier, person_identifier) values (?, ?);

【问题讨论】:

  • 请显示 SQL 的 DDL。

标签: java hibernate inheritance


【解决方案1】:

您正在向企业列表添加人员参考:

entreprise.getPersons().addPerson(person);

这样做,您只添加个人数据,而不是扩展雇员的数据。您应该添加使用的对象。

【讨论】:

    【解决方案2】:

    尝试将@PrimaryKeyJoinColumn(name = "YOUR_SUBCLASS_ID_FIELD_THAT_WILL_MATCH_THE_SUPERCLASS_ID_FIELD") 添加到所有子类。

    子类也需要标识符,这是它们链接到超类记录的方式。

    @Entity
    @PrimaryKeyJoinColumn(name = "identifier")
    public class Employed extends Person{
    
     @Id
     private long identifier;
    
     @Column
     private String actualJob;
    
     // constructors,getter and setter
    }
    
    
    @Entity
    @PrimaryKeyJoinColumn(name = "identifier")
    public class Unemployed extends Person{
    
     @Id
     private long identifier;
    
     @Column
     private String lastJob;
    
    // constructors,getter and setter
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 2013-08-08
      • 2020-12-01
      • 2020-03-10
      • 2021-04-04
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多