본문 바로가기

SPRING

하이버네이트 + Mysql(anotaion) 기초 잡기

DB TABLE 만들기:
create table STUDENT (
   id INT NOT NULL auto_increment PRIMARY KEY,
   first_name VARCHAR(30) NOT NULL,
   last_name  VARCHAR(30) NOT NULL,
   section    VARCHAR(30) NOT NULL
);
Model 만들기:
package com.hojin.model;

import java.io.Serializable;

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


@Entity
@Table(name = "STUDENT")//선택적, 생략 시 class name = database name
public class Student implements Serializable{
	
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//mysql,oracle은  sequence (strategy = GenerationType.SEQUENCE)
    private int id;

	@Column(name = "FIRST_NAME", nullable = false)//이밖에도 unique, nullable, name & length 속성
    private String firstName;
 
    @Column(name = "LAST_NAME", nullable = false)
    private String lastName;
 
    @Column(name = "SECTION", nullable = false)
    private String section;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    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 String getSection() {
        return section;
    }
 
    public void setSection(String section) {
        this.section = section;
    }
    //하이버네이트는 hashcode and equals method 찾기 때문에, 재정의 해주는게 좋은 습관
	@Override
	public boolean equals(Object obj) {
		if(this == obj) return true;
		if(obj == null) return false;
		if(!(obj instanceof Student)) return false;
		Student other = (Student) obj;
		if(id != other.id) return false;
		return true;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}
 
    
}


Hibernate 환경설정:



	  
        org.hibernate.dialect.MySQLDialect
        com.mysql.jdbc.Driver
        selfStudyId
        selfStudyPw
        jdbc:mysql://localhost:3306/selfStudy
        true
        false
        
    
	

Hibernate Utility class:
package com.hojin.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	
	static{
		try{
			sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

 
        }catch (Throwable ex) {
            System.err.println("Session Factory could not be created." + ex);
            throw new ExceptionInInitializerError(ex);
        }   

	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	
}


Run and perform CRUD operations:
package com.hojin.core;

import java.util.List;

import org.hibernate.Session;

import com.hojin.model.Student;
import com.hojin.util.HibernateUtil;

public class HibernateStandAloneDemo {
	public static void main(String[] args) {
		HibernateStandAloneDemo application = new HibernateStandAloneDemo();
		
		//삽입
		int studentId1 = application.saveStudent("Sam", "Disilva", "Maths");
        int studentId2 = application.saveStudent("Joshua", "Brill", "Science");
        int studentId3 = application.saveStudent("Peter", "Pan", "Physics");
        int studentId4 = application.saveStudent("Bill", "Laurent", "Maths");
        
        //리스트
        List students = application.getAllStudents();
        System.out.println("List of all persisted students >>>");
        for (Student student : students) {
            System.out.println("Persisted Student :" + student);
        }
        
        //업데이트
        application.updateStudent(studentId4, "ARTS");
        
        //삭제
        application.deleteStudent(studentId2);
	}

	 public void deleteStudent(int id) {
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        session.beginTransaction();
	 
	        Student student = (Student) session.get(Student.class, id);
	        session.delete(student);
	        session.getTransaction().commit();
	        session.close();
	    }


	private void updateStudent(int id, String section) {
		Session session = openSession();
		session.beginTransaction();
		
		Student student = (Student) session.get(Student.class, id);//get 해올 때 객체와 주키로 맵핑
		student.setSection(section);
		//session.update(student);//트랜잭션이 끝나면 자동적으로 값 변경되기 때문에, 수동적으로 update 필요 x 
		session.getTransaction().commit();
		session.close();
	}

	private List getAllStudents() {
		Session session = openSession();
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List employess =  (List) session.createQuery(
                "FROM Student s ORDER BY s.firstName ASC").list();
		session.getTransaction().commit();
		session.close();

		return employess;
	}

	private int saveStudent(String firstName, String lastName, String section) {
		  Student student = new Student();
	        student.setFirstName(firstName);
	        student.setLastName(lastName);
	        student.setSection(section);
	        
	        Session session = openSession();
	        session.beginTransaction();
	        
	        int id = (Integer) session.save(student);//generated identifier값이 리턴
	        session.getTransaction().commit();
	        session.close();
	        return id;
	}
	
	public static Session openSession(){
		return HibernateUtil.getSessionFactory().openSession();
	}
}

예제:http://websystique.com/hibernate/hibernate-mysql-maven-hello-world-example-annotation/