Hibernate 连接 MySQL

小结:

hibernate是用来封装数据库中的表,将表中的字段映射成为面向对象中的对象属性,这样操作更利于面向对象的编程。
主要方法就是两个配置文件:hibernate.cfg.xml 和 Demo.hbm.xml 文件:
1、cfg.xml   用来指定需要建立连接的表单,所以增加一个 类 或者 数据库表单 只需要在这个文件中加入一句<mapping resource=“Xxx.hbm.xml”><mapping class="Xxx.java">就行了。
2、hbm.xml用来指定对象熟性和表单字段的对应关系,当你使用Annotation方式的时候,就不用写这个了。

1,hibernate.cfg.xml

<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">haizhu</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</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.internal.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>

		<property name="javax.persistence.validation.mode">none</property>
	
	    <mapping resource="com/haizhu/model/Student.hbm.xml"/>
		<mapping class="com.haizhu.model.Teacher"/>    	
		</session-factory>

</hibernate-configuration>


 

2、HibernateSessionFactory.java

package com.haizhu.hb;

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

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

	static {
    	try {
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

3、Student.hbm.xml

<?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.haizhu.model.Student" table="h_student">
		<id name="id" column="s_id" type="int">
			<generator class="native"></generator>
		</id>
		<property name="name" column="s_name"/>
		<property name="age" column="s_age"/>
    </class>
</hibernate-mapping>

4、Student.java

package com.haizhu.model;

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;
	}
}


5、StudentTest.java

package test.com.haizhu.model;

import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;

import com.haizhu.hb.HibernateSessionFactory;
import com.haizhu.model.Student;

public class StudentTest {

	@Before
	public void setUp() throws Exception {
		System.out.println("增加学生:");
	}

	@Test
	public void test() {
		Student s = new Student();
		s.setId(22);
		s.setName("刘");
		s.setAge(25);
		
		Session sess = HibernateSessionFactory.getSession();
		sess.beginTransaction();
		sess.save(s);
		sess.getTransaction().commit();
	}

}

6、Teacher.java

package com.haizhu.model;


import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher {
	private int id;
	private String name;
	private String title;
	
	@Id
	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 String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
}


7、TeacherTest.java

package test.com.haizhu.model;

import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;

import com.haizhu.hb.HibernateSessionFactory;
import com.haizhu.model.Student;

public class StudentTest {

	@Before
	public void setUp() throws Exception {
		System.out.println("增加学生:");
	}

	@Test
	public void test() {
		Student s = new Student();
		s.setId(22);
		s.setName("刘");
		s.setAge(25);
		
		Session sess = HibernateSessionFactory.getSession();
		sess.beginTransaction();
		sess.save(s);
		sess.getTransaction().commit();
	}

}


 

 


 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值