Component Mapping in Hibernate 4


Hôm nay mình xin giới thiệu với các bạn . Về việc thiết lập component mapping từ database to Object java in Hibernate như thế nào.

Source code : Downlaod

d1

Student table của chúng ta.

d1

Cấu trúc thư mục như sau :

d1

Class Address.java


package thaihoanghai.hibernate.bean;

import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
 * @Embeddable this annotation is used to specify the Address class will be used
 * as a component. The address class can't have a primary key of it's own.
 * It uses the enclosing class primary key
 *
 */

@Embeddable
public class Address {
 @Column(name="address_street", nullable=false, length=100)
 private String street;
 @Column(name="address_city", nullable=false, length=100)
 private String city;
 @Column(name="address_state", nullable=false, length=100)
 private String state;
 @Column(name="address_zipcode", nullable=false, length=100)
 private String zipcode;

 public Address() {

 }
 public Address(String street, String city, String state, String zipcode) {
 this.street = street;
 this.city = city;
 this.state = state;
 this.zipcode = zipcode;
 }
 public String getStreet() {
 return street;
 }
 public void setStreet(String street) {
 this.street = street;
 }
 public String getCity() {
 return city;
 }
 public void setCity(String city) {
 this.city = city;
 }
 public String getState() {
 return state;
 }
 public void setState(String state) {
 this.state = state;
 }
 public String getZipcode() {
 return zipcode;
 }
 public void setZipcode(String zipcode) {
 this.zipcode = zipcode;
 }
}

Class Student.java


package thaihoanghai.hibernate.bean;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student {
 @Id
 @GeneratedValue
 @Column(name="student_id")
 private int studentId;

 @Column(name="student_name", nullable=false, length=100)
 private String studentName;

 /**
 * @Embedded this annotation is used to specify the Address entity
 * stored in student table
 *
 */

 @Embedded
 private Address studentAddress;

 public Student() {

 }
 public Student(String studentName, Address studentAddress) {
 this.studentName = studentName;
 this.studentAddress = studentAddress;
 }
 public int getStudentId() {
 return studentId;
 }
 public void setStudentId(int studentId) {
 this.studentId = studentId;
 }
 public String getStudentName() {
 return studentName;
 }
 public void setStudentName(String studentName) {
 this.studentName = studentName;
 }
 public Address getStudentAddress() {
 return studentAddress;
 }
 public void setStudentAddress(Address studentAddress) {
 this.studentAddress = studentAddress;
 }

}

Class StudentDAO.java


package thaihoanghai.hibernate.dao;

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

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

public class StudentDAO {

public boolean addStudent(Student student){
 boolean flag = true;
 Session session = HibernateUtil.getSeesionfactory().openSession();
 Transaction trns = null;
 try {
 trns = session.beginTransaction();
 session.save(student);
 trns.commit();
 } catch (Exception e) {
 flag = false;
 trns.rollback();
 e.printStackTrace();
 // TODO: handle exception
 }finally{
 session.flush();
 session.close();
 }
 return flag;
 }
}

Class StudentService.kava


package thaihoanghai.hibernate.service;

import thaihoanghai.hibernate.bean.Student;
import thaihoanghai.hibernate.dao.StudentDAO;

public class StudentService {
 StudentDAO service = new StudentDAO();

 public boolean addStudent(Student std){
 return service.addStudent(std);
 }
}

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 SessionFactory creation failed. " + e);
 throw new ExceptionInInitializerError(e);
 }

 }

public static SessionFactory getSeesionfactory() {
 return seesionFactory;
 }

}

Class Hibernate.config.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/dbTest</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">123456</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

 <!-- JDBC connecition pool (use the built-in) -->
 <property name="hibernate.connection.pool_size">1</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>
 <property name="hbm2ddl.auto">Validate</property>

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

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

class Test.java


package project;

import thaihoanghai.hibernate.bean.Address;
import thaihoanghai.hibernate.bean.Student;
import thaihoanghai.hibernate.service.StudentService;
public class Test {
 public static void main(String[] args) {

 // Add student into database
 StudentService service = new StudentService();
 Address address = new Address("Thống Nhất", "Hồ Chí Minh", "State - Not", "123456");
 Student student = new Student("Kobee", address);
 service.addStudent(student);
 }
}

Kết quả sau khi run :

d1

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

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: