首页 > 解决方案 > @ManyToOne 映射没有中间表的实体

问题描述

我正在编写一个将查询无法更改的大型数据库的应用程序。

出于这个原因,我的应用程序不需要映射所有对象,因为那将是无用且耗时的。

那里映射的所有实体都是@Immutable.

我遇到了这种关系:

数据库

我想映射Order,并让它参考Customer。事实上,这是一个多对一的关系,它只是发生在两个连接子句之外。

我对既不感兴趣也不感兴趣RB因为它们没有传达与我的要求相关的信息。

我设想这样的事情,但我知道语法是无效的:

@Entity
@Immutable
@Table(name = "Order")
public class Order implements Serializable {
    
   @Id
   @Column(name = "id")
   private Long id;

   @ManyToOne
   @JoinColumns(value = 
              @JoinColumn(table = "R", name = "id", referencedColumnName = "R_id"),
                @JoinColumn(table = "Customer", name = "id", referencedColumnName = "Customer_id")
    )
    private Customer customer;
    
    ... more data and getters/setters omitted ...
}
    
    
@Entity
@Immutable
@Table(name = "Customer")
public class Customer implements Serializable {
    
   @Id
   @Column(name = "id")
   private Long id;
    
    
   ... more data and getters/setters omitted ...
}

有没有办法可以做到这一点,而无需创建实体R

编辑: - - - - - - - - - - - - -

根据建议,我尝试了以下方法:

@ManyToOne
@JoinTable(name = "R",
     joinColumns = @JoinColumn(name = "id", referencedColumnName = "R_id"),
     inverseJoinColumns = @JoinColumn(name = "id", referencedColumnName = "Customer_id"))
private Customer customer;

但是,我收到以下错误:

Unable to find column with logical name: R_id in org.hibernate.mapping.Table(Order) and its related supertables and secondary tables

标签: databasehibernatejpaspring-data-jpa

解决方案


您可以将@JoinTable注释用于以下模式。

ManyYoOneWithIntermTable

这样

@Entity
@Table(name = "Order")
public class Order {

    // ...

    @ManyToOne
    @JoinTable(
        name = "R",
        joinColumns = @JoinColumn(name = "ord_id"),
        inverseJoinColumns = @JoinColumn(name = "customer_id"))
    private Customer customer;

    // ...
}

但是对于您的情况,R由于.OrderR


推荐阅读