Hibernate笔记之JDBC入门

最近在学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 }

猜你喜欢

转载自www.cnblogs.com/wicosad/p/9879695.html