【问题标题】:Hibernate/JPA incorrect join in Spring Boot Application在 Spring Boot 应用程序中,Hibernate/JPA 不正确加入
【发布时间】:2017-07-19 11:32:24
【问题描述】:

请参阅下面的代码了解我的 2 个实体类 - 当我从 OrigRepository 类调用 findAll() 方法时,它使用两个主键连接这两个表。我希望连接在 Orig 表的主键和 MsgResponse 表中的外键条目(“OrigID”)之间 - 有什么建议吗?

原始实体

@Entity
@Table(name = "originator")
public class Orig {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "OrigID")
    private int OrigID;

    @OneToOne(cascade = CascadeType.ALL) 
    @JoinColumn(name = "OrigID")  
    private MsgResponse responseInfo;
}

MsgResponse 实体

@Entity
@Table(name = "message_response")
public class MsgResponse {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private int responseId;

    @Column(name = "OrigID")
    private int OrigId;

    @OneToOne(mappedBy="responseInfo")
    private Orig OrigInfo; 
}

【问题讨论】:

    标签: java mysql spring hibernate jpa


    【解决方案1】:

    我建议您查看 jpa 文档 here.

    示例 1 应该是您的情况

    【讨论】:

    • 感谢您的回复。尝试遵循这个,现在这些表根本没有加入。我是否需要在我的 (Spring Boot) 应用程序的其他地方配置关系?
    【解决方案2】:

    尝试交换关系所有权,即:

    @Entity
    @Table(name = "originator")
    public class Orig {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "OrigID")
        private int OrigID;
    
        @OneToOne(mappedBy="origInfo") 
        private MsgResponse responseInfo;
    }
    
    @Entity
    @Table(name = "message_response")
    public class MsgResponse {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID")
        private int responseId;
    
        // @Column(name = "OrigID")
        // private int origId;
    
        @OneToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "OrigID")  
        private Orig origInfo; 
    }
    

    请注意,@JoinColum 注释现在位于 MsgResponse 实体中。这是因为在 @OneToOne 中,连接列引用 source 实体(请参阅 here)。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 2019-01-22
      • 2018-09-24
      • 2017-11-20
      • 2020-04-17
      • 2017-07-02
      相关资源
      最近更新 更多