1、 數據庫設計
建立crud.student數據庫表:
圖1 數據庫表
你可以使用如下語句創建該庫表:
[sql] view plaincopy
create database if not exists `crud`;
USE `crud`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(20) default NULL,
`age` int(4) default NULL,
`score` int(4) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;<font size="3"><font size="+0">
在這裏我使用的是MySQL,當然你也可以選擇別的數據庫,只是在選擇之前請準備好相應的jar包即可。
2、 程序編寫:
第一步:配置數據源
1、打開MyEclipse,新建一個web工程,這裏命名爲hibernate_demo
2、打開數據庫設置器:依次單擊【window】-->【Show View】-->【Other…】 如下圖所示:
3、在彈出的窗口ShowView中選擇DB Browser,如下圖所示:
4、在DB Browser窗口中,選擇顯示的圖標,單擊右鍵執行新建命令,如下圖示
5、彈出Database Driver對話框,在此會要求我們配置數據庫的相關信息,具體設置如下圖所示,設置完成,單擊Finish.
【第二步】引入hibernate配置文件
1、 添加hibernate包:
選中我們的Web工程,依次單擊鼠標右鍵-->MyEclipse-->Add Hibernate Capabilities… 如下圖所示:
2、 在彈出的窗口中做如下設置:
【Next】
【Next】
單擊Next,把要創建的SessionFactory放置於相應的包中,如果前面沒有設置包名,這裏要先單擊New創建新的包。
單擊【Finish】按鈕,頁面效果如下圖所示:
接下來要給hibernate.cfg.xml文件添加屬性:在properties處選擇Add…,如下圖所示:
單擊【Add…】,在Hibernate Properties Wizard頁面填入如下圖所示信息,最後單擊Ok。
show_sql:默認爲false, 如果爲true,表示在程序運行時,會在控制檯輸出SQL語句,這有利於跟中Hibernate的運行狀態。在開發和測試階段,可以將該屬性設置爲 true,以便跟蹤、調試程序,在應用發佈以後 ,應將該屬性值設置爲false,以減少應用的輸出信息,提高運行性能。
【第三步】添加hibernate映射文件
1、新建org.njy.bean包
2、在前面設置的數據源上找到我們要操作的表:
在DB Browser中選中新建的數據源,單擊鼠標右鍵並選擇open connection..
輸入數據庫的用戶名和密碼,以創建連接:
找到剛纔新建的crud數據庫,然後是TABLE,如下圖所示:
生成POJO:
3、 修改Student.hbm.xml文件
[xml] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="org.njy.bean.Student" table="student">
<!-- 必須先定義<id>元素,後定義<property>元素 -->
<id name="id" type="java.lang.Integer">
<column name="id" />
<!-- 主鍵的生成方式 -->
<generator class="increment" />
</id>
<!-- name屬性,類型爲String,對應的數據庫中的列爲name,長度爲20 -->
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
<property name="age" type="java.lang.Integer">
<column name="age" />
</property>
<property name="score" type="java.lang.Integer">
<column name="score" />
</property>
</class>
</hibernate-mapping>
提示:建議刪除catalog=”crud”,當修改了數據庫名的時候程序會出現錯誤(找不到對應的庫)。
4、 hibernate.cfg.xml文件
[xml] view plaincopy
<?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>
<!-- dialect指定數據庫使用的方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- connection.dirver_class指定數據庫的驅動程序 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- connection.url指定連接數據庫的URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/crud</property>
<!-- connection.username指定連接數據庫的用戶名 -->
<property name="connection.username">root</property>
<!-- connection.password指定連接數據庫的密碼 -->
<property name="connection.password">root</property>
<!-- show_sql指定是否打印SQL語句 -->
<property name="show_sql">true</property>
<!-- 指定POJO的映射文件 -->
<mapping resource="org/njy/bean/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
5、 新建一個包org.njy.test,再新建TestHibernate.java用來測試一下我們的Hibernate。
【添加】
[java] view plaincopy
public static void main(String[] args) {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Student stu = new Student("聶靖宇", 22, 98);
try {
session.save(stu);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
}
在執行添加的時候控制檯打印出如下兩條sql語句:
Hibernate: select max(id) from student
Hibernate: insert into student (name, age, score, id) values (?, ?, ?, ?)
【修改】
[java] view plaincopy
public static void main(String[] args) {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Student stu = new Student("test", 22, 98);
stu.setId(1);
try {
session.update(stu);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
}<font size="3"><font size="+0"><span>
在修改信息的時候要保證主鍵Id存在,這樣程序才知道修改的是那條記錄的信息。
在修改信息的時候要保證主鍵Id存在,這樣程序才知道修改的是那條記錄的信息。
【刪除】
[java] view plaincopy
public static void main(String[] args) {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Student stu = new Student();
stu.setId(1);
try {
session.delete(stu);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally{
session.close();
}
}