inheritancedemo.java

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

JAVA
82
字号
package tutorial.inheritance.tableperhierarchy;import java.util.Iterator;import java.util.List;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 InheritanceDemo {	public static void main(String[] args) {		try {			new InheritanceDemo();		} catch(HibernateException he) {			he.printStackTrace();		}	}		public InheritanceDemo() throws HibernateException {		Configuration config = new Configuration();		// add the classes you want to persist		// make sure the mapping files are on the classpath		config.addClass(Animal.class);				SessionFactory sf = config.buildSessionFactory();				Session sess = sf.openSession();		Transaction tx = null;		try {			tx = sess.beginTransaction();						Cat cat = new Cat();			cat.setName("Silvester");			cat.setNickName("Sly");			sess.save(cat);						Cow cow = new Cow();			cow.setName("Rose");			cow.setFurColor("Brown");			sess.save(cow);   						tx.commit();		} catch (HibernateException e) {		    if (tx!=null) tx.rollback();		    throw e;		}		finally {		    sess.close();		}								sess = sf.openSession();		tx = null;		try {		    tx = sess.beginTransaction();		   		    List animals = sess.find("from " + Cat.class.getName());		    for (Iterator it = animals.iterator(); it.hasNext();) {				Animal animal = (Animal) it.next();				System.out.println(	"Animal '" + animal.getName() +									"' its class is: " + animal.getClass().getName());				System.out.print("Makes sound: ");				animal.makeSound();											}		    		    tx.commit();		}		catch (HibernateException e) {		    if (tx!=null) tx.rollback();		    throw e;		}		finally {		    sess.close();		}	}}

⌨️ 快捷键说明

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