Java如何检索Hibernate的持久对象列表?
在此示例中,我们添加了该函数以读取LabelManager类中的记录列表。该函数Label将从数据库读取所有持久对象。你可以看到其他的功能,如saveLabel,getLabel和deleteLabel在这个例子中的有关示例部分。
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 List<Label> getLabels() {
Session session =
SessionFactoryHelper.getSessionFactory().getCurrentSession();
session.beginTransaction();
//我们使用简单的Hibernate从数据库读取标签记录
//查询,即休眠查询语言(HQL)。
List<Label> labels = session.createQuery("from Label", Label.class)
.list();
session.getTransaction().commit();
return labels;
}
public void saveLabel(Label label) {
//为了保存对象,我们首先通过调用
//SessionFactoryHelper中的getCurrentSession()方法
//类。接下来我们创建一个新事务,保存Label对象
//并将其提交到数据库,
Session session =
SessionFactoryHelper.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(label);
session.getTransaction().commit();
}
}package org.nhooo.example.hibernate.app;
import org.nhooo.example.hibernate.model.Label;
import java.util.Date;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
LabelManager manager = new LabelManager();
//创建一个我们要存储在数据库中的Label对象。
//我们设置名称,修改日期和修改日期信息。
Label newLabel = new Label();
newLabel.setName("PolyGram");
newLabel.setCreated(new Date());
//调用LabelManagersaveLabel方法。
manager.saveLabel(newLabel);
List<Label> labels = manager.getLabels();
for (Label label : labels) {
System.out.println("Label = " + label);
}
}
}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>