personidcardservice.java

来自「Hibernate的精典实例」· Java 代码 · 共 116 行

JAVA
116
字号
package hibernate.demo.onetoone;

import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;


public class PersonIdCardService {
	public static SessionFactory sf;
	static {
		try {
			Configuration config = new Configuration();
			config.addClass(Persons.class);
			config.addClass(IDCards.class);
			sf = config.buildSessionFactory();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	public void queryPerson()throws Exception{
		Session session=null;
		Transaction tx=null;
		try{
			session=sf.openSession();
			tx=session.beginTransaction();
			Persons person=(Persons)session.get(Persons.class, new Integer(2));
			//System.out.println(person.getPersonName());
			//System.out.println(person.getIdcards().getCardno());
			tx.commit();
		}catch(Exception ex){
			if(tx!=null){
				tx.rollback();
			}
			ex.printStackTrace();
		}finally{
			session.close();
		}
		
	}
	public void saveIDCard(IDCards idcard)throws Exception{
		Session session=null;
		Transaction tx=null;
		try{
			session=sf.openSession();
			tx=session.beginTransaction();
			session.save(idcard);
			tx.commit();
		}catch(Exception ex){
			if(tx!=null){
				tx.rollback();
			}
			ex.printStackTrace();
		}finally{
			session.close();
		}
	}
	
	public void savePerson(Persons person)throws Exception{
		Session session=null;
		Transaction tx=null;
		try{
			session=sf.openSession();
			tx=session.beginTransaction();
			session.save(person);
			tx.commit();
		}catch(Exception ex){
			if(tx!=null){
				tx.rollback();
			}
			ex.printStackTrace();
		}finally{
			session.close();
		}
	}
	public void deletePerson(Integer id)throws Exception{
		Session session=null;
		Transaction tx=null;
		try{
			session=sf.openSession();
			tx=session.beginTransaction();
			Persons person=(Persons)session.get(Persons.class, id);
			session.delete(person);
			tx.commit();
		}catch(Exception ex){
			if(tx!=null){
				tx.rollback();
			}
			ex.printStackTrace();
		}finally{
			session.close();
		}
	}
	public void test()throws Exception{
		try{
			queryPerson();
			IDCards idcard=new IDCards();
			Persons persons=new Persons(idcard,"ghn",1,25,java.sql.Date.valueOf("2007-07-12"));
			idcard.setCardno("423456789012345667");
			
			idcard.setPerson(persons);
			persons.setIdcards(idcard);
			this.savePerson(persons);
			//this.saveIDCard(idcard);
			this.deletePerson(new Integer(1));
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public static void main(String[] args) throws Exception{
		new PersonIdCardService().test();
		sf.close();
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?