Hibernate中ManyToOne,OneToMany,OneToOne的使用例

时间:2021-03-05 15:21:18

有3个表:
News:新闻表
NewsResource:新闻附件表
Resource:资源表

表关系:
1个新闻(News)对应多条新闻附件(NewsResource)
News:ID  <--->  NewsResource:news_id

1个新闻附件(NewsResource)对应1个资源(Resource)。
NewsResource:resource_id  <--->  Resource:ID

实体类如下:

News:
@Entity@Table(name="news")public class NewsEntity implements Serializable{    private static final long serialVersionUID = 48L;    @Id	    @GeneratedValue    @Column(name="ID")    private Long id;    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="news")    private Set<NewsResourceEntity> newsResource;    //其他内容省略}


NewsResource:
关于NewsResource表,有两种写法:
方法1:
这种写法用于不想和news表做级联更新,只想做级联查询的情况。news_id和resource_id都定义了2次,上面@Column用于自己表的更新,下面的@JoinColumn用于级联查询的时候的Join列。

@Entity
@Table(name="newsresource")
public class NewsResourceEntity implements Serializable{
private static final long serialVersionUID = 48L;

@Id
@GeneratedValue
@Column(name="ID")
private Long id;

@Column(name = "news_id")
private Long newsId;

@Column(name = "resource_id")
private Long resourceId;

@ManyToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="news_id", insertable = false,updatable = false)
private NewsEntity news;

@OneToOne(optional = false, cascade = CascadeType.MERGE)
@JoinColumn(name = "resource_id", referencedColumnName = "id", unique = true, insertable = false,updatable = false)
private ResourceEntity resource;

//其他内容省略
}

方法2:
这种写法就是典型的级联查询+级联更新。

<pre name="code" class="java">@Entity
@Table(name="newsresource")
public class NewsResourceEntity implements Serializable{
private static final long serialVersionUID = 48L;

@Id
@GeneratedValue
@Column(name="ID")
private Long id;

@ManyToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="news_id")
private NewsEntity news;

@OneToOne(optional = false, cascade = CascadeType.MERGE)
@JoinColumn(name = "resource_id", referencedColumnName = "id", unique = true)
private ResourceEntity resource;

//其他内容省略
}
 
Resource: 
 
 
 
 
 
@Entity
@Table(name="resource")
public class ResourceEntity implements Serializable {
private static final long serialVersionUID = 48L;

@Id
@GeneratedValue
@Column(name="ID")
private Long id;

@OneToOne(optional = true, cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy = "resource")
private NewsResourceEntity newsResource;

//其他内容省略
}

另外,懒加载(LAZY)如果遇到问题,请参照相关文章:
http://blog.csdn.net/sunroyi666/article/details/51890571