inversedemo.java

来自「hibernate_tutorial经典教程」· Java 代码 · 共 72 行

JAVA
72
字号
package tutorial.dev.inverse;import java.io.Serializable;import java.util.HashSet;import net.sf.hibernate.HibernateException;import net.sf.hibernate.Session;import net.sf.hibernate.SessionFactory;import net.sf.hibernate.Transaction;import net.sf.hibernate.cfg.Configuration;public class InverseDemo {	public static void main(String[] args) {		try {			new InverseDemo();		} catch(HibernateException he) {			he.printStackTrace();		}	}		public InverseDemo() throws HibernateException {		Configuration config = new Configuration();		// add the classes you want to persist		// make sure the mapping files are on the classpath		config.addClass(Hotel.class);		config.addClass(HotelRoom.class);				SessionFactory sf = config.buildSessionFactory();			Session sess = sf.openSession();		Transaction tx = null;		// store the orderlist and all products		Serializable id = null;		Hotel h = null;		try {			tx = sess.beginTransaction();			h = new Hotel();			h.setRooms(new HashSet());			h.setName("Royal");			h.getRooms().add(new HotelRoom(1));			h.getRooms().add(new HotelRoom(2));			h.getRooms().add(new HotelRoom(3));			h.getRooms().add(new HotelRoom(4));						sess.save(h);			tx.commit();		} catch (HibernateException e) {		    if (tx!=null) tx.rollback();		    throw e;		} 		finally {		    sess.close();		}		sess = sf.openSession();		// store the orderlist and all products		try {			tx = sess.beginTransaction();					h = (Hotel)sess.get(Hotel.class, h.getId());			System.out.println("Found hotel: " + h.getName() +" with " + h.getRooms().size() +" rooms");			tx.commit();		} catch (HibernateException e) {		    if (tx!=null) tx.rollback();		    throw e;		} 		finally {		    sess.close();		}	}	}

⌨️ 快捷键说明

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