⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 personidcardservice.java

📁 Hibernate的精典实例
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -