spring-boot - 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”
有人可以指出我这样做是否正确吗?
解决方案
我认为你应该纠正这个:
@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 映射,则外键位于目标实体的表中。
- 如果连接是针对多对多映射或单对一或使用连接表的双向多对一/单对多映射,则外键位于连接表中。
- 如果连接用于元素集合,则外键位于集合表中。
推荐阅读
- postgresql - 将 PostgreSQL int[] 数组映射到 Java 实体中的 List
- typescript - 在@Component 中使用 vue mixin
- cordova - 如何在 Ionic 中使用 Google Play Install Referrer API?
- python - Tensorflow 2 Keras 的 Pearson 相关指标
- java - 用于自动创建 windows vm 密码的谷歌云功能
- azure - 如何在 Azure Databricks 中升级 Hive 版本
- xamarin - iOs App 被 Apple 拒绝 - 在使用“grep -r UIWebView”时未获取使用 UIWebview 的包
- html - &:focus on input 不会改变元素
- android - 如何修改部分图像视图?
- reactjs - React Hooks - UseState - 将对象从子级传递给父级