Java工作笔记-使用Hibernate连接mysql数据库并进行增、删、改、查!
生活随笔
收集整理的這篇文章主要介紹了
Java工作笔记-使用Hibernate连接mysql数据库并进行增、删、改、查!
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
環境要求
增加數據庫記錄
查詢數據
修改數據庫記錄
刪除數據庫記錄
?
環境要求
導入好Hibernate相關jar包,
并且對每一個表都生成了POJO類!
?
增加數據庫記錄
表結構如下:
?
這里使用Hibernate生成的POJO類如下:
Student.java
package my.db;import java.util.Date;/*** Student entity. @author MyEclipse Persistence Tools*/public class Student implements java.io.Serializable {// Fieldsprivate Integer id;private String name;private String phone;private Date birthday;// Constructors/** default constructor */public Student() {}/** full constructor */public Student(Integer id, String name, String phone, Date birthday) {this.id = id;this.name = name;this.phone = phone;this.birthday = birthday;}// Property accessorspublic Integer getId() {return this.id;}public void setId(Integer id) {this.id = id;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public String getPhone() {return this.phone;}public void setPhone(String phone) {this.phone = phone;}public Date getBirthday() {return this.birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}Example.java
package my.db;/*** Example entity. @author MyEclipse Persistence Tools*/public class Example implements java.io.Serializable {// Fieldsprivate Long id;private String author;private String title;// Constructors/** default constructor */public Example() {}/** full constructor */public Example(String author, String title) {this.author = author;this.title = title;}// Property accessorspublic Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public String getAuthor() {return this.author;}public void setAuthor(String author) {this.author = author;}public String getTitle() {return this.title;}public void setTitle(String title) {this.title = title;}}?
關鍵的添加數據如下:
Test.java
package my.db;import java.text.SimpleDateFormat; import org.hibernate.Session; import org.hibernate.Transaction;public class Test {/*** @param args*/public static void main(String[] args) {Session dbss = null;try{SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");Student row = new Student();row.setId(201602);row.setName("小明");row.setPhone("18888888888");row.setBirthday(sdf.parse("1888-8-8"));Example re = new Example();re.setAuthor("小明");re.setTitle("裝逼指南");/*連接數據庫*/dbss = HibernateSessionFactory.getSession();Transaction dbtr = dbss.beginTransaction();dbss.save(row);dbss.save(re);dbtr.commit();System.out.println("數據庫生成的小明的ID " + re.getId());System.out.println("測試成功!");}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss!= null) dbss.close();}}}運行截圖如下:
表內容如下:
?
?
查詢數據
查詢數據有3種分別是:
test1:按主鍵查詢
test2:HQL查詢 (Hibernate Query Language)
test3:Native SQL 查詢
?
源碼如下:
package my.db;import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction;public class Test {public static void test1(){Session dbss = null;try{//連接數據庫dbss = HibernateSessionFactory.getSession();Integer rowid = new Integer(201602);Student row = (Student)dbss.get(Student.class, rowid);if(row == null){System.out.println("找不到記錄!");}else{System.out.println("姓名:" + row.getName() + ",電話:" + row.getPhone());}}catch(Exception e){System.out.println("出錯:" + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void test2(){Session dbss = null;try{//連接數據庫dbss = HibernateSessionFactory.getSession();String hql = "from my.db.Student where id > 201601";List<Student> results = dbss.createQuery(hql).list();if(results.size() == 0){System.out.println("找不到記錄!");}else{for(Student row: results){System.out.println("姓名:" + row.getName() + ",電話:" + row.getPhone());}}}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void test3(){Session dbss = null;try{dbss = HibernateSessionFactory.getSession();String sql = "SELECT * FROM testwebdb.student";List<Object[]> results = dbss.createSQLQuery(sql).list();for(Object[] row : results){Integer id = Integer.valueOf( row[0].toString() );String name = row[1].toString();String phone = row[2].toString();String brithday = row[3].toString(); // System.out.println("學號" + id + "姓名:" + name + ",電話:" + phone + ",生日" + brithday);}}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if (dbss != null)dbss.close();}}public static void main(String[] args) {//test1();//test2();//test3();}}?
修改數據庫記錄
修改數據有3種分別是:
test1:按主鍵查詢
test2:HQL查詢 (Hibernate Query Language)
test3:Native SQL 查詢
源碼如下:
package my.db;import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction;public class Test {public static void test1(){Session dbss = null;try{dbss = HibernateSessionFactory.getSession();Integer rowid = new Integer(201602);Student row = (Student)dbss.get(Student.class, rowid);if(row != null){row.setPhone("16666666666");//保存到數據Transaction dbtr = dbss.beginTransaction();dbss.update(row);dbtr.commit();}}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void test2(){Session dbss = null;try{dbss = HibernateSessionFactory.getSession();Transaction dbtr = dbss.beginTransaction();String hql = "UPDATE Student SET phone='12233330000' WHERE id='201602'";int rowsAffected = dbss.createQuery(hql).executeUpdate();System.out.print(rowsAffected + " rows affected.");dbtr.commit();}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void test3(){Session dbss = null;try{/* 連接數據庫 */dbss = HibernateSessionFactory.getSession();// 構造一個普通的SQL語句Transaction dbtr = dbss.beginTransaction();String sql = "UPDATE student SET `phone`='13355550000' WHERE id='201601' ";int rowsAffected = dbss.createSQLQuery(sql).executeUpdate(); System.out.println(rowsAffected + " rows affected.");}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void main(String[] args) {//test1();//test2();test3();}}?
刪除數據庫記錄
刪除數據有3種分別是:
test1:按主鍵查詢
test2:HQL查詢 (Hibernate Query Language)
test3:Native SQL 查詢
源碼如下:
package my.db;import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction;public class Test {public static void test1(){Session dbss = null;try{dbss = HibernateSessionFactory.getSession();Integer rowid = new Integer(201601);Student row = (Student)dbss.get(Student.class, rowid);if(row != null){Transaction dbtr = dbss.beginTransaction(); dbss.delete(row);dbtr.commit();}}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void test2(){Session dbss = null;try{dbss = HibernateSessionFactory.getSession();Transaction dbtr = dbss.beginTransaction();String hql = "delete from Student where id='201602' ";int rowsAffected = dbss.createQuery(hql).executeUpdate(); System.out.println(rowsAffected + " rows affected.");dbtr.commit();}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void test3(){Session dbss = null;try{/* 連接數據庫 */dbss = HibernateSessionFactory.getSession();// 構造一個普通的SQL語句Transaction dbtr = dbss.beginTransaction();String sql = "DELETE FROM `student` WHERE id='201603' ";int rowsAffected = dbss.createSQLQuery(sql).executeUpdate(); System.out.println(rowsAffected + " rows affected.");dbtr.commit();}catch(Exception e){System.out.println("出錯: " + e.getMessage());e.printStackTrace();}finally{if(dbss != null)dbss.close();}}public static void main(String[] args) {//test1();//test2();test3();}}?
總結
以上是生活随笔為你收集整理的Java工作笔记-使用Hibernate连接mysql数据库并进行增、删、改、查!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式工作笔记-简单工厂场景与实现(针
- 下一篇: Qt文档阅读笔记-QStyledItem