一、準備工作
3,創建一個測試數據庫hibernate_first,再創建一個User表,各字段如下(id爲主鍵):
二、工程實例
1,新建一個普通Java工程,在Build Path中加入數據庫驅動jar包路徑及hibernate的jar包路徑。最新hibernate5.0.4的jar包目錄結構如下:
Required是必須的,其它的如果搞不懂作用就全部加入到Build Path中,否則可能有編譯錯誤。
2,在src目錄下新建數據庫默認的配置文件:hibernate.cfg.xml,內容如下:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!--hibernate_first要操作的數據庫-->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">bourne</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--是否在控制檯輸出操作的sql語句-->
<property name="hibernate.show_sql">true</property>
<mapping resource="com/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3,在src下創建一個com.entity包,再創建一個User類,代碼如下:
package com.entity;
import java.util.Date;
public class User {
private String id;
private String name;
private String password;
private Date createTime;
private Date expireTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getExpireTime() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
}
4,在com.entity下創建實體映射文件User.hdm.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.entity.User">
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime">
<column name="createTime"/>
</property>
<property name="expireTime">
<column name="expireTime"/>
</property>
</class>
</hibernate-mapping>
User.hbm.xml的作用簡而言之就是對實體和數據庫中的表進行相呼應,保證我們對實體對象進行的操作都會在數據庫中產生與之對應響應的結果。
property name對應的是類的字段名,column name對應的是數據庫字段名。如果省略後者則表示兩者相同。
5,在com.entity下創建測試類Client
package com.entity;
import java.util.Date;
import java.util.List;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Query;
import org.hibernate.cfg.Configuration;
import com.entity.User;
public class Client {
private SessionFactory factory = null;
public Client(SessionFactory factory){
this.factory = factory;
}
@SuppressWarnings("unchecked")
public void query(){
Session session = null;
try {
session = factory.openSession();
//開啓事務
session.beginTransaction();
Query query = session.createQuery("from User");
//還可以這樣加限制條件
//Query query = session.createQuery("from User WHERE name='NAME1'");
System.out.printf("%-50s%-20s%-20s\n", "id", "name", "password");
List<User> users = query.list();
for(Iterator<User> iter = users.iterator(); iter.hasNext();)
{
User user =(User)iter.next();
System.out.printf("%-50s%-20s%-20s\n", user.getId(),
user.getName(), user.getPassword());
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滾事務
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//關閉session
session.close();
}
}
}
}
public void update(){
Session session = null;
try {
session = factory.openSession();
//開啓事務
session.beginTransaction();
//這裏的id應先從數據庫查詢
User user = session.load(User.class, "402881ec5153a792015153a793e80000");
user.setName("Jack");
session.update(user);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滾事務
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//關閉session
session.close();
}
}
}
}
public void insert(){
//取得session
Session session = null;
try {
session = factory.openSession();
//開啓事務
session.beginTransaction();
/*
* 插入一條user記錄
*/
User user = new User();
user.setName("Mary");
user.setPassword("123456");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
//session.load(User.class, arg1)
//保存User對象
session.save(user);
//提交事務
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滾事務
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//關閉session
session.close();
}
}
}
}
public void delete(){
Session session = null;
try {
session = factory.openSession();
//開啓事務
session.beginTransaction();
User user = new User();
//這裏的id應先從數據庫查詢
user.setId("402881ec5153e384015153e3854f0000");
session.delete(user);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滾事務
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//關閉session
session.close();
}
}
}
}
public static void main(String[] args) {
//讀取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
//建立SessionFactory
SessionFactory factory = cfg.buildSessionFactory();
Client client = new Client(factory);
client.query();
client.insert();
System.out.println("table after inserted:");
client.query();
client.update();
System.out.println("table after updated:");
client.query();
client.delete();
System.out.println("table after deleted:");
client.query();
}
}
最後的工程目錄應該是這樣的:
沒有錯誤的話,運行Client.Java就能看到測試結果了。