【问题标题】:Spring Data JPA Join IssueSpring Data JPA 加入问题
【发布时间】:2021-10-27 12:42:10
【问题描述】:

我有以下实体:

TestCommentEntity

@Entity
@Table(name = "test_comment")
public class TestCommentEntity {
    @EmbeddedId
    private TestCommentEntityPK testCommentEntityPK;

    @Column(name = "comment", nullable = false)
    private String comment;
}

TestCommentEntityPK

@Data
@Embeddable
public class TestCommentEntityPK implements Serializable {
//This is suppose to be the join between the two tables:
    @Column(name = "test_id", nullable = false)
    private String testId;
    @Column(name = "user_id", nullable = false)
    private String userId;
}

测试实体

@Entity
@Table(name = "test")
public class TestEntity {
    @Id
    @Column(name = "test_id", nullable = false)
    private String testId;

    @Column(name = "user_id", nullable = false)
    private String userId;

    @Enumerated(EnumType.STRING)
    @Column(name = "test_type", nullable = false)
    private TestType testType;

    @Column(name = "active")
    private boolean isActive;

    @Column(name = "quality", nullable = false)
    private TestQuality quality;

    @Column(name = "vote_count")
    private int voteCount;

    @OneToMany(fetch = FetchType.EAGER, targetEntity = TestCommentEntity.class, cascade = CascadeType.ALL)
    @JoinColumn(referencedColumnName = "test_id")
    private List<TestCommentEntity> comments;
}

我有以下存储库:

@Repository
public interface TestRepository extends JpaRepository<TestEntity, String> {
}

与

@Repository
public interface TestCommentRepository extends JpaRepository<TestCommentEntity, TestCommentEntityPK> {
}

每当声明:

testRepository.findById(testId)

正在执行,我收到以下错误:

原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'cmets1_.cmets_test_id' in 'field list'

谁能指出我这样做是否正确?

【问题讨论】:

    标签: spring-boot hibernate jpa spring-data-jpa


    【解决方案1】:

    我认为你应该纠正这个:

    @OneToMany(fetch = FetchType.EAGER, targetEntity = TestCommentEntity.class, cascade = CascadeType.ALL)
    @JoinColumn(referencedColumnName = "test_id")
    private List<TestCommentEntity> comments;
    

    到这里:

    @OneToMany(fetch = FetchType.EAGER, targetEntity = TestCommentEntity.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "test_id")
    private List<TestCommentEntity> comments;
    

    因为根据documentation:

    名字

    公共抽象 java.lang.String 名称

    (可选)外键列的名称。 它所在的表取决于上下文。

    • 如果联接是针对使用外键映射策略的 OneToOne 或 ManyToOne 映射,则外键列在源实体的表中或可嵌入的。
    • 如果连接是针对使用外键映射策略的单向 OneToMany 映射,则外键在目标实体的表中。
    • 如果连接是针对多对多映射或单对一或使用连接表的双向多对一/单对多映射,则外键位于连接表中。
    • 如果连接用于元素集合,则外键位于集合表中。

    【讨论】:

    • 像魅力一样工作!谢谢@SternK
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2017-01-12
    • 2016-04-09
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多