niedziela, 19 maja 2013

Using Hibernate persistence with Maven

First lets generate same basic maven project:

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=net.hibernateApp.packt.maven -DartifactId=TestHibernateApp -Dversion=1.0.0

Now we identify and include all Hibernate artifacts and its dependencies into Maven project:
      
    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.com/maven2/</url>
        </repository>
    </repositories>


    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- Hibernate core -->
        <dependency>
            <groupId>hibernate</groupId>
            <artifactId>hibernate3</artifactId>
            <version>3.2.3.GA</version>
        </dependency>

        <!-- Hibernate annotation -->
        <dependency>
            <groupId>hibernate-annotations</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.3.0.GA</version>
        </dependency>

        <dependency>
            <groupId>hibernate-commons-annotations</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>3.0.0.GA</version>
        </dependency>

        <!-- Hibernate library dependecy start -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>3.2.6.ga</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.4.0.GA</version>
        </dependency>
        <!-- Hibernate library dependecy end -->


        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.2</version>
        </dependency>

        <dependency>
             <groupId>javax.transaction</groupId>
             <artifactId>jta</artifactId>
             <version>1.1</version>
        </dependency>


  The next step is to create entity class, lets say User:

import javax.persistence.*;
import java.sql.Date;

@Entity
@Table(name = "User")
public class User {

    @Id
    @GeneratedValue
    private long id;

    @Column(name = "firstName")
    private  String firstName;

    @Column(name = "surName")
    private  String surName;

    @Column(name = "birthDate")
    private Date birthDate;

    @Column (name = "address")
    private  String address;

    public User() {
    }

    public User(String firstName, String surName, Date birthDate, String address) {
        this.firstName = firstName;
        this.surName = surName;
        this.birthDate = birthDate;
        this.address = address;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSurName() {
        return surName;
    }

    public void setSurName(String surName) {
        this.surName = surName;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


Notice the use of the @Table, @Entity, @Id, @Column annotations. There is two constructor in POJO User class, first default and second with arguments. The second is optional but note that it is nessesery to define a default(non-argument) constructor in your mapping class. This user class will be mapped by hibernate to User table.

Now we have to define util class which will be resposible for connection to our mysql database:

package net.hibernateApp.packt.maven.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtils {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();

        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}





When we already have class which will be keep connection to database, we have to configure that connection. Lets add file hibernate.cfg.xml to location /src/main/java/resources:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">{user}</property>
        <property name="connection.password">{pass}</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">false</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.User"/>

    </session-factory>
</hibernate-configuration>


The first six properties are specific to the underlying MYSQL database and the connection pool size available. hibernate.show_sql echoes all queries onto the console. hbm2ddl.auto = create-drop drops and generates the tables in the database each time the application is executed. Other possible values are validate, update and create. 

Finally, we will create the main class of our application to test CRUD basic database operations:

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;


import java.sql.Date;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        // Read
        System.out.println("******* READ *******");
        List users = list();
        System.out.println("Total Users: " + users.size());

        // Write
        System.out.println("******* WRITE *******");
        User user = new User("Christopher", "Stepniak", new Date(System.currentTimeMillis()), "Poland");
        user = save(user);
        user = read(user.getId());
        System.out.printf("%d %s %s \n", user.getId(), user.getFirstName(), user.getSurName());

        // Update
        System.out.println("******* UPDATE *******");
        User user2 = read(1l);
        System.out.println("Name Before Update:" + user2.getFirstName());
        user2.setFirstName("James");
        update(user2);  // save the updated user details

        user2 = read(1l);
        System.out.println("Name Aftere Update:" + user2.getFirstName());


        // Delete
        System.out.println("******* DELETE *******");
        delete(user);
        User user3 = read(user.getId());
        System.out.println("Object:" + user3);
    }

    private static List list() {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        List employees = session.createQuery("from User").list();
        session.close();
        return employees;
    }

    private static User save(User user){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        Long id = (Long) session.save(user);
        user.setId(id);

        session.getTransaction().commit();

        session.close();

        return user;
    }

    private static User read(Long id) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        User user = (User) session.get(User.class, id);
        session.close();
        return user;
    }

    private static User update(User user) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        session.merge(user);

        session.getTransaction().commit();

        session.close();
        return user;

    }

    private static void delete(User user) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        session.delete(user);

        session.getTransaction().commit();

        session.close();
    }

}







Brak komentarzy:

Prześlij komentarz