JPA: @JoinTable - Both columns are Primary Keys.. How do I stop that?

≯℡__Kan透↙ 提交于 2019-12-01 09:53:32

问题


This is my annotation I use to generate my Join Table.

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "service_operations", 
        joinColumns = { @JoinColumn(name = "serviceId") },
        inverseJoinColumns = { @JoinColumn(name = "operationId") })
public Set<Operation> getOperations() {
    return operations;
}

Considering this is a OneToMany association, my natural assumption is that this table would generate a

[ Primary Key | Foreign Key ] table, however everytime I drop and re create the database it is not the case:

mysql> describe workflow_services;
+-------------+------------+------+-----+---------+-------+
| Field       | Type       | Null | Key | Default | Extra |
+-------------+------------+------+-----+---------+-------+
| workflow_id | bigint(20) | NO   | PRI | NULL    |       |
| service_id  | bigint(20) | NO   | PRI | NULL    |       |
+-------------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Im a tad baffled by this. Any suggestions?


回答1:


This looks correct to me. Each row in the join table should identify a pair of workflow/service items. So (workflow_id, service_id) should be the primary key. Also workflow_id should be a foreign key into the workflow table and service_id should be a foreign key into the service table.

Also note that a one-to-many association between A and B does not mean that an instance of A can have the same instance of B multiple times, rather an instance of A can have multiple distinct instances of B. For example a blog Post entity can have a one-to-many association with a Tag entity. This means that a blog Post P1 can have multiple tags Java, JPA, JavaEE, but can not have the same tag multiple times.




回答2:


I fixed my problem by adding the following changes:

I changed my @OneToMany to a @ManyToMany annotation

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "workflow_services", 
        joinColumns = @JoinColumn(name = "workflow_id"), 
        inverseJoinColumns = @JoinColumn(name = "service_id"))
public Set<Service> getServices() {
    return services;
}

I added a Set workflows; association in my Service object

@ManyToMany(mappedBy="services")  // map info is in person class
public Set<Workflow> getWorkflows() {
    return workflows;
}


来源:https://stackoverflow.com/questions/7615859/jpa-jointable-both-columns-are-primary-keys-how-do-i-stop-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!