Hibernate多对多

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值