miércoles, 9 de marzo de 2016

CRUD con Java y Hibernate

You can view and download the complete source code of this tutorial from my github account.
In this tutorial, we will create a simple CRUD (Create Read Update Delete) User Management Console Application using Java, Hibernate and MySQL.
For this tutorial, we will need the following tools: (The older or newer version should also works).

First, lets create the database and table for User using the following SQL scripts. Copy and run this script in the MySQL Workbench (GUI Tool) –> SQL Editor:
create database UserDB;
use UserDB;
grant all on UserDB.* to 'admin'@'localhost' identified by 'test'; 

CREATE TABLE UserDB.`users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(45) DEFAULT NULL,
  `lastname` varchar(45) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

Go to eclipse and create a new project. Select File—>New—>Java Project. Enter “SimpleJava Hibernate” as the project name. Accept all the default value. Click Finish.
Please refer to this project directory in case you miss something along the way
structure
After creating the project, we need to add MySQL connector .jar file to our project build path. To do so, right click our newly created project “SimpleJavaHibernate” and choose Properties to open Properties window.
Select Java Build Path in the left side tree view to open right side detail view. Click Add External JARs.. button to open File browser dialog and point it to the MySQL connector .jar file which you have downloaded earlier.
Furthermore, we need to add Hibernate library to our project. Right click again the project and select Properties –>Java Build Path. This time, click Add Library. Select User Library from the list of selection. Click User Library. Next, click New. Enter “Hibernate” as the library name. Ok. Click our newly created User Library and click Add Jar. Select all the .jar file in both provided and required folder which located inside this directory structure [your hibernate download folder]—>hibernate-search-4.1.0.CR3-dist—>hibernate-search-4.1.0.CR3—>dist—>lib
Verify your build path to match configuration in picture below:
build path
This is all the configuration that we need to do and now let us get to the code.
Create four packages in the src folder.
  • com.daniel: contains the main method as the entry point for our console application
  • com.daniel.dao: contains the logic for database operation
  • com.daniel.model: contains the POJO (Plain Old Java Object). Each class in this package represents the database table. For this tutorial, however, we only have one table.
  • com.daniel.util : contains the class for initiating database connection
Next, create a new Java class. in com.daniel.model folder. Name it “User.java” and insert these following codes. Each of the variables in this class represents the field in USERS table in our database.
package com.daniel.model;

import java.util.Date;

public class User {

    private int userid;
    private String firstName;
    private String lastName;
    private Date dob;
    private String email;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [userid=" + userid + ", firstName=" + firstName
                + ", lastName=" + lastName + ", dob=" + dob + ", email="
                + email + "]";
    }    
}
Create a new class in com.daniel.util package and name it HibernateUtil.java. This class will read the configuration in our hibernate.cfg.xml file which handles the database connection to our MySQL server.
package com.daniel.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().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;
    }
}
Create the aforementioned hibernate.cfg.xml configuration file directly under SimpleJavaHibernate folder. Put the following information inside.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/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/UserDB</property>
        <property name="connection.username">admin</property>
        <property name="connection.password">test</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="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- Mapping files -->
        <mapping resource="user.hbm.xml" />

    </session-factory>
</hibernate-configuration>
Notice that inside the file, there is an information about mapping resource which point to user.hbm.xml file. So, create an .xml file directly under SimpleJavaHibernate folder to map our Plain Old Java Object (POJO) variables with fields in database. Name it user.hbm.xml and write the following code inside
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.daniel.model.User" table="users">
        <id name="userid" type="int" column="userid">
            <generator class="increment" />
        </id>
        <property name="firstName">
            <column name="firstname" />
        </property>
        <property name="lastName">
            <column name="lastname" />
        </property>
        <property name="dob">
            <column name="dob" />
        </property>
        <property name="email">
            <column name="email" />
        </property>
    </class>
</hibernate-mapping>
Next, create a new class in com.daniel.dao package, name it UserDao.javaDao stands for Data Access Object. It contains the logic for database operation.
package com.daniel.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.daniel.model.User;
import com.daniel.util.HibernateUtil;

public class UserDao {

    public void addUser(User user) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }

    public void deleteUser(int userid) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            User user = (User) session.load(User.class, new Integer(userid));
            session.delete(user);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }

    public void updateUser(User user) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            session.update(user);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }

    public List<User> getAllUsers() {
        List<User> users = new ArrayList<User>();
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            users = session.createQuery("from User").list();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return users;
    }

    public User getUserById(int userid) {
        User user = null;
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            String queryString = "from User where id = :id";
            Query query = session.createQuery(queryString);
            query.setInteger("id", userid);
            user = (User) query.uniqueResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return user;
    }
}
Finally, create our main application class inside the com.daniel package and name it App.java
package com.daniel;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.daniel.dao.UserDao;
import com.daniel.model.User;
import com.daniel.util.DbUtil;

public class App {

    public static void main(String[] args) {
        UserDao dao = new UserDao();

        // Add new user
        User user = new User();
        user.setFirstName("Daniel");
        user.setLastName("NikoJdbc");
        try {
            Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1986-01-02");
            user.setDob(dob);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setEmail("daniel@example.com");
        dao.addUser(user);
//
//        // Update user
        user.setEmail("daniel@updatedJdbc.com");
        user.setUserid(1);
        dao.updateUser(user);

        // Delete user
        //dao.deleteUser(2);

        // Get all users
        for (User iter : dao.getAllUsers()) {
            System.out.println(iter);
        }

        // Get user by id
        System.out.println(dao.getUserById(8));

        try {
            DbUtil.getConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
That is it. Run the project from eclipse and see the output from Console window

Fuente:
https://danielniko.wordpress.com/2012/12/03/simple-crud-using-java-hibernate-and-mysql/

No hay comentarios:

Publicar un comentario