JPA从数据库中检索对象

时间:2015-05-29 09:00:52

标签: java jpa datapersistance

我正在为大学解决Java编程练习,但我不知道如何解决下一个问题。我有下一个persistence.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="stud" transaction-type="RESOURCE_LOCAL">
    <class>lt.vu.mif.jate.tasks.task03.jpa.model.Customer</class>
    <class>lt.vu.mif.jate.tasks.task03.jpa.model.Product</class>
    <class>lt.vu.mif.jate.tasks.task03.jpa.model.Sale</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
      <property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.NoCacheProvider"/>
      <property name="hibernate.generate_statistics" value="false"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://****************"/>
      <property name="javax.persistence.jdbc.user" value=""/>
      <property name="javax.persistence.jdbc.password" value=""/>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="hibernate.hbm2ddl.auto" value="none"/>
    </properties>
  </persistence-unit>
</persistence>

这里只是省略了数据库的URL。我无法更改此文件。我必须连接到数据库并从数据库中获取所有数据。我已经创建了所需的三个类。我该怎么做?非常感谢。

1 个答案:

答案 0 :(得分:0)

看看这个页面:

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/SettingUpJPA/SettingUpJPA.htm

https://docs.jboss.org/hibernate/orm/3.6/quickstart/en-US/html/hibernate-gsg-tutorial-jpa.html

还有其他一些教程等。但我认为你缺少的关键部分是:

public static void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("stud");
    EntityManager em = emf.createEntityManager();
}

这为您提供了一个EntityManager。然后你可以打电话:

em.getTransaction().begin();
List<Customer> result = entityManager.createQuery( "from Customer", Customer.class ).getResultList();