MyEclipse Hibernate 學習總結


最近在學習Hibernate,先把學習的過程記錄一下,方便自己以后復習.

1.使用工具

MyEclipse 10

 

2.

1)新建Java程序

2)右鍵程序,選擇MyEclipse-> Add Hibernate Capabilities.

會自動生成HibernateSessionFactory.java文件和hibernate.cfg.xml文件

package com.water.testhibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * 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 String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} 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(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} 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 session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

  

創建Grade文件

public class Grade implements Serializable {
	private int gid;
	private String gname;
	private String gdesc;
	private Set<Student> students;

	public int getGid() {
		return gid;
	}

	public void setGid(int gid) {
		this.gid = gid;
	}

	public String getGname() {
		return gname;
	}

	public void setGname(String gname) {
		this.gname = gname;
	}

	public String getGdesc() {
		return gdesc;
	}

	public void setGdesc(String gdesc) {
		this.gdesc = gdesc;
	}

	public Grade() {
		super();
	}

	public Set<Student> getStudents() {
		return students;
	}

	public void setStudents(Set<Student> students) {
		this.students = students;
	}

	public Grade(int gid, String gname, String gdesc) {
		super();
		this.gid = gid;
		this.gname = gname;
		this.gdesc = gdesc;
	}

	public Grade(String gname, String gdesc) {
		super();
		this.gname = gname;
		this.gdesc = gdesc;
	}

}

創建Grade.hbm.xml文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.water.model.Grade" table="grade">
		<id name="gid" column="gid" type="java.lang.Integer">
			<generator class="increment"></generator>
		</id>
		<property name="gname" type="java.lang.String">
			<column name="gname" length="20" not-null="true"></column>
		</property>
		<property name="gdesc">
			<column name="gdesc"></column>
		</property>
		<!-- 配置一對多關聯關系 -->
		<set name="students" table="student">
			<key column="gid"></key>
			<one-to-many class="com.water.model.Student"/>
		</set>
	</class>
</hibernate-mapping>

 

 

 

創建Student文件

public class Student implements Serializable {
	private int sid;
	private String sname;
	private String sex;
	// 在多方定義一個一方的引用
	private Grade grade;

	public Grade getGrade() {
		return grade;
	}

	public void setGrade(Grade grade) {
		this.grade = grade;
	}

	public int getSid() {
		return sid;
	}

	public void setSid(int sid) {
		this.sid = sid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Student() {
		super();
	}

	public Student(String sname, String sex) {
		super();
		this.sname = sname;
		this.sex = sex;
	}

}

 創建Student.hbm.xml  文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.water.model.Student" table="student">
		<id name="sid" column="sid" type="java.lang.Integer">
			<generator class="increment"></generator>
		</id>
		<property name="sname" type="java.lang.String">
			<column name="sname" length="20" not-null="true"></column>
		</property>
		<property name="sex">
			<column name="sex"></column>
		</property>
		<!-- 配置多對一關聯關系 -->
		<!-- <many-to-one name="grade" class="com.water.model.Grade" column="gid" cascade="all"></many-to-one> -->
	</class>
</hibernate-mapping>

 最后hibernate.cfg.xml文件的配置如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/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.driver_class">com.mysql.jdbc.Driver</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="show_sql">true</property>
	<!-- create and update the database automaticlly -->
	<property name="hbm2ddl.auto">update</property>
	<property name="myeclipse.connection.profile">ms_sql</property>
	<property name="connection.url">jdbc:mysql://localhost:3306/mysql</property>

	<mapping resource="com/water/model/Student.hbm.xml" />
	<mapping resource="com/water/model/Grade.hbm.xml" />
</session-factory>

</hibernate-configuration>

 <property name="connection.username">root</property>數據庫用戶名

<property name="connection.password">root</property> 數據庫密碼

<property name="connection.url">jdbc:mysql://localhost:3306/mysql</property> mysql為數據庫名

 

 創建測試類Test.java

public class Test {
	public static void main(String[] args) {
		add();
	}
	
		public static void add(){
			Grade g=new Grade("software developer", "Java Android");
			Student stu1=new Student("zhasan", "boy");
			Student stu2=new Student("lisi", "girl");
			
			Session session=HibernateSessionFactory.getSession();
			Transaction tx=session.beginTransaction();
			session.save(g);
			session.save(stu1);
			session.save(stu2);
			tx.commit();
			HibernateSessionFactory.closeSession();
		}
}

 運行后的效果如下:

說明已經插入成功.

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com