1. 程式人生 > >Hibernate筆記之JDBC入門

Hibernate筆記之JDBC入門

行修改 localhost 由於 span ava soft prim 學校 文檔

最近在學Hibernate,學校的專業課安排,雖然不是很想學,但是畢竟還有期末考試和課程設計,於是還是學了一些。

剛上了幾節課,都沒怎麽聽過,所以昨天的實驗課開始向百度求救並查書,讀了一些代碼,也算勉強完成了第一次實驗,所以想將這些記錄下來。

廢話不多說了,開始正題。

像我一樣作為一個初學者剛開始接觸Hibernate的話會有無從下手的感覺,我也是摸索著前行,所以第一步開始學習JDBC的一些操作。

我使用的數據庫是MySQL 5.5.62, 連接器是mysql-connector-java-8.0.13,連接器從8.0版本開始,在連接數據庫時會和以前的版本有一些小區別,已在後文的代碼註釋中說明。

以我的實驗內容為例,首先需要兩個表,一個是STUDENT表,一個是CLASSROOM表,然後針對STUDENT表進行增刪改查四個基礎操作。

表結構如下圖,需要將兩個表結構轉換成Java代碼的形式,這裏我由於對Java中的Date類型不熟悉,於是將Date類型用String表示,有能力者可自行修改。。

STUDENT:

技術分享圖片

 1  
2
3 public class Student { 4 private long Id; 5 private String Name; 6 private String Birthday; 7 private long Classroom_id; 8 //帶primary_key的構造參數,用於update和delete 9 public Student(long
id, String name, String birthday, long classroom_id) {   10 this.Id = id; 11 this.Name = name; 12 this.Birthday = birthday; 13 this.Classroom_id = classroom_id; 14 } 15 //不帶primary_key的構造參數,用於insert 16 public Student(String name, String birthday, long classroom_id) { 
17 this.Name = name; 18 this.Birthday = birthday; 19 this.Classroom_id = classroom_id; 20 } 21 22 public long getId() { 23 return Id; 24 } 25 26 public void setId(long id) { 27 Id = id; 28 } 29 30 public String getName() { 31 return Name; 32 } 33 34 public void setName(String name) { 35 Name = name; 36 } 37 38 public String getBirthday() { 39 return Birthday; 40 } 41 42 public void setBirthday(String birthday) { 43 Birthday = birthday; 44 } 45 46 public long getClassroom_id() { 47 return Classroom_id; 48 } 49 50 public void setClassroom_id(long classroom_id) { 51 Classroom_id = classroom_id; 52 } 53 54 55 }

CLASSROOM:

技術分享圖片

 1  
2
3 public class Classroom { 4 private long Id; 5 private String Name; 6 private String Site; 7 8 public Classroom(long id, String name, String site) {   9 this.Id = id; 10 this.Name = name; 11 this.Site = site; 12 } 13 14 public long getId() { 15 return Id; 16 } 17 18 public void setId(long id) { 19 Id = id; 20 } 21 22 public String getName() { 23 return Name; 24 } 25 26 public void setName(String name) { 27 Name = name; 28 } 29 30 public String getSite() { 31 return Site; 32 } 33 34 public void setSite(String site) { 35 Site = site; 36 } 37 38 }

由於第一次接觸到JDBC相關的內容,所以對主鍵的處理不是很懂,所以Student寫了兩個構造用於不同的用途,感覺自己寫的不是很好,還望大牛們看到多多包涵,如果願意可以留下建議,我會改正。

然後是增刪改查四個操作,我將這些都封裝到了Operation類中,先上代碼:

  1 import java.sql.Connection;
  2 import java.sql.DriverManager;
  3 import java.sql.PreparedStatement;
  4 import java.sql.ResultSet;
  5 import java.sql.SQLException;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 
  9 public class Operation {
 10     private String Url = "jdbc:mysql://localhost:3306/exerciseone?serverTimezone=UTC";  
                      //加?serverTimezone=UTC是為了解決數據庫和系統時區差異的問題
11 private String Username = "root"; 12 private String Password = "*****";  //此處填寫你的密碼 13 14 private Connection getConnection() throws Exception {  //連接數據庫 15 Class.forName("com.mysql.cj.jdbc.Driver");  
        //在連接器8.0中對於過去的com.mysql.jdbc.Driver已經不支持,需要修改成我寫的這樣
16 return DriverManager.getConnection(Url, Username, Password); 17 } 18 //實現主鍵的自動增長,在insert時調用,保證id的連續性和正確性,個人理解 19 private long getNextId(Connection conn, String tableName) throws Exception {  20 long nextId = 0; 21 PreparedStatement pstmt = null; 22 ResultSet rs = null; 23 try { 24 String sql = "select max(ID) from " + tableName;  //查詢語句 25 pstmt = conn.prepareStatement(sql); 26 rs = pstmt.executeQuery();  //獲取查詢結果 27 if(rs.next()) { 28 nextId = rs.getLong(1) + 1; 29 if(rs.wasNull())  30 nextId = 1; 31 } 32 else { 33 nextId = 1; 34 } 35 return nextId; 36 }finally { 37 try { 38 rs.close(); 39 pstmt.close(); 40 }catch(Exception e){ 41 e.printStackTrace(); 42 } 43 } 44 } 45 //插入操作,主鍵id自動增長,對應插入name, birthday, classroom_id 46 public void insert(Student stu) throws Exception { 47 Connection conn = null; 48 PreparedStatement pstmt = null; 49 try { 50 conn = getConnection(); 51 conn.setAutoCommit(false); 52 if(stu.getName() == null) 53 throw new Exception("學生姓名不允許為空 "); 54 String sql = "insert into student (ID, NAME, BIRTHDAY, CLASSROOM_ID) values(?,?,?,?)"; 55 pstmt = conn.prepareStatement(sql); 56 long stuId = getNextId(conn, "student"); 57 pstmt.setLong(1, stuId); 58 pstmt.setString(2, stu.getName()); 59 pstmt.setString(3, stu.getBirthday()); 60 pstmt.setLong(4, stu.getClassroom_id()); 61 pstmt.executeUpdate(); 62 conn.commit(); 63 }catch (Exception e) { 64 e.printStackTrace(); 65 try { 66 conn.rollback(); 67 }catch(SQLException sqle) { 68 sqle.printStackTrace(System.out); 69 } 70 throw e; 71 }finally { 72 try { 73 pstmt.close(); 74 conn.close(); 75 }catch(Exception e) { 76 e.printStackTrace(); 77 } 78 } 79 } 80 //更新操作, 根據給出的主鍵id找到對應的學生進行相應的修改 81 public void update(Student stu) throws Exception { 82 Connection conn = null; 83 PreparedStatement pstmt = null; 84 try{ 85 conn = getConnection(); 86 conn.setAutoCommit(false); 87 String sql = "update student set NAME = ?, BIRTHDAY = ?, CLASSROOM_ID = ? where ID = ?"; 88 pstmt = conn.prepareStatement(sql); 89 pstmt.setString(1, stu.getName()); 90 pstmt.setString(2, stu.getBirthday()); 91 pstmt.setLong(3, stu.getClassroom_id()); 92 pstmt.setLong(4, stu.getId()); 93 pstmt.executeUpdate(); 94 conn.commit(); 95 }catch (Exception e) { 96 try { 97 conn.rollback(); 98 }catch(SQLException sqle){ 99 sqle.printStackTrace(); 100 } 101 throw e; 102 }finally{ 103 pstmt.close(); 104 conn.close(); 105 } 106 } 107 //刪除操作,根據主鍵id刪除對應的學生信息 108 public void delete(Student stu) throws Exception { 109 Connection conn = null; 110 PreparedStatement pstmt = null; 111 try{ 112 conn = getConnection(); 113 conn.setAutoCommit(false); 114 String sql = "delete from student where " + "ID = ?"; 115 pstmt = conn.prepareStatement(sql); 116 pstmt.setLong(1, stu.getId()); 117 pstmt.executeUpdate(); 118 conn.commit(); 119 }catch(Exception e){ 120 try{ 121 conn.rollback(); 122 }catch(SQLException sqlex){ 123 sqlex.printStackTrace(System.out); 124 } 125 throw e; 126 }finally{ 127 try{ 128 pstmt.close(); 129 conn.close(); 130 }catch(Exception e){ 131 e.printStackTrace(); 132 } 133 } 134 } 135 //查找操作,根據給出的班級信息,獲取其中的班級Id然後調用SQL語句查詢對應班級的學生,用List存儲並返回 136 public List<Student> findStudentByClassroom(Classroom room) throws Exception{ 137 List<Student> result = new ArrayList<Student>(); 138 Connection conn = null; 139 PreparedStatement pstmt = null; 140 ResultSet rs = null; 141 try { 142 conn = getConnection(); 143 conn.setAutoCommit(false); 144 String sql = "select * from student where CLASSROOM_ID = ?"; 145 pstmt = conn.prepareStatement(sql); 146 pstmt.setLong(1, room.getId()); 147 rs = pstmt.executeQuery(); 148 System.out.println("ID |\t" + "NAME |\t" + "BIRTHDAY |\t" + "CLASSROOM_ID"); 149 while(rs.next()) { 150 Student stu = new Student(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getLong(4)); 151 result.add(stu); 152 } 153 }finally{ 154 try { 155 rs.close(); 156 pstmt.close(); 157 conn.close(); 158 }catch(Exception e) { 159 e.printStackTrace(); 160 } 161 } 162 return result; 163 } 164 }

上面的代碼中用到了很多JDBC中的方法,這些都是JDBC提供的,直接調用即可,由於我也是初學者,所以在這裏對詳細用法不會進行詳解(因為我也不太懂),大家可查閱文檔學習相關內容。

我針對我的代碼,講解以下我的思路。

首先是數據庫的連接,給出對應的接口及數據庫的名稱,然後寫好用戶名和密碼,之後在getConnection方法中調用相應的內容進行數據庫的連接。

在之後的幾個操作中都需要先調用getConnection連接數據庫,當然try,catch,finally等都是為了保證操作的可靠性和正確性。

之後是插入操作,這裏我先寫了一個getNextId方法來實現主鍵ID的自動增長,先調用SQL語句進行查詢,獲取查詢結果後進行相應操作。邏輯是取當前最大的主鍵值+1,如果表中不含記錄則返回1。

然後在insert中寫出對應的SQL語句,調用getNextId設置ID,然後通過Student傳來的內容實現對NAME, BIRTHDAY, CLASSROOM_ID的插入。

之後的update和delete操作與insert類似,不同之處在於SQL語句的不同。我這裏是根據主鍵ID來進行修改和刪除。

最後是一個根據CLASSROOM_ID查找學生的操作,利用List存儲查詢結果。

我這裏提供了一個測試的主函數方便大家調試和理解:

 1 import java.util.Iterator;
 2 import java.util.List;
 3 
 4 public class Main {
 5 
 6     public static void main(String[] args) throws Exception {
 7         Operation op = new Operation();
 8         Student stu = new Student("user1", "20181029", 1);
 9         op.insert(stu);
10         stu = new Student("user2", "20181028", 1);
11         op.insert(stu);
12         stu = new Student("user3", "20181027", 1);
13         op.insert(stu);
14         stu = new Student("user4", "20181026", 2);
15         op.insert(stu);
16         stu = new Student("user5", "20181025", 2);
17         op.insert(stu);
18         stu = new Student("user7", "20181020", 1);
19         op.insert(stu);
20         stu = new Student(6, "user6", "20181024", 2);
21         op.update(stu);
22         stu = new Student(6, "", "", 0);
23         op.delete(stu);
24         Classroom room = new Classroom(1, "software162", "xxx");
25         List<Student> list = op.findStudentByClassroom(room);
26         Iterator<Student> it = list.iterator();
27         while(it.hasNext()) {
28             Student t = (Student)it.next();
29             System.out.println(t.getId() + "\t" + t.getName() + "\t" + t.getBirthday() + "\t" + t.getClassroom_id());
30         }
31     }
32     
33 }

Hibernate筆記之JDBC入門