hibernate中数据库表多对多关系,一般会把多对多分割成2个一对多,而单向关联比较多!
新闻类:
@Entity
@Table(name = "news")
public class News implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "title")
private String title;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="news")
private Set<TopNews> topnews = new HashSet<TopNews>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<TopNews> getTopnews() {
return topnews;
}
public void setTopnews(Set<TopNews> topnews) {
this.topnews = topnews;
}
}
主题类:
@Entity
@Table(name = "topic")
public class Topic implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name="code")
private String code;
//@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="news")
//private Set<TopNews> topnews = new HashSet<TopNews>();
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
中间表类:
@Entity
@Table(name = "topic_news")
public class TopNews implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(cascade=CascadeType.ALL,optional=false)
@JoinColumn(name="news_id",referencedColumnName="id")
private News news;
@ManyToOne(cascade=CascadeType.ALL,optional=false)
@JoinColumn(name="topic_id",referencedColumnName="id")
private Topic topic;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public News getNews() {
return news;
}
public void setNews(News news) {
this.news = news;
}
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
}
测试代码:
Topic topic1 = new Topic() ;
topic1.setCode("economic");
testService.saveEntity(topic1);
News news1 = new News();
news1.setTitle("今日新闻");
TopNews topnews1 = new TopNews();
topnews1.setNews(news1);
topnews1.setTopic(topic1);
news1.getTopnews().add(topnews1);
testService.createNews(news1);