首页 > 解决方案 > Spring Data JPA 加入问题

问题描述

我有以下实体:

测试评论实体

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

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

测试评论实体PK

@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:“字段列表”中的未知列“comments1_.comments_test_id”

有人可以指出我这样做是否正确吗?

标签: spring-boothibernatejpaspring-data-jpa

解决方案


我认为你应该纠正这个:

@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;

因为根据文档

姓名

公共抽象 java.lang.String 名称

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

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

推荐阅读