日期:2014-05-16  浏览次数:20611 次

hibernate操作数据库的增删改查实例
package com.xaygc;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class StudentDAO {
public void save2() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
Student student = new Student("张栋", 23, "男", "13217979535", "北京");
try {
session.save(student);
t.commit();
} catch (Exception e) {
t.rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}

public void save() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
Student student = new Student("刘趁阳", 23, "男", "13217979535", "北京");
try {
session.save(student);
t.commit();
} catch (Exception e) {
t.rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}

public void update() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
Student student = new Student("刘趁阳", 24, "男", "13217979535", "北京海淀区");
student.setId(6);
try {
session.saveOrUpdate(student);
t.commit();
} catch (Exception e) {
t.rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}

public void getAll() {
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery("from com.xaygc.Student");
List<Student> students = query.list();
for (Student student : students) {
System.out.println(student);
}
HibernateSessionFactory.closeSession();

}

public void getById() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
try {
Student student = (Student) session.get(Student.class, 7);
student.setAge(23);
student.setAddress("中关村环保科技园");
t.commit();
System.out.println(student);
} catch (Exception e) {
t.rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}

public void delete() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
try {
session.delete(session.load(Student.class, 5));
t.commit();
} catch (Exception e) {
t.rollback();
}
HibernateSessionFactory.closeSession();
}

public void delete2() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
try {
Query query = session
.createQuery("delete from com.xaygc.Student where id=1");
int row = query.executeUpdate();
System.out.println(row);
t.commit();
} catch (Exception e) {
t.rollback();
}
HibernateSessionFactory.closeSession();
}

public static void main(String[] args) {
StudentDAO studentDAO = new StudentDAO();
// studentDAO.save();
// studentDAO.save2();
// studentDAO.delete2();
//studentDAO.update();
//studentDAO.getAll();
studentDAO.getById();
//studentDAO.getAll();
}
}