是否可以暂时禁用Hibernate实体的级联?

时间:2015-09-15 08:52:02

标签: java hibernate jpa cascading-deletes cascading

给定一个Hibernate / JPA实体,为相关实体设置级联设置为@Entity public class Entity { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "entity") private Set<RelatedEntities> relatedEntities; }

ObjC.import("Cocoa");

var styleMask = $.NSTitledWindowMask | $.NSClosableWindowMask | $.NSMiniaturizableWindowMask;
var windowHeight = 85;
var windowWidth = 600;
var ctrlsHeight = 80;
var minWidth = 400;
var minHeight = 340;
var window = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer(
  $.NSMakeRect(0, 0, windowWidth, windowHeight),
  styleMask,
  $.NSBackingStoreBuffered,
  false
);

var textFieldLabel = $.NSTextField.alloc.initWithFrame($.NSMakeRect(25, (windowHeight - 40), 200, 24));
textFieldLabel.stringValue = "Image: (jpg, png, or gif)";
textFieldLabel.drawsBackground = false;
textFieldLabel.editable = false;
textFieldLabel.bezeled = false;
textFieldLabel.selectable = true;

var textField = $.NSTextField.alloc.initWithFrame($.NSMakeRect(25, (windowHeight - 60), 205, 24));
textField.editable = false;

var btn = $.NSButton.alloc.initWithFrame($.NSMakeRect(230, (windowHeight - 62), 150, 25));
btn.title = "Choose an Image...";
btn.bezelStyle = $.NSRoundedBezelStyle;
btn.buttonType = $.NSMomentaryLightButton;

window.contentView.addSubview(textFieldLabel);
window.contentView.addSubview(textField);
window.contentView.addSubview(btn);

window.center;
window.title = "Choose and Display Image";
window.makeKeyAndOrderFront(window);

是否可以暂时关闭级联,例如允许实体持久化而不保持其相关的实体?

2 个答案:

答案 0 :(得分:1)

你不能暂时禁用级联(据我所知,至少),但是既然你使用了Hibernate,你可以insert new entity using HQL

String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ...";
int createdEntities = s.createQuery( hqlInsert ).executeUpdate();

总有一个&#34;手册&#34;解决方案,您可以在变量中记住relatedEntities以供日后使用,并在null实例上设置Entity值作为其值,然后再保留它。

答案 1 :(得分:1)

不,这是不可能的,至少根据我的谦虚意见,这样做也不是一件好事。当其他开发人员查看映射和持久/合并/删除的代码时...他们会期望应用级联并引入意外行为,如果他们监督级联在其他地方临时禁用它们所关注的代码改变。

但是,您可以将同一个表映射到没有级联字段的新实体类。然后在您不希望应用级联的情况下使用该实体。