程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> hibernate3學習筆記(四) 增刪改查

hibernate3學習筆記(四) 增刪改查

編輯:關於JAVA

測試代碼:

package com.hb3.pack_01;

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

import com.hb3.pack_01.model.User;

public class BusinessService {

public static void main(String[] args) {

Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();

//insert
User user = new User();
user.setName("chenyan");
//user.setAge(new Integer(23));
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();

//get
user = (User) session.get(User.class, user.getId());
System.out.println(user.getAge());

//update
user.setAge(new Integer(24));
tx= session.beginTransaction();
session.update(user);
tx.commit();

//load
user = (User) session.load(User.class, user.getId());
System.out.println(user.getAge());

//delete
tx = session.beginTransaction();
session.delete(user);
tx.commit();

session.close();
sessionFactory.close();
}
}
執行結果:

11:50:50,750 WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
11:50:51,156 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
11:50:51,171 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: insert into user (name, age) values (?, ?)
null
Hibernate: update user set name=?, age=? where id=?
24

修改User.hbm.xml文件如下:

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

<hibernate-mapping>
<class name="com.hb3.pack_01.model.User" table="user"
dynamic-insert="true"
dynamic-update="true"
>
<id name="id" column="id" type="java.lang.Integer">
<generator class="native" />
</id>

<property name="name" column="name" type="java.lang.String" />

<property name="age" column="age" type="java.lang.Integer" />
</class>
</hibernate-mapping>
運行結果如下:

12:46:32,062 WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
12:46:32,468 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
12:46:32,500 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: insert into user (name) values (?)
null
Hibernate: update user set age=? where id=?
24
Hibernate: delete from user where id=?

可見:

dynamic-insert和dynamic-update設成true後,分別表示生成的SQL中只插入非空字段以及只修改改變過的字段。

另外,hibernate還提供了saveOrUpdate()方法,因為這個方法很容易出錯,故在後續章節著重講述。

關於查詢:

1.package com.hb3.pack_01;
2.
3.import java.util.Iterator;
4.import java.util.List;
5.
6.import org.hibernate.Criteria;
7.import org.hibernate.Query;
8.import org.hibernate.Session;
9.import org.hibernate.SessionFactory;
10.import org.hibernate.cfg.Configuration;
11.import org.hibernate.criterion.Restrictions;
12.
13.import com.hb3.pack_01.model.User;
14.
15.public class BusinessService {
16.
17.    public static void main(String[] args) {
18.        
19.        Configuration config = new Configuration().configure();
20.        SessionFactory sessionFactory = config.buildSessionFactory();      
21.        Session session = sessionFactory.openSession();
22.        
23.        Criteria criteria = session.createCriteria(User.class);
24.        List<?> users = criteria.list();
25.        Iterator<?> iterator = users.iterator();
26.        System.out.println("id \t name/age");
27.
28.        while (iterator.hasNext()) {
29.            User user = (User) iterator.next();
30.            System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
31.        }
32.        
33.        //criteria.add(Expression.eq("name", "shenbin"));
34.        criteria.add(Restrictions.eq("name", "shenbin"));
35.        users = criteria.list();
36.        iterator = users.iterator();
37.        System.out.println("id \t name/age");
38.
39.        while (iterator.hasNext()) {
40.            User user = (User) iterator.next();
41.            System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
42.        }
43.        
44.        System.out.println("====================================================");
45.        
46.        Query query = session.createQuery("from User");
47.        users = query.list();
48.        iterator = users.iterator();
49.        System.out.println("id \t name/age");
50.
51.        while (iterator.hasNext()) {
52.            User user = (User) iterator.next();
53.            System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
54.        }
55.        
56.        query = session.createQuery("from User user where user.name like ?");
57.        query.setParameter(0, "shenbin");
58.        users = query.list();
59.        iterator = users.iterator();
60.        System.out.println("id \t name/age");
61.
62.        while (iterator.hasNext()) {
63.            User user = (User) iterator.next();
64.            System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
65.        }
66.
67.        session.close();
68.        sessionFactory.close();
69.    }
70.}

執行結果:

13:05:43,031 WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
13:05:43,453 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
13:05:43,484 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_
id name/age
1 shenbin/29
2 chenyan/24
3 chenyan/24
4 chenyan/24
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_ where this_.name=?
id name/age
1 shenbin/29
================================================
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_
id name/age
1 shenbin/29
2 chenyan/24
3 chenyan/24
4 chenyan/24
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_ where user0_.name like ?
id name/age
1 shenbin/29

以上分別演示了使用Criteria對SQL的分裝以及透過HQL來進行查詢。

注意:

代碼中如下部分

//criteria.add(Expression.eq("name", "shenbin"));
criteria.add(Restrictions.eq("name", "shenbin"));

在hibernate3.3以後的版本,可能Expression類會被廢除,為了保證代碼的向後兼容,請使用Restrictions替代。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved