Hibernate4.3.8Final环境搭建

1.在eclipse上新建java project


2.下载hibernate最新包4.3.8.Final.zip,解压文件


3.导入lib目录下required中的包


4.导入mysql的连接包


5.编写hibernate配置文件:hibernate.cfg.xml到src目录下





    

        
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost/test
        root
        123456

        
         

        
        org.hibernate.dialect.MySQLDialect

        
        

        
        org.hibernate.cache.internal.NoCacheProvider

        
        true

        
        update

        

    

6.编写实体类 Student
package com.dr.domain;

public class Student {
	private int id;
	private String name;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
}
7.编写实体类映射文件:Student.hbm.xml





	
		
		
		
		
	
8.在数据库中建相应的表:student

9.新建hibernate辅助类用来获取SessionFactory:HibernateUtil
 
  
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

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

    private static SessionFactory buildSessionFactory() {
        try {
        	Configuration cfg = new Configuration().configure();
        	StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
        	                    .applySettings(cfg.getProperties()).build();
        	SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        	return sessionFactory;
            
        }
        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;
    }


}

10.新建junit测试
 
  
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;

import com.dr.domain.Student;

public class HibernateTest {

	@Test
	public void test() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session s = sf.openSession();
		
		s.beginTransaction();
		Student student = new Student();
		student.setId(2);
		student.setName("dr02");
		student.setAge(22);
		
		s.save(student);
		s.getTransaction().commit();
		
		s.close();
		sf.close();
		
		
	}

}
11.测试成功打印sql语句:
 
  


 
  

你可能感兴趣的:(java)