Spring Data JPA Join Issue



我有以下实体:

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

TestEntity

@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。mysqlsyntaxerrorexcexception:字段列表中未知列' comments_1_1 .comments_test_id'

有人能指出我这样做是正确的吗?

我认为你应该改正:

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

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

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

最新更新