Search code examples
javajpadata-persistence

JPA retrieve objects from database


I'm triying to solve a Java programming exercise for the universisty, but I don't know how to solve the next problem. I have the next persistence.xml file:

<?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>

The URL to the data base is just ommited here. I can't change this file. I have to connect to the database and get all the data from the database. I have already created the three classes needed. How can I do it? Thanks a lot.


Solution

  • Take a look at this page:

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

    and

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

    There are several other tutorials etc out there. But the key part that I think you are missing is:

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

    This gives you an EntityManager. You can then call:

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