Java如何在Hibernate中删除持久对象?
继续前面的示例,如何在Hibernate中从数据库中获取对象?,我们现在在LabelManager类中添加delete函数。
package org.nhooo.example.hibernate.app;
import org.hibernate.Query;
import org.hibernate.Session;
import org.nhooo.example.hibernate.model.Label;
import java.util.List;
public class LabelManager {
public void deleteLabel(Long id) {
//加载要删除的对象
Label label = getLabel(id);
//我们获取当前会话并从以下位置删除Label对象
//数据库。
Session session =
SessionFactoryHelper.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.delete(label);
session.getTransaction().commit();
}
}package org.nhooo.example.hibernate.app;
import org.nhooo.example.hibernate.model.Label;
import java.util.Date;
public class DeleteDemo {
public static void main(String[] args) {
LabelManager manager = new LabelManager();
//创建一个我们要存储在数据库中的Label对象。
//我们设置名称并创建日期信息。
Label label = new Label();
label.setName("Sony Music");
label.setCreated(new Date());
//调用LabelManagersaveLabel方法。
manager.saveLabel(label);
//从数据库读回对象。
label = manager.getLabel(label.getId());
System.out.println("Label = " + label);
manager.deleteLabel(label.getId());
}
}Maven依赖
<dependencies>
<!--https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.4.1.Final/hibernate-core-5.4.1.Final.jar-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!--https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-ehcache/5.4.1.Final/hibernate-ehcache-5.4.1.Final.jar-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!--https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>