hibernate的增删改查
package com.endual.test;
import java.util.ArrayList;
import java.util.Date;
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;
import com.endual.model.Person;
import junit.framework.TestCase;
public class T extends TestCase {
?
??? @Override
??? protected void setUp() throws Exception {
??? ??? // TODO Auto-generated method stub
??? ??? super.setUp();
??? }
??? @Override
??? protected void tearDown() throws Exception {
??? ??? // TODO Auto-generated method stub
??? ??? super.tearDown();
??? }
??? public void testSave(){
??? ???
??? ??? Configuration cfg = new Configuration().configure();
??? ??? SessionFactory sf = cfg.buildSessionFactory();
??? ???
??? ??? ?Session session = sf.openSession();
??? ???
??? ??? ?Transaction tran = session.beginTransaction();
??? ??? ?//tran.begin();
??? ???
??? ??? ?Person person = new Person();
??? ?? ??? ?person.setId(1);
??? ??? ?person.setName("ch");
??? ??? ?person.setPassword("123");
??? ??? ?person.setCreateTime(new Date());
??? ??? ?person.setExpireTime(new Date());//事务层
??? ??? ?
??? ??? ?session.update(person);//持久层
??? ??? ?
??? ??? ?
??? ??? ?tran.commit();
??? ??? ?
??? ??? ?session.close();//游离层了
??? ??? ?
??? ???
??? }
???
public void testfind(){
??? ???
??? ??? Configuration cfg = new Configuration().configure();
??? ??? SessionFactory sf = cfg.buildSessionFactory();
??? ???
??? ??? ?Session session = sf.openSession();
??? ???
??? ??? ?Transaction tran = session.beginTransaction();
???
??? ??? //Person person =? (Person) session.get(Person.class, 5);
??? ???
??? ??? ?Person person =? (Person)session.load(Person.class, 5);
??? ??? ?tran.commit();
??? ??? ?
??? ??? ?session.close();//游离层了
??? ??? ?
??? ??? //int a = person.getId();
??? ??? //System.out.println(a);
??? }
public void testDel(){
???
??? Configuration cfg = new Configuration().configure();
??? SessionFactory sf = cfg.buildSessionFactory();
???
??? ?Session session = sf.openSession();
???
??? ?Transaction tran = session.beginTransaction();
??? // Person person =? (Person) session.get(Person.class, 1);
??? ?
??? ?Person person = new Person();
??? ?person.setId(1);
??? ?session.delete(person);
??? ?tran.commit();
??? ?
??? ?session.close();//游离层了
???
}
public void testfindAll(){
???
??? Configuration cfg = new Configuration().configure();
??? SessionFactory sf = cfg.buildSessionFactory();
??? ?Session session = sf.openSession();
??? ?Transaction tran = session.beginTransaction();
??? //Person person =? (Person) session.get(Person.class, 5);
??? ?List<Person> list = new ArrayList<Person>();
???? Query query = session.createQuery("from Person");
???? list = query.list();
???? System.out.print(list.size());
???? tran.commit();
??? ?session.close();//游离层了
??? ?
??? //int a = person.getId();
??? //System.out.println(a);
}
???
}