Hibernate 筆記4 實現對數據庫的增刪改查

1? 準備

?

首先在mysql數據庫中建表User,并添加相關信息。

user表結構如下。

+-------+--------------+------+-----+---------+----------------+
| Field????| Type??????????? ?|???Null |??Key |???Default |????? Extra????????? |
+-------+--------------+------+-----+---------+----------------+
| id?????? ?| int(11)??????????| NO?? ?| PRI?? | NULL?? ? | auto_increment |
| name ? | varchar(255) | YES?? |????? ??| NULL?????|??????????????????????? |
| pwd??? ?| varchar(255) | YES? ?|?????? ?| NULL??? ?|?????????????????????? ?|
+-------+--------------+------+-----+---------+----------------+

建立User類,添加set,get 方法。

使用hibernate對數據進行增刪改差的步驟:

        1. 獲得連接
        2. 開啟事務
        3. 增刪改查操作
        4. 提交事務
        5. 關閉連接

?

2? 對數據進行添加(insert)

?

? ? 插入操作使用 session.save(類對象)如上述代碼14行所示。

?? ?可以使用session.saveorupdate(類對象),由hibernate判斷是添加還是更新。

?

 saveorupdate與sava的區別,以及saveorupdate的好處?

???????????? ?save是返回插入數據的主見的,而saveOrUpdate是void

? save方法更適用與確定了是要插入,而且需要得到插入數據的主鍵而saveOrUpdate更傾向于不確定是插入還是更新,而且你不需要得到他的主鍵?

? 另一方面,如果你無法確定你要插入或更新的對象是不是持久態或游離態時。如果你save一個持久態或更新一個游離態,這都是有問題的,

? 此時你就要用到???? saveOrUpdat

? 總體來說,如果你能確定你即將操作對象的狀態,則不需要用saveOrUpdate

?

 1 public void TestInsert() throws Exception{
2 User user= new User(); //初始化User
3 user.setId(1); //設置屬性的數據
4 user.setName("藍冰竹齋");
5 user.setPwd("123");
6
7 Configuration config=new Configuration().configure(); // 加載總配置文件
8 SessionFactory sessionFactory= config.buildSessionFactory(); // 建立工廠
9 Session session=null; //定義Session
10 Transaction tx=null; // 定義事務
11 try{
12 session=sessionFactory.openSession(); // 通過工廠建立連接
13 tx=session.beginTransaction(); // 通過連接開啟事務
14 session.save(user); // 通過連接保存user
15 tx.commit(); // 提交
16
17 }catch(Exception e){
18 tx.rollback(); // 出現異常回滾
19
20 }finally{
21 if(session!=null){
22 session.close(); // 關閉連接
23 }
24 if(sessionFactory!=null){
25 sessionFactory.close(); // 關閉連接工廠
26 }
27 }
28 }

測試后打印出的語句:Hibernate: insert into user (name, pwd) values (?, ?)

?

3?對數據進行修改(update)

?

?修改操作使用session.save(類對象),根據表id知道要修改的對象。 如果id不存在,出現異常org.hibernate.StaleStateException

?如果某列不需要更新,需要在映射文件的相應<property>中加入 update="false",如不更新name,

 <propertyname="pwd" column="pwd"? update="false"></property>

? 更新時需要將表中所有字段數據進行設置,不設置的字段,其值默認為null.

?可以使用session.saveorupdate(類對象),由hibernate判斷是添加還是更新。

?

public void TestUpdate() throws Exception{
User user= new User();
user.setId(1);
user.setName("藍冰"); //對name進行了修改
user.setPwd("1321121"); //對pwd進行了修改

Configuration config=new Configuration().configure();
SessionFactory sessionFactory= config.buildSessionFactory();
Session session=null;
Transaction tx=null;
try{
session=sessionFactory.openSession();
tx=session.beginTransaction();
session.update(user); //修改數據
tx.commit();

}catch(Exception e){
tx.rollback();

}finally{
if(session!=null){
session.close();
}
if(sessionFactory!=null){
sessionFactory.close();
}
}
}

Hibernate: update user set name=?, pwd=? where id=?

?

4?刪除數據(deleted)

?

修改操作使用session.delete(類對象)

注意,只能通過id來刪除數據,不能通過title或content來刪除,會報缺少標示符錯誤。

public void TestDelete() throws Exception{
User user= new User();
user.setId(1);
user.setName("藍冰竹齋1"); //根據ID刪除,設置其他屬性不起作用
user.setPwd("1321121");

Configuration config=new Configuration().configure();
SessionFactory sessionFactory= config.buildSessionFactory();
Session session=null;
Transaction tx=null;
try{
session=sessionFactory.openSession();
tx=session.beginTransaction();
session.delete(user); //刪除數據
tx.commit();

}catch(Exception e){
tx.rollback();

}finally{
if(session!=null){
session.close();
}
if(sessionFactory!=null){
sessionFactory.close();
}
}
}


Hibernate: delete from user where id=?

?


5?查詢數據(select)

?

通過ID進行查詢。

查詢有兩種方式,1 session.get(類.class,id);

????????????????????? 2 session.load(類.class,id);

??????????????????????????? 類名.class 返回這個類的Class類型對象

load 支持懶加載,既使用對象時才執行。調用getID() ?和 getclass()兩個方法不執行。

兩者的區別會在后面詳細說明。

public void TestSelect() throws Exception{
User user1=null; // 用戶1,使用get方法查詢
User user2=null; // 用戶2,使用load方法查詢

Configuration config=new Configuration().configure();
SessionFactory sessionFactory= config.buildSessionFactory();
Session session=null;
Transaction tx=null;
try{
session=sessionFactory.openSession();
tx=session.beginTransaction();
user1=(User) session.get(User.class, 3); //用戶1 get查詢 get方法中第一個字段是查詢的類.class,第二個參數是id
            user2=(User) session.load(User.class, 3);   //用戶2  load查詢   參數同上

System.out.println(user1.getName()+"user1用戶");
System.out.println(user2.getPwd()+"user2用戶");
tx.commit();

}catch(Exception e){
tx.rollback();

}finally{
if(session!=null){
session.close();
}
if(sessionFactory!=null){
sessionFactory.close();
}
}
}

Hibernate: select user0_.id as id0_0_, user0_.name as name0_0_, user0_.pwd as pwd0_0_ from user user0_ where user0_.id=?

轉載于:https://www.cnblogs.com/zilong882008/archive/2011/11/03/2234859.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/380118.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/380118.shtml
英文地址,請注明出處:http://en.pswp.cn/news/380118.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Direct3D中的繪制(3)

立方體——只比三角形稍微復雜一點&#xff0c;這個程序渲染一個線框立方體。 這個簡單的繪制和渲染立方體的程序的運行結果如下圖所示&#xff1a; 源程序&#xff1a; /************************************************************************************** Renders a …

遠控免殺專題(19)-nps_payload免殺

免殺能力一覽表 幾點說明&#xff1a; 1、上表中標識 √ 說明相應殺毒軟件未檢測出病毒&#xff0c;也就是代表了Bypass。 2、為了更好的對比效果&#xff0c;大部分測試payload均使用msf的windows/meterperter/reverse_tcp模塊生成。 3、由于本機測試時只是安裝了360全家桶…

VS2005中使用WebDeploymentProject的問題

近來做Web項目&#xff0c;VS2005中發布網站時默認發布大批的程序集&#xff0c;這給升級網站時造成很大麻煩&#xff0c;所以偶從MS下載了個WebDeploymentProject的插件&#xff08;下載地址http://download.microsoft.com/download/c/c/b/ccb4877f-55f7-4478-8f16-e41886607a…

操作系統中的多級隊列調度

多級隊列調度 (Multilevel queue scheduling) Every algorithm supports a different class of process but in a generalized system, some process wants to be scheduled using a priority algorithm. While some process wants to remain in the system (interactive proce…

編寫一程序,輸入一個字符串,查找該字符串中是否包含“abc”。

import java.lang.String.*;//這里調用java.long.String.contains()方法&#xff1b; import java.util.Scanner; public class shit {public static void main(String[] args) {Scanner wsq new Scanner(System.in);String str wsq.next();boolean status str.contains(&qu…

顯示消息提示對話框(WebForm)

1: /// <summary>2: /// 顯示消息提示對話框。3: /// Copyright (C) Maticsoft4: /// </summary>5: public class MessageBox6: { 7: private MessageBox()8: { 9: }10: 11: …

借助格式化輸出過canary保護

0x01 canary保護機制 棧溢出保護是一種緩沖區溢出攻擊緩解手段&#xff0c;當函數存在緩沖區溢出攻擊漏洞時&#xff0c;攻擊者可以覆蓋棧上的返回地址來讓shellcode能夠得到執行。當啟用棧保護后&#xff0c;函數開始執行的時候會先往棧里插入cookie信息&#xff0c;當函數真…

什么叫灰度圖

任何顏色都有紅、綠、藍三原色組成&#xff0c;假如原來某點的顏色為RGB(R&#xff0c;G&#xff0c;B)&#xff0c;那么&#xff0c;我們可以通過下面幾種方法&#xff0c;將其轉換為灰度&#xff1a; 1.浮點算法&#xff1a;GrayR*0.3G*0.59B*0.11 2.整數方法&#xff1a;Gra…

各抓包軟件的之間差異_系統軟件和應用程序軟件之間的差異

各抓包軟件的之間差異什么是軟件&#xff1f; (What is Software?) Software is referred to as a set of programs that are designed to perform a well-defined function. A program is a particular sequence of instructions written to solve a particular problem. 軟件…

輸入一字符串,統計其中有多少個單詞(單詞之間用空格分隔)(java)

import java.util.*; class Example3{public static void main(String args[]){Scanner sc new Scanner(System.in);String s sc.nextLine();//這里的sc.nextLine&#xff08;&#xff09;空格也會記數&#xff1b;StringTokenizer st new StringTokenizer(s," ")…

為何苦命干活的人成不了專家?

所謂熟能生巧&#xff0c;但離專家卻有一個巨大的鴻溝&#xff0c;在農田干活的農民怎么也成不了水稻專家&#xff0c;推廣之&#xff0c;那些在本職工作上勤勤懇懇的人&#xff0c;在業務上總有一個不可沖破的瓶頸。 這種現象非常普遍&#xff0c;這就是為什么很多人很勤奮&am…

今天發布一個新網站www.heijidi.com

新網站發布了&#xff0c;歡迎訪問&#xff0c;關于國產機的 網站 www.heijidi.com 轉載于:https://www.cnblogs.com/liugod/archive/2008/03/26/1122753.html

ret2shellcdoe

ret2shellcode的關鍵是找到一個緩沖區&#xff0c;這個緩沖區是可讀寫寫可執行的&#xff0c;我們要想辦法把我們的shellcdoe放到這個緩沖區&#xff0c;然后跳轉到我們的shellcode處執行。 例子&#xff1a; #include <stdio.h> #include <string.h> char str1[…

stl取出字符串中的字符_從C ++ STL中的字符串訪問字符元素

stl取出字符串中的字符字符串作為數據類型 (String as datatype) In C, we know string basically a character array terminated by \0. Thus to operate with the string we define character array. But in C, the standard library gives us the facility to use the strin…

Object類的hashCode()方法

public class day11 {public static void main(String[] args) {Object obj1 new Object();int hashCode obj1.hashCode();System.out.println(hashCode);}} hashCode public int hashCode()返回該對象的哈希碼值。支持此方法是為了提高哈希表&#xff08;例如 java.util.Ha…

調整Tomcat上的參數提高性能[轉]

Webtop Performance Test w/ Tomcat(調整Tomcat上的參數提高性能) Login several users with one second between each login. After the 25th user, the users begin to experience poor performance, to the point where some users are receiving “Page cannot be display…

RecordSet中的open完全的語法

RecordSet中的open完全的語法是:SecordSet.Open Source,ActiveConnection,CursorType,LockType,Options例如&#xff1a; rs.open sql,conn,1,3CursorTypeadOpenForwardOnly 0 默認游標類型, 為打開向前游標, 只能在記錄集中向前移動。adOpenKeyset 1 打開鍵集類型的游標, 可以…

用篩選法求100之內的素數

#include <stdio.h> int main() {int i ,j ,a[100];//定義一個數組存放1~100&#xff1b;for(i2; i<100; i)//由于1既不是素數也不是質素&#xff0c;所以不用考慮1&#xff0c;直接從2開始&#xff1b;{a[i]i;//以次賦值&#xff0c;2~100&#xff1b;for(j2; j<i…

遠控免殺專題(20)-GreatSCT免殺

轉載&#xff1a;https://mp.weixin.qq.com/s/s9DFRIgpvpE-_MneO0B_FQ 免殺能力一覽表 幾點說明&#xff1a; 1、上表中標識 √ 說明相應殺毒軟件未檢測出病毒&#xff0c;也就是代表了Bypass。 2、為了更好的對比效果&#xff0c;大部分測試payload均使用msf的windows/mete…

Java LinkedList對象的get(int index)方法與示例

LinkedList對象的get(int索引)方法 (LinkedList Object get(int index) method) This method is available in package java.util.LinkedList.get(int index). 軟件包java.util.LinkedList.get(int index)中提供了此方法。 This method is used to retrieve an object or eleme…