我有一些问题需要了解如何使用Hibernate删除实体。
我有Table(Object1)与其他表(OneToMany)的关系,如:User,Localization,Status,Object2ID,Object3ID。
如何制作Hiberante session.delete - 删除Object1和Object2,其中ID = Obejct2ID(Object3,其中ID = Object3ID)并且不删除用户,本地化,状态关系 - 这些值是常量,我只用它来归属我的对象。这是我的代码(不是所有代码,只是带注释的定义):
@Entity
@Table(name="OBJECT1")
public class Object1 {
@Id
@Column(name="ID_Object1")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer idObject1;
@ManyToOne (cascade = CascadeType.PERSIST)
@JoinColumn(name="ID_LOCALIZATION")
private Localization LOCALIZATION;
我的本地化课程:
@Entity
@Table(name="LOCALIZATION")
public class Localization {
@Id
@Column (name="ID_LOCALIZATION")
private int ID_LOCALIZATION;
@Column (name="LOCALIZATION")
private String Localization;
@OneToMany (mappedBy="LOCALIZATION")
private Set<Object1> OBJECT1;
public Localization(){
}
public Localization(int ID_LOCALIZATION,String Localization){
this.ID_LOCALIZATION= ID_LOCALIZATION;
this.Localization= Localization;
}
我可以插入,更新数据但是当我要删除Object1时,hibernate也会删除子表中的数据。
感谢您的帮助!
答案 0 :(得分:1)
Hibernate ORM会在您定义它们时删除您的实体关系。 使用Hibernate删除实体的3种方法...使用名为Object1的通用模型实体(用户或模型的任何其他实体):
1#删除瞬态对象:
Object1 obj1 = new Object1();
obj1.setId(7);
session.delete(obj1);
2#删除持久对象:使用session.load(Class clazz,Long id)
Object1 obj1 = session.load(Object1.class, 7L);
if (null!=obj1) { session.delete(obj1); }
使用Hibernate HQL删除3#:
Query query = session.createQuery("delete Object1 where id = :idObj");
query.setParameter("idObj", 7L);
int result = query.executeUpdate();
if (result > 0 ) {
logger.info("The object with id#{} was removed from db.", 7L);
}
关于使用Hibernate处理关系的问题,搜索使用JPA Annotations定义它们的方式,Hibernate Annotations方式似乎已经过时(据我所知,它们已经被淘汰了一段时间)。
javax.persistence.CascadeType
这肯定会与你的实体形成类似的东西:
@Entity(name = "USER")
public class User {
@Id
@Column(name = "USER_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long userId;
// others fields
// relationships
@OneToMany(optional=false,cascade=CascadeType.PERSIST,
mappedBy="user",targetEntity=Localization.class)
private Localization localization;
@OneToMany(optional=false,cascade=CascadeType.PERSIST,
mappedBy="user",targetEntity=Status.class)
private Status status;
// etc.
}
这样,当您存储新用户时,您正在发送呼叫以保持关系,当您需要删除用户时,您将不会删除本地化或状态实体。
您可以使用某些jpa/hibernate best practises
撰写的好文章要删除对象而不删除自己的关系,必须在删除操作之前将对象内的关系设置为null
。
// something like that with an initialized Object1 obj1 having some relationships
obj1.setLocalization(null);
// and now delete your object with the #2 or the #3 method I have given before... see what happens!
// i.e.
if (null!=obj1) { session.delete(obj1); }