Wednesday, November 6, 2013

A quick introduction to Hibernate using Maven

Create the project

  1. Run mvn archetype:generate
  2. Select default archetype (maven-archetype-quickstart)
  3. Select the latest version of the archetype (1.1 at the time of making this tuto)
  4. Enter the groupId (I’ll use com.mycompany).
  5. Enter the artifactId (I’ll use hibernate-basic).
  6. Leave the default version (1.0-SNAPSHOT for me).
  7. Leave the default package (same as groupId).
  8. Confirm properties.
  9. Run cd hibernate-basic.


You will end up with the following project structure:


Import into eclipse

  1. Go to File –> Import and select Existing Maven Projects:
    Note: do NOT run the command mvn eclipse:eclipse
  2. Select the root directory of your Maven project:
  3. Hit Finish.
  4. You’ll get a nice looking project: 

Add dependencies

  1. Open your pom file and add these two dependencies:
    <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-entitymanager</artifactId>
     <version>4.2.7.Final</version>
    </dependency>
    <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>1.2.145</version>
    </dependency>
    We’ll need the hibernate-entitymanager library to be able to use hibernate in our project (EntityManagerFactory, EntityManager, annotations, etc). It depends on other libraries such as hibernate-core and hibernate-commons-annotations, but Maven will automatically handle that for us.
    The h2 library will give us the ability to persist our entities to an in-memory database called H2.
  2. We need to create the folder src/main/resources/META-INF, since it will hold our JPA persistence descriptor:

Add persistence.xml

  1. Right click your META-INF folder and add a new XML file called persistence.xml:
  2. Copy the following code into persistence.xml:
    <persistence 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_2_0.xsd"
     version="2.0">
    
     <persistence-unit name="myPersistenceUnit">
      <description>My persistence unit</description>
    
      <class>com.mycompany.Employee</class>
    
      <properties>
        <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
       <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE" />
       <property name="javax.persistence.jdbc.user" value="sa" />
       <property name="javax.persistence.jdbc.password" value="" />
    
       <property name="hibernate.show_sql" value="false" />
       <property name="hibernate.hbm2ddl.auto" value="create" />
      </properties>
    
     </persistence-unit>
    
    </persistence>
  3. You can give the persistence-unit any name you want, but take note of it. In our case it is myPersistenceUnit.
  4. Give it a description.
  5. The class section tells hibernate which class (or classes) we want to persist. Right now we still haven’t created this class, but that will be our next step.

Add an entity

  1. Add a class called Employee to the package com.mycompany
  2. Give the class 3 private properties, and generate their respective getters and setters:
    • id : long
    • name : String
    • age : int
  3. We have two ways of mapping our Employee class to the database.
    • The hibernate-specific way is using a mapping file for each persisted class, named <class-name>.hbm.xml, in our case it would be Employee.hbm.xml. There is also the posibility to use one single mapping file for all the persisted classes.
    • The JPA compliant way is using annotations inside each of our classes.
    We will go with the JPA compliant option.
  4. Add the following annotations to the class definition:
    @Entity
    @Table (name = "employees")
  5. Add the following annotations to the getId() method:
    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
  6. For our annotations to work, we need to import the following libraries:
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    import org.hibernate.annotations.GenericGenerator;
    employee annotations
  7. Let’s add two constructors to our Employee class: a default one, required by hibernate, and one for us to use:
    public Employee(){
    }
    
    public Employee(String name, int age){
     this.name = name;
     this.age = age;
    }

Test

  1. Add the following code inside the main method of our App class:
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(new Employee("John Doe", 24));
    em.persist(new Employee("Homer Simpson", 43));
    em.getTransaction().commit();
    
    em.getTransaction().begin();
      List<Employee> result = em.createQuery( "from Employee", Employee.class ).getResultList();
    for (Employee employee : result) {
     System.out.println( "Employee " + employee.getName() + " is " + employee.getAge() );
    }
    em.getTransaction().commit();
    em.close();
    Note: The method Persistence.createEntityManagerFactory() should receive the name of the persistence unit we specified in our persistence.xml.
  2. We need to import the following libraries:
    import java.util.List;
    
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
  3. We have 3 ways or running our app:
    1. Right click App.java and select Run As –> Java Application:

    1. In a command prompt, go to the root of our project and run:
      mvn compile
      mvn exec:java -Dexec.mainClass="com.mycompany.App"
    2. In a command prompt, go to the root of our project and run:
      mvn dependency:copy-dependencies
      mvn compile
      java -cp target\classes;target\dependency\* com.mycompany.App
      Note: mvn dependency:copy-dependencies will copy all the required jars inside target\dependency.
    Note: If you want to get rid of all that output hibernate produces, turn of the logging level by importing java.util.logging.Level and adding this at the beggining of our main method:
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);

1 comment:

  1. Are you dealing with outlook problems. visit askprob community to get your problem resolved easily.
    how to fix can't sign into outlook mail?

    ReplyDelete