1. 程式人生 > >使用Hibernate連線MySQL實現新增資料功能

使用Hibernate連線MySQL實現新增資料功能

開發工具: MyEclipse2013 , 資料庫: MySql

1.首先, 在資料庫中建立資料庫 , 我使用的資料庫工具是SQLyog.

建立如下資料庫:

資料庫建立完成後開啟MyEclispe

2.建立Web Project

2.1: 第一項: 導包

需要匯入如下包:(這些包在網上都可以找到, 我也會共享在我得資源裡)

2.2 : 編寫配置檔案:hibernate.cfg.xml

<hibernate-configuration>
		<!-- 配置資料庫各個引數 -->
		<session-factory>
			<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
			<property name="connection.url">jdbc:mysql://localhost:3306/hibertest?characterEncoding=utf-8</property>
			<property name="connection.username">root</property>
			<property name="connection.password">sasa</property>
			<property name="dialect">org.hibernate.dialect.MySQLDialect</property>


			<!-- 顯示sql語句 -->
			<property name="show_sql">true</property>
			<!-- 格式化程式碼 -->
			<property name="format_sql">true</property>
		
			<mapping resource="com/entity/Dept.hbm.xml" />
		</session-factory>
		</hibernate-configuration>

2.3: 建立一個實體類 , 並給get/set方法 , 有參無參構造

package com.entity;

import java.io.Serializable;

public class Dept implements Serializable {

	private int deptno;
	private String deptname;
	private String loc;

	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}

	public String getDeptname() {
		return deptname;
	}

	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}

	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

	public Dept(int deptno, String deptname, String loc) {
		super();
		this.deptno = deptno;
		this.deptname = deptname;
		this.loc = loc;
	}

	public Dept() {
		super();
		// TODO Auto-generated constructor stub
	}

}

實體包裡需建立Dept.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.entity.Dept" table="dept">
		<!-- 主鍵對映 -->
		<id name="deptno" column="deptno">
			<!-- 主鍵產生的值得策略 -->
			<generator class="native"></generator>
		</id>
		<!-- 此處的name值對應實體類中屬性 -->
		<property name="deptname" column="deptname"></property>
		<property name="loc" column="loc"></property>
	</class>
</hibernate-m

下面編寫test類:

程式碼如下:

package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.entity.Dept;

import junit.framework.TestCase;

public class Test extends TestCase {

	// 增加部門
	public void testAdd() {

		// 讀取hibernate配置檔案
		Configuration config = new Configuration()
				.configure("hibernate.cfg.xml");

		// 所有的配置都要向一個類中註冊
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(
				config.getProperties()).buildServiceRegistry();

		// 獲得sessionfactory
		SessionFactory sf = config.buildSessionFactory(sr);

		// 獲得session,操作資料庫的介面
		Session session = sf.openSession();

		// 建立一個部門物件
		Dept dept = new Dept();
		dept.setDeptname("開發部");
		dept.setLoc("武漢");

		// 開啟事物
		Transaction tran = session.beginTransaction();

		// 執行插入操作
		//手動try catch 選中-右鍵 -surround with
		try {  
			session.save(dept);
			tran.commit();
		} catch (Exception e) {
			tran.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
總體圖如下:
執行test類裡的testAdd()方法:
控制檯會打印出sql語句如下:
Hibernate: 
    insert 
    into
        dept
        (deptname, loc) 
    values
        (?, ?)


資料庫資料新增結果: