我在hibernate中遇到过一个场景,我试图寻找这样的场景讨论,但我无法在这里争取任何建议或帮助,
我有三个表类别,category_artical,artical。
CREATE TABLE `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(45) NOT NULL,
`category_description` varchar(45) NOT NULL,
PRIMARY KEY (`category_id`)
);
CREATE TABLE `article` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(70) NOT NULL,
`description` varchar(250) NOT NULL,
`keywords` varchar(150) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`article_id`)
);
CREATE TABLE `category_article` (
`category_id` int(11) NOT NULL,
`article_id` int(11) NOT NULL,
'category_article_status' varchar(1) NOT NULL.
'category_article_type' varchar(2) NOT NULL,
PRIMARY KEY (`category_id`,`article_id`),
UNIQUE KEY `article_id_UNIQUE` (`article_id`),
KEY `fk_category` (`category_id`),
KEY `fk_article` (`article_id`),
CONSTRAINT `fk_article` FOREIGN KEY (`article_id`) REFERENCES `article` (`article_id`),
CONSTRAINT `fk_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`)
);
我有类别的实体,
@Entity
@Table(name = "CATEGORY")
public class Category {
private long id;
private String name;
@Id
@GeneratedValue
@Column(name = "CATEGORY_ID")
public long getId() {
return id;
}
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "CATEGORY_ARTICLE",`enter code here`
joinColumns = @JoinColumn(name = "CATEGORY_ID"),
inverseJoinColumns = @JoinColumn(name = "ARTICLE_ID")
)
private Set<Article> articles;
// other getters and setters...
/*For Article entity is */
@Entity
@Table(name = "ARTICLE")
public class Article {
private long id;
private String title;
private String description;
private String keywords;
private String content;
@Id
@GeneratedValue
@Column(name = "ARTICLE_ID")
public long getId() {
return id;
}
// other getters and setters...
对于category_article,我没有实体,因为我在类别中使用@jointable 所以一切正常,直到我在category_article中只有两列是category_id和article_id。但是,一旦我添加了两个列,我就会混淆如何在那些非空的数据库(category_article_status和category_article_type)中输入数据。
对此有任何建议。
答案 0 :(得分:0)
您应该像这样为CATEGORY_ARTICLE
创建另一个实体。
@Entity
@Table(name = "CATEGORY_ARTICLE")
public class CategoryArticle{
@Id
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "category_id")
private Category category;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "article_id")
private Article article;
// other columns
private Boolean categoryArticleStatus;
private Long categoryArticleType;
}
也应该更改Category
和Article
。从类别实体中删除JoinTable
并将其更改为以下。
<强>分类强>
@Entity
@Table(name = "CATEGORY")
public class Category {
//.....
@OneToMany(mappedBy = "category")
private Set<CategoryArticle> categoryArticleSet;
}
文章
@Entity
@Table(name = "ARTICLE")
public class Article {
//.....
@OneToMany(mappedBy = "article")
private Set<CategoryArticle> categoryArticleSet;
}