2017-10-10 209 views
0

我的数据库包含公司和员工。我将员工建模为公司的弱实体。使用JPA映射弱实体

我的JPA注释是这样的:

@Entity 
public class Company extends Model { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    public Long id; 

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL) 
    private List<Employee> employees; 

} 

Employee.java:

@Entity 
public class Employee extends Model { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    public Long id; 

    @ManyToOne(optional = false) 
    @JoinColumn(name="company_id", insertable=false, updatable=false) 
    private Company company; 
} 

下面的SQL代码创建:

create table employee (
    id       bigint auto_increment not null, 
    company_id     bigint not null, 
    constraint pk_employee primary key (id) 
); 

alter table employee add constraint fk_employee_company_id foreign key (company_id) references company (id) on delete restrict on update restrict; 

我要的是(约束pk_employee主键(编号,company_id):

create table employee (
    id       bigint auto_increment not null, 
    company_id     bigint not null, 
    constraint pk_employee primary key (id, company_id) 
); 

alter table employee add constraint fk_employee_company_id foreign key (company_id) references company (id) on delete restrict on update restrict; 

有没有办法创建这样的SQL脚本?

编辑:Employee实施Serializable不会做的伎俩。

Caused by: javax.persistence.PersistenceException: Could not find BeanDescriptor for class models.Company. Perhaps the EmbeddedId class is not registered? 
    at io.ebeaninternal.server.deploy.BeanEmbeddedMetaFactory.create(BeanEmbeddedMetaFactory.java:26) 
    at io.ebeaninternal.server.deploy.BeanPropertyAssocOne.<init>(BeanPropertyAssocOne.java:79) 
    at io.ebeaninternal.server.deploy.BeanPropertyAssocOne.<init>(BeanPropertyAssocOne.java:62) 
    at io.ebeaninternal.server.deploy.meta.DeployBeanTable.createProperty(DeployBeanTable.java:68) 
    at io.ebeaninternal.server.deploy.meta.DeployBeanTable.createIdProperties(DeployBeanTable.java:59) 
    at io.ebeaninternal.server.deploy.BeanTable.<init>(BeanTable.java:42) 
+1

为什么你需要这个? –

+1

“弱实体”是什么意思? –

+1

你正在寻找的是员工的综合PK。这是相当标准的,并在这里概述了选项:https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Composite_Primary_Keys –

回答

0

只需添加您的@JoinColumn注释下@Id注释。但Employee类必须使用implements Serializable这个解决方案。

+0

不幸的是它不起作用。 我已添加错误消息。 – mollwitz