Hibernate學習-------資料庫增刪改查操作(部分)

來源:互聯網
上載者:User

標籤:hibernate   增刪改查   hql   update   

(1)增加和刪除

<span style="white-space:pre"></span>@Testpublic void test(){EStudent student=new EStudent();student.setName("張三");student.setSex("男");Session session=sf.openSession();session.beginTransaction();        session.save(student);//增                //刪除操作delete        EStudent s=new EStudent();        s.setId(4);//設定ID        session.delete(s);        session.getTransaction().commit();        session.close();}
(2)get和Load查詢,注意兩個的區別

<span style="white-space:pre"></span>@Testpublic void testLoad()//Load讀取資料庫{Session session=sf.openSession();session.beginTransaction();//參數分別為EStudent實體類和要查詢的主鍵//Load只有當需要查詢的對象的時候(比如getName)時才會產生並執行SQL語句//返回的是代理對象EStudent s=(EStudent) session.load(EStudent.class, 1);System.out.println(s.getId()+"--"+s.getName());session.getTransaction().commit();//System.out.println(s.getId()+"--"+s.getName());//如果只有在這使用到查詢的對象的屬性方法會報錯session.close();}@Testpublic void testGet()//get讀取資料庫{Session session=sf.openSession();session.beginTransaction();//參數分別為EStudent實體類和要查詢的主鍵//立即產生並執行SQL語句EStudent s=(EStudent) session.get(EStudent.class, 1);System.out.println(s.getId()+"--"+s.getName());session.getTransaction().commit();session.close();}

(3)update更新操作


@Testpublic void testUpdate()//更新資料庫{Session session=sf.openSession();session.beginTransaction();//先查詢再修改,如果修改後的屬性跟原來的相同則不進行更新//參數分別為EStudent實體類和要查詢的主鍵//立即產生並執行SQL語句EStudent s=(EStudent) session.get(EStudent.class, 1);s.setName("dou豆1");session.update(s);//先建立一個新的對象,設定ID再修改,如果不設定ID,會出錯//如果只設定了部分屬性,則未設定的屬性會為空白值或者預設值EStudent s2=new EStudent();s2.setId(6);//資料庫中存在,如果設定的ID在資料庫中不存在同樣會出錯s2.setName("豆豆豆豆");session.update(s2);session.getTransaction().commit();session.close();}

(4)HQL更新操作

@Testpublic void testUpdateHQL()//更新資料庫  使用HQL{Session session=sf.openSession();session.beginTransaction();//org.hibernate.Query    注意Update的對象Query q=session.createSQLQuery("Update newtablestudent set name='張三' where name='豆豆豆豆'");q.executeUpdate();//更新session.getTransaction().commit();session.close();}




Hibernate學習-------資料庫增刪改查操作(部分)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.