我正在开发一个Hibernate/Spring应用程序来管理一些电影.
课堂电影与班级类型有很多关系.这两个类都使用GeneratedValue注释生成了id.
通过使用@Cascade(CascadeType.SAVE_UPDATE)通过电影对象保存类型我已经对类型的类型属性(例如它的名称;"Fantasy")设置了唯一约束.
我现在要做的是让Hibernate检查是否已经存在类型为"Fantasy"的类型,如果有,请使用该类型的id而不是尝试插入新记录.(后者显然会抛出错误)
最后我需要的是像select-before-update之类的东西,但更像是select-before-save.
Hibernate中有这样的功能吗?
一些代码:
电影课
@Entity
public class Movie {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@Lob
private String description;
@Temporal(TemporalType.TIME)
private Date releaseDate;
@ManyToMany
@Cascade(CascadeType.SAVE_UPDATE)
private Set<Genre> genres = new HashSet<Genre>();
.... //other methods
Run Code Online (Sandbox Code Playgroud)
类型课程
@Entity
public class Genre {
@Column(unique=true)
private String type;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id
....//other methods
Run Code Online (Sandbox Code Playgroud)
你可能在想这个.任何select-before-update/select-before-save选项将导致2个DB往返,第一个用于select,第二个用于插入(如果需要).
如果你知道从一开始你就不会有很多类型,那么在大多数情况下你可以在1 RT中做到这一点:
但实际上,除非您谈论大量事务,否则在保存/更新之前进行简单的预查询不会影响您的性能.
| 归档时间: |
|
| 查看次数: |
12865 次 |
| 最近记录: |