我有两张桌子:
主题表:
CREATE TABLE `topics` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`topicId` varchar(45) NOT NULL,
`title` text NOT NULL,
`details` text,
`dayPosted` varchar(45) DEFAULT NULL,
`username` varchar(45) DEFAULT NULL,
`userImage` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8;
评论表:
CREATE TABLE `comments` (
`commentId` int(11) NOT NULL,
`topicId` varchar(45) NOT NULL,
`comments` text,
`commentDate` varchar(45) DEFAULT NULL,
PRIMARY KEY (`commentId`),
KEY `topicId_idx` (`topicId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
topicId
列在两个表中都很常见,我想在两个表之间创建关系。问题是topicId不是主键(我可以使它成为唯一的)
或者我创建第三个表格,如topics_comments
并同时拥有:
实际情况是我有博客发布网站,用户将在该博客上发表评论,其中每个博客主题都有topicId
,每个用户评论都有commentId
,现在我根据条件创建了表: / p>
我正在使用mysql与 spring boot 和 spring jpa
实体类:
@Entity
@Table(name = "topics")
public class TopicBean implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "topicId")
private String topicId;
@Column(name = "title")
private String title;
@Column(name = "details")
private String details;
@Column(name = "username")
private String username;
@Column(name = "userImage")
private String userImage;
@Column(name = "dayPosted")
private String dayPosted;
//Getters and setters
}
答案 0 :(得分:0)
您可以坚持使用当前架构,并且仍然可以使用JPA定义工作映射。这是在当地环境中为我工作的设置(这里只有重要的部分):
<强>主题强>
@Entity
@Table(name = "topics")
public class Topic implements Serializable {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "topicId")
private Integer topicId;
@OneToMany(mappedBy = "topic", cascade = {CascadeType.REMOVE, CascadeType.MERGE})
private List<Comment> comments;
<强>评论强>
@Entity
@Table(name = "comments")
public class Comment implements Serializable{
@Id
@Column(name = "commentId")
private Integer commentId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "topicId", referencedColumnName = "topicId")
private Topic topic;
请记住在TOPICS.topicsId上添加唯一索引。
关于链接表方案,如果您确实如此,我会使用它:
加号当然是你要正确加入,即使用主键,所以决定取决于你。以下是映射:
<强>主题强>
@Entity
@Table(name = "topics")
public class Topic implements Serializable {
@Id
@Column(name = "id")
private Integer id;
@ManyToMany
@JoinTable(name="COMMON",
joinColumns=@JoinColumn(name="TOPIC_ID"),
inverseJoinColumns=@JoinColumn(name="COMMENT_ID"))
private List<Comment> comments;
<强>评论强>
@Entity
@Table(name = "comments")
public class Comment implements Serializable{
@Id
@Column(name = "commentId")
private Integer commentId;
@ManyToMany
@JoinTable(name="COMMON",
joinColumns=@JoinColumn(name="COMMENT_ID"),
inverseJoinColumns=@JoinColumn(name="TOPIC_ID"))
private Topic topic;