java - 加入具有复杂关联表​​的 JPA 实体而不创建关联实体?

标签 java sql-server hibernate

我正在尝试使用不太简单的关联表在两个 JPA 实体之间进行多对多联接。我想知道是否有一种方法可以在不创建关联表实体的情况下实现此目的(类似于使用@JoinTable)。

数据库架构

表A
- ID (PK)
- 姓名

表B
- ID (PK)
- 姓名

表格映射
- ID (PK)
- Parent_ID (FK) --> TableMapping.ID
- A_ID (FK) --> 表A.ID
- B_ID (FK) --> TableB.ID

示例

TableA  
ID     Name 
-----------------------  
A1     Algebra  
A2     Data Structures  
A3     Economics  

TableB  
ID     Name  
------------------------  
B1     Beginner  
B2     Advanced  

TableMapping  
ID     Parent_ID    A_ID     B_ID  
----------------------------------  
1        NULL       NULL       B1  
2        NULL       NULL       B2 
3         1          A1       NULL  
4         2          A2       NULL  
5         2          A3       NULL  


The mapping is stored the way I described above for reasons I do not know and I cannot change that. It is being used like this in a ton of places and I have to work with the way it is. Essentially, the data in TableMapping can be simplified to something like this.

A_ID    B_ID  
-------------  
 A1      B1
 A2      B2
 A3      B2

From my understanding of the problems, there are two ways of doing this:

  1. Create an entity of the association table and map the two entities with the association table entity. This should work, but it would be great if I can do something like @JoinTable and not have to create an entity for this association table since all it does is map entities in TableA to entities in TableB.
  2. Create a view which simplifies the association between the two tables into a single database row for each mapping as shown above. Use the view in @JoinTable.

Note: To keep the code simple, I have not created any getter / setters or constructors.

Entity Code

@Entity
@Table(name = "TableA")
public class EntityA {

    @Id
    @Column(name = "ID")
    public int id;

    @Column(name = "NAME")
    public String name;

}

@Entity
@Table(name = "TableB")
public class EntityB {

    @Id
    @Column(name = "ID")
    public int id;

    @Column(name = "NAME")
    public String name;

    // Want to add below mapping
    // @ManyToMany
    // @JoinTable or equivalent?? 
    // public Set<EntityA> aEntitySet;
}

我不知道是否有一种方法可以使用这个奇怪的映射表来连接两个实体,而无需创建实体或 View 。有没有办法做到这一点?

最佳答案

您应该首先学习数据库规范化。您应该选择 OneToMany 而不是 ManyToMany。 提示:您可以通过在两个表之间添加另一个表来完成此操作。

此外,您创建的使用 OneToMany 的对象必须是 List 或 Set。 you can look here for OneToMany Annotation

关于java - 加入具有复杂关联表​​的 JPA 实体而不创建关联实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58615413/

相关文章:

java - JFormattedTextField 与 MaskFormatter 和 DateFormat

java - 为什么我的存储过程的日期时间参数被拒绝?

sql - SQL Server 中表变量可以拥有的最大记录数

java - JDBC VS Hibernate

java - 使用 Mockito 和 jUnit5 的 Spring Boot Controller 测试失败,因为 Spring 无法创建加载属性的 Property Service 类的 bean?

java - Hibernate 查询实体中的字符串列表

java - 如何将所有依赖项升级到特定版本

java - 使用 GWT-RPC 与 RequestFactory 来传递大型数组

java - 如何从只有 1 个剩余字节的 ByteBuffer 中获取 Int (Java NIO)

sql-server - 如何将序列号连接到不相关的数据 (SQL Server)