Java如何在Hibernate中从数据库检索对象?
在如何在休眠中存储对象?示例,您将看到如何将对象存储到数据库中。在此示例中,我们将扩展LabelManager类并添加从数据库获取或查询对象的功能。
package org.nhooo.example.hibernate.app;
import org.hibernate.Session;
import org.nhooo.example.hibernate.model.Label;
public class LabelManager {
public Label getLabel(Long id) {
Session session =
SessionFactoryHelper.getSessionFactory().getCurrentSession();
session.beginTransaction();
//我们通过调用Session从数据库取回Label对象
//objectget()方法并传递对象类型和对象
//要读取的ID。
Label label = session.get(Label.class, id);
session.getTransaction().commit();
return label;
}
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;
public class LoadDemo {
public static void main(String[] args) {
//创建LabelManager的实例。
LabelManager manager = new LabelManager();
//我们将getLabel()方法称为传递标签ID以加载它
//从数据库中打印出标签字符串。
Label label = manager.getLabel(1L);
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>