數據庫:oracle 10g
開發環境:Myeclipse8+
數據庫結構:
-- Create table
create table STUDENT
(
SID NUMBER not null,
SNAME VARCHAR2(10),
SNO CHAR(10),
SAGE NUMBER,
SSEX CHAR(1),
SBIRTHDAY DATE
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table STUDENT
add constraint PK_STUDENT primary key (SID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
1)根據主鍵查找:
public void testFind() {
Session session = HibernateSessionFactory.getSession();
Student s = (Student) session.load(Student.class, 1234);//與get的區別:load若主鍵值不存在,則拋出異常
// Student s = (Student) session.get(Student.class, 1234);//而get使用時,主鍵不存在,返回的是null,推薦使用
System.out.println(s);
HibernateSessionFactory.closeSession();
}
2)根據主鍵刪除:
public void testDelete(){
Session session = HibernateSessionFactory.getSession();
Student s = new Student();
s.seSid(1234);
Transaction tran =session.beginTransaction();
session.delete(s);
tran.commit();//要記得提交,否則去查看數據庫就可以看到數據並沒有刪除
HibernateSessionFactory.closeSession();
}
3)根據主鍵更新:
public void testUpdate1() {
Session session = HibernateSessionFactory.getSession();
Object obj = session.get(Tuser.class, 1234);
if (obj != null) {
Student s = (Student) obj;user.setSname("zhangfei");Transaction tran = session.beginTransaction();session.update(s);tran.commit();}HibernateSessionFactory.closeSession();}
4)增加記錄:
public void testSave() {
Session session = HibernateSessionFactory.getSession();
Student s = new Student();
s.setSid(1234);
s.setSname("zhangfei");
s.setSno("s001");
s.setSsex("1");
s.setSbirthday(new Date());
Transaction tran = session.beginTransaction(); // save,update,delete都需要加transaction
session.save(s);
tran.commit();
HibernateSessionFactory.closeSession();
}
未完。