Hibernate with MySQL


Hôm nay mình xin giới thiệu các bạn triển khai sử dụng Hibernate trong java web . Ở phần model của chúng ta.

Sau đây là các bước các bạn cần thiết lập cho môi trường

1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download 
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download

Source code : Download

Sau khi down về các bạn sẻ có được các thư viện như hình vẽ sau :

d1

Khi có các thư mục các bạn copy nó vào thư mục lib bên dưới WebContent/Web-INF/lib

Sau đây là cấu trúc toàn bộ cho thư mục của chúng ta :

d1

Chúng ta tạo CSDL my SQL với tên mydatabase và có table product.

d1

OK chúng ta triển khai như hình trên :

Class product.java


package thaihoanghai.hibernate.bean;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Product")
public class Product {
 @Id
 @GeneratedValue
 @Column(name="product_id")
 private Integer productId;
 @Column(name="name")
 private String productName;
 @Column(name="expiration_date")
 private Date expirationDate;
 @Column(name="price")
 private Double price;
 public Integer getProductId() {
 return productId;
 }
 public void setProductId(Integer productId) {
 this.productId = productId;
 }
 public String getProductName() {
 return productName;
 }
 public void setProductName(String productName) {
 this.productName = productName;
 }
 public Date getExpirationDate() {
 return expirationDate;
 }
 public void setExpirationDate(Date expirationDate) {
 this.expirationDate = expirationDate;
 }
 public Double getPrice() {
 return price;
 }
 public void setPrice(Double price) {
 this.price = price;
 }
 public Product(Integer productId, String productName, Date expirationDate,
 Double price) {
 super();
 this.productId = productId;
 this.productName = productName;
 this.expirationDate = expirationDate;
 this.price = price;
 }
 public Product() {
 super();
 // TODO Auto-generated constructor stub
 }

 public Product(String productName, Date expirationDate, Double price) {
 super();
 this.productName = productName;
 this.expirationDate = expirationDate;
 this.price = price;
 }
 @Override
 public String toString() {
 return "Product [productId=" + productId + ", productName="
 + productName + ", expirationDate=" + expirationDate
 + ", price=" + price + "]";
 }

}

Sau đó chúng ta cấu hình hibernate trong file hibernate.cfg.xml 


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

<hibernate-configuration>
 <session-factory>
 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="hibernate.connection.url">jdbc:mysql://localhost/mydatabase</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">123456</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

 <!-- JDBC connecition pool (use the built-in) -->
 <property name="hibernate.connection.pool_size">10</property>
 <!-- Enable Hibernate's automatic session context management -->
 <property name="hibernate.current_session_context_class">thread</property>

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

 <!-- Mapping to Resource -->
 <mapping class="thaihoanghai.hibernate.bean.Product" />

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

Tiếp theo chúng ta viết class HibernateUtil.java


package thaihoanghai.hibernate.util;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate Util used to configure Hibernate's Session Factoru and retrieve it as Singleton
 * @author kobee
 *
 */
public class HibernateUtil {
 private static final SessionFactory seesionFactory;
 private static ServiceRegistry serviceRegistry;

 static{
 try {
 Configuration configuration = new Configuration();
 configuration.configure();
 serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
 seesionFactory = configuration.buildSessionFactory(serviceRegistry);

 } catch (HibernateException e) {
 System.err.println("Initial SessionFactoru creation failed. " + e);
 throw new ExceptionInInitializerError(e);
 }

 }

public static SessionFactory getSeesionfactory() {
 return seesionFactory;
 }

}

Class ProductDAO.java


package thaihoanghai.hibernate.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

import thaihoanghai.hibernate.bean.Product;
import thaihoanghai.hibernate.util.HibernateUtil;

public class ProductDAO {
 public boolean addProduct(String name, Date eDate, Double price){
 boolean flag = false;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 Transaction trns = null;

try {
 trns = session.beginTransaction();
 Product p = new Product(name, eDate,price);
 session.saveOrUpdate(p);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }

public boolean updateProduct(Integer id,String newName, Date newDate, Double newPrice ){
 boolean flag = false;
 Transaction trns = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 Product p = (Product) session.get(Product.class, id);
 p.setProductName(newName);
 p.setExpirationDate(newDate);
 p.setPrice(newPrice);
 session.update(p);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 e.printStackTrace();
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }
 public boolean deleteProduct(Integer id){
 boolean flag = false;
 Transaction trns = null;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 try {
 trns = session.beginTransaction();
 Product product = (Product) session.get(Product.class, id);
 session.delete(product);
 trns.commit();
 flag = true;
 } catch (Exception e) {
 if(trns != null)
 trns.rollback();
 e.printStackTrace();
 }
 return flag;
 }

@SuppressWarnings("rawtypes")
 public List<Product> getListProduct(){
 List<Product> listProduct = new ArrayList<Product>();
 Session session = HibernateUtil.getSeesionfactory().openSession();
 Transaction trns = null;
 try {
 trns = session.beginTransaction();

Criteria crit = session.createCriteria(Product.class);
 List list = crit.list();
 Iterator iter = list.iterator();
 while(iter.hasNext()){
 Product p = (Product) iter.next();
 listProduct.add(p);
 System.out.println(p);
 }
 session.getTransaction().commit();

} catch (Exception e) {
 if(trns != null){
 trns.rollback();
 e.printStackTrace();
 return null;
 }
 }finally{
 session.flush();
 session.close();
 }

return listProduct;

}
}

Class ProductService.java


package thaihoanghai.hibernate.service;
import java.util.List;

import thaihoanghai.hibernate.bean.Product;
import thaihoanghai.hibernate.dao.ProductDAO;

public class ProductService {
 ProductDAO productDAO = new ProductDAO();

public boolean addProduct(Product product){
 return productDAO.addProduct(product.getProductName(),
 product.getExpirationDate(), product.getPrice());
 }

public boolean deleteProduct(int productId) {
 return productDAO.deleteProduct(productId);
 }

public boolean updateProduct(Product product){
 return productDAO.updateProduct(product.getProductId(),
 product.getProductName(), product.getExpirationDate(), product.getPrice());
 }

 public List<Product> getListProduct(){
 return productDAO.getListProduct();
 }
}

Class Test.java


package project;

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

import thaihoanghai.hibernate.bean.Product;
import thaihoanghai.hibernate.service.ProductService;

public class Test {
 public static void main(String[] args) {
 ProductService service = new ProductService();
 boolean flag;

 //================================Add New Product=======================================
 flag = service.addProduct(new Product("Nokia 101", new Date(), 690d));
 if(flag)
 System.out.println("Insert Success");
 else
 System.out.println("Insert faild");

 //================================Delete Product=======================================
 int idDelete = 999999;
 flag = service.deleteProduct(idDelete);
 if(flag)
 System.out.println("Delete Success");
 else
 System.out.println("Delete faild");

 //================================Update Product=======================================
 int idUpdate = 99999;
 String newName = "yourValue";
 Date newDate = new Date(); // your date
 Double newPrice = 99999d; // your price
 flag = service.updateProduct(idUpdate, new Product(newName, newDate, newPrice));

 flag = service.deleteProduct(idDelete);
 if(flag)
 System.out.println("Update Success");
 else
 System.out.println("Update faild");

 //================================Display List Product=======================================
 List<Product> listProduct = service.getListProduct();
 for(Product p : listProduct)
 System.out.println(p);

 }

}

Chúc các bạn thành công !!

One Response to “Hibernate with MySQL”

  1. kobee Says:

    For connect MSSQL 2008
    com.microsoft.sqlserver.jdbc.SQLServerDriver
    jdbc:sqlserver://localhost:1433;databaseName=dbshop
    sa
    123456
    org.hibernate.dialect.SQLServer2008Dialect


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: