保存从实体扩展的实例

时间:2017-05-22 18:14:59

标签: java spring hibernate jpa hibernate-mapping

我有一个定义员工表的实体。对于项目结构,有一些子类,如"EmployeeTrn""EmployeeBck",...,它们只是从Employee超类扩展而来。所有属性和方法都完全相同。

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;

   @Column(name = "first_name")
   private String firstName;

   @Column(name = "last_name")
   private String lastName;

   @Column(name = "salary")
   private int salary;  

   public Employee() {}
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

扩展子类如下所示。

public class EmployeeTrn extends Employee{
        public EmployeeTrn(){
            id = Builder.generateSSI();
            firstName = Helper.fetchFromLocal("8091").name();
            lastName = Helper.fetchFromLocal("8091").surname();
        }
    }


public class EmployeeBck extends Employee{
            public EmployeeBck(){
                id = Builder.generateSSIFromHost("localhost:8091");
                firstName = Helper.fetchFromAWS("/token.dat").name();
                lastName = Helper.fetchFromAWS("/token.dat").surname();
            }
        }

我已经在配置xml文件上映射了Employee实体。但是当我尝试保存从Employee扩展的类时,会出现问题

session.saveEmployee(employeeTrn);

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.company.EmployeeTrn

任何人都可以帮助我吗?我被卡住了。

2 个答案:

答案 0 :(得分:1)

你的子类实体也应该被定义为实体,因为你没有定义你的继承类型,继承策略将是单个表,这意味着你的超级类和它的孩子将被映射到同一个table,所以你应该定义子类的实体是有道理的。

@Entity
public class EmployeeTrn extends Employee{
    public EmployeeTrn(){
        id = Builder.generateSSI();
        firstName = Helper.fetchFromLocal("8091").name();
        lastName = Helper.fetchFromLocal("8091").surname();
    }

答案 1 :(得分:0)

Hibernate无法识别实体。因此,您还需要映射 EmployeeTrn 实体:

请参阅继承配置:http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#entity-inheritance