hibernate之利用配置文件和annotation往數據庫裏插入數據

        大三學了javaEE三大框架,但課上只着重講了struts,hibernate講了一點,已經忘記的差不多了。馬上就要找工作了,重新捧起hibernate自學,今天是第一天,希望能有個好開始。

         慣例是先介紹開發環境是:hibernate-annotations-3.4.0.GA,hibernate-distribution-3.3.2.GA,slf4j-1.5.8,JDK1.6,MySQL5.0,myeclipse10.0。

         先介紹使用配置文件來往數據庫裏插入數據:

         利用MySQL創建_Student表:      

create table _Student(_id int primary key,_name varchar(20),_age int);
         進入myeclipse先建個java project命名爲:Test_001,然後導包:以前導包都是通過Bulid Path->add External jars,現在介紹個使用user library添加jar的新方法:

1.點擊Myeclipse的window菜單,選擇“Preference” 
2.在preferences窗口中選擇java->User Libraries,然後點擊窗口右邊的New...按鈕,在彈出的子窗口中輸入user library的名稱,此時在user libraries窗口中會出現新加的 
library名稱。 
3.向該user library中添加jar包。選中hibernate,然後點擊Add JARS...按鈕,選擇你要添加的jar後,點擊“打開”按鈕,則hibernate庫中就會出現你剛添加的jar文件信息。 
4.最後點擊窗口下的“OK”按鈕,完成user library的添加和其jar的添加。 

將user lirbrary添加到工程裏面:

1.鼠標右鍵單擊要添加user library庫的工程名稱,然後點擊Build Path->Add Libraries....菜單, 
   2.在彈出的子窗口中選中User Library,單擊Next按鈕,在新窗口中選中你要加入的library名稱後點擊finish按鈕即可,這樣就在該工程下 會出現你剛加入的library名稱。 

         接着介紹一下我的user library庫中所包含的包:slf4j-1.5.8包裏的slf4j-nop-1.5.8.jar,hibernate-distribution-3.3.2.GA包根目錄裏的hibernate3.jar,lib裏的required包裏的antlr-2.7.6.jar,commons-collections-3.1.jar,dom4j-1.6.1.jar,javassist-3.9.0.GA.jar,jta-1.1.jar,slf4j-api-1.5.8.jar。要連接MySQL數據庫當然少不了數據庫連接驅動:mysql-connector-java-3.1.13-bin.jar,這個就不需要放到user library庫裏了,直接通過add external jars方法導入即可。

         開發環境介紹完了,果斷進入正題:

         建包:com.hibernate.model,然後創建個Student類:     

package com.hibernate.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;
}

}
        然後創建配置文件,從路徑hibernate-distribution-3.3.2.GA/documentation/manual/zh-CN/html/index.html裏找到hibernate官方提供的配置文件格式創建配置文件: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">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://192.168.199.230/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">1</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.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> -->

        <mapping resource="com/hibernate/model/Student.hbm.xml"/>
        <mapping class="com.hibernate.model.Teacher"></mapping>

    </session-factory>

</hibernate-configuration>

創建映射文件Student.hbm.xml,將數據庫裏的_Student表和Student類映射起來(同理從官方文檔裏找參考配置文件):

<?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 package="com.hibernate.model">
<class name="Student" table="_Student">
<id name="id" column="_id"></id>
<property name="name" column="_name"></property>
<property name="age" column="_age"></property>
</class>
</hibernate-mapping>
最後就是創建StudentTest來測試連接了,代碼如下:

package com.hibernate.huanglei;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.hibernate.model.Student;

public class StudentTest {
	public static void main(String[] args) {
		Student s=new Student();		
		s.setId(1120010109);
		s.setName("huanglei");
		s.setAge(23);		
		Configuration cfg = new Configuration();
		SessionFactory sf = cfg.configure().buildSessionFactory();
		Session session=sf.openSession();
		session.beginTransaction();
		session.save(s);
		session.getTransaction().commit();
		session.close();
		sf.close();
	}
}
最後亮成果吐舌頭


       接着介紹annotation添加數據:

       慣例:先配置開發環境,往user library裏再添加幾個annotation必須的包:dom4j.jar,ejb3-persistence.jar,hibernate-commons-annotations.jar,hibernate-core.jar,slf4j-api.jar,hibernate-annotations.jar。

      創建_Teacher表:

create table _Teacher(_id int primary key,_name varchar(20),_title varchar(20));
    創建Teacher類:

package com.hibernate.model;

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

@Entity
@Table(name="_teacher")
public class Teacher {
private int id;
private String name;
private String title;
@Id
@Column(name="_id")
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
@Column(name = "_name")
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
@Column(name = "_title")
public String getTitle() {
	return title;
}
public void setTitle(String title) {
	this.title = title;
}
}
創建配置文件:

<?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">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://192.168.199.230/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">1</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.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> -->

        <mapping resource="com/hibernate/model/Student.hbm.xml"/>
        <mapping class="com.hibernate.model.Teacher"></mapping>

    </session-factory>

</hibernate-configuration>
創建TeacherTest類:

package com.hibernate.huanglei;

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

import com.hibernate.model.Teacher;

public class TeacherTest {
	public static void main(String[] args) {
		Teacher t = new Teacher();
		t.setId(4);
		t.setName("yy");
		t.setTitle("高級");
		
		//此處與使用xml配置文件方式不同
		Configuration cfg = new AnnotationConfiguration();
		
		SessionFactory sf = cfg.configure().buildSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(t);
		session.getTransaction().commit();
		session.close();
		sf.close();

	}
}
亮成果大笑




                            歡迎關注行者摩羅微信公衆號(xingzhemoluo),共同交流編程經驗,掃描下方二維碼即可;




發佈了41 篇原創文章 · 獲贊 14 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章