Hibernate的级联配置 J2EE学习备忘录

作者:Magci 日期:2008-09-12 08:02 PM

1.级联是指两个对象之间的操作联动关系,对一个对象执行了操作之后,对其指定的级联对象也需要执行相同的操作;
2.级联配置通过many-to-one的cascade属性实现;
3.cascade属性有四种取值:
  all:所有操作都执行级联操作;
  none:所有操作都不执行级联操作;
  save-update:保存和更新时执行级联操作;
  delete:删除时执行级联操作;
4.通过级联操作可以解决持久化对象不能直接引用瞬时对象的问题。

hibernate.cfg.xml:
01.<?xmlversion='1.0'encoding='UTF-8'?>
02.<!DOCTYPE hibernate-configuration PUBLIC
03."-//Hibernate/Hibernate Configuration DTD 3.0//EN"
04.
06.<!-- Generated by MyEclipse Hibernate Tools.                   -->
07.<hibernate-configuration>
09.<session-factory>
10.<propertyname="connection.username">scott</property>
11.<propertyname="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:MGC</property>
12.<propertyname="dialect">org.hibernate.dialect.Oracle9Dialect</property>
13.<propertyname="myeclipse.connection.profile">MGC</property>
14.<propertyname="connection.password">tiger</property>
15.<propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
16.<propertyname="show_sql">true</property>
18.<mappingresource="cn/edu/ahau/mgc/hibernate/many2one/pojo/Group.hbm.xml"/>
19.<mappingresource="cn/edu/ahau/mgc/hibernate/many2one/pojo/User.hbm.xml"/>
21.</session-factory>
23.</hibernate-configuration>


Group.java:
01.packagecn.edu.ahau.mgc.hibernate.many2one.pojo;
03.publicclassGroup {
05.privatelongid;
06.privateString name;
08.publiclonggetId() {
09.returnid;
12.publicvoidsetId(longid) {
13.this.id = id;
16.publicString getName() {
17.returnname;
20.publicvoidsetName(String name) {
21.this.name = name;


User.java:
01.packagecn.edu.ahau.mgc.hibernate.many2one.pojo;
03.publicclassUser {
05.privatelongid;
06.privateString username;
07.privateString password;
08.privateGroup group;
10.publicGroup getGroup() {
11.returngroup;
14.publicvoidsetGroup(Group group) {
15.this.group = group;
18.publiclonggetId() {
19.returnid;
22.publicvoidsetId(longid) {
23.this.id = id;
26.publicString getUsername() {
27.returnusername;
30.publicvoidsetUsername(String username) {
31.this.username = username;
34.publicString getPassword() {
35.returnpassword;
38.publicvoidsetPassword(String password) {
39.this.password = password;


Group.hbm.xml:
01.<?xmlversion="1.0"encoding="utf-8"?>
02.<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
03.
04.<!-- 
05.Mapping file autogenerated by MyEclipse Persistence Tools
06.-->
07.<hibernate-mapping>
08.<classname="cn.edu.ahau.mgc.hibernate.many2one.pojo.Group"table="MANY2ONE_GROUP"schema="SCOTT">
09.<idname="id"type="java.lang.Long">
10.<columnname="ID"precision="22"scale="0"/>
11.<generatorclass="native"/>
12.</id>
13.<propertyname="name"type="java.lang.String">
14.<columnname="NAME"length="20"not-null="true"/>
15.</property>
16.</class>
17.</hibernate-mapping>


User.hbm.xml:
01.<?xmlversion="1.0"encoding="utf-8"?>
02.<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
03.
04.<!-- 
05.Mapping file autogenerated by MyEclipse Persistence Tools
06.-->
07.<hibernate-mapping>
08.<classname="cn.edu.ahau.mgc.hibernate.many2one.pojo.User"table="MANY2ONE_USER"schema="SCOTT">
09.<idname="id"type="java.lang.Long">
10.<columnname="ID"precision="22"scale="0"/>
11.<generatorclass="native"/>
12.</id>
13.<propertyname="username"type="java.lang.String">
14.<columnname="USERNAME"length="10"not-null="true"/>
15.</property>
16.<propertyname="password"type="java.lang.String">
17.<columnname="PASSWORD"length="10"not-null="true"/>
18.</property>
19.<many-to-onename="group"column="RELATEDGROUP"cascade="all"/>
20.</class>
21.</hibernate-mapping>


HibernateSessionFactory.java:
001.packagecn.edu.ahau.mgc.hibernate.many2one.factory;
003.importorg.hibernate.HibernateException;
004.importorg.hibernate.Session;
005.importorg.hibernate.cfg.Configuration;
008.* Configures and provides access to Hibernate sessions, tied to the
009.* current thread of execution.  Follows the Thread Local Session
010.* pattern, see {@link http://hibernate.org/42.html ;}.
012.publicclassHibernateSessionFactory {
014.
015.* Location of hibernate.cfg.xml file.
016.* Location should be on the classpath as Hibernate uses  
017.* #resourceAsStream style lookup for its configuration file. 
018.* The default classpath location of the hibernate config file is 
019.* in the default package. Use #setConfigFile() to update 
020.* the location of the configuration file for the current session.   
022.privatestaticString CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
023.privatestaticfinalThreadLocal<Session> threadLocal = newThreadLocal<Session>();
024.privatestaticConfiguration configuration = newConfiguration();
025.privatestaticorg.hibernate.SessionFactory sessionFactory;
026.privatestaticString configFile = CONFIG_FILE_LOCATION;
028.
029.
030.configuration.configure(configFile);
031.sessionFactory = configuration.buildSessionFactory();
032.} catch(Exception e) {
033.System.err
034..println("%%%% Error Creating SessionFactory %%%%");
035.e.printStackTrace();
038.privateHibernateSessionFactory() {
042.* Returns the ThreadLocal Session instance.  Lazy initialize
043.* the <code>SessionFactory</code> if needed.
045.*  @return Session
046.*  @throws HibernateException
048.publicstaticSession getSession() throwsHibernateException {
049.Session session = (Session) threadLocal.get();
051.if(session == null|| !session.isOpen()) {
052.if(sessionFactory == null) {
053.rebuildSessionFactory();
055.session = (sessionFactory != null) ? sessionFactory.openSession()
056.
057.threadLocal.set(session);
060.returnsession;
064.*  Rebuild hibernate session factory
067.publicstaticvoidrebuildSessionFactory() {
068.
069.configuration.configure(configFile);
070.sessionFactory = configuration.buildSessionFactory();
071.} catch(Exception e) {
072.System.err
073..println("%%%% Error Creating SessionFactory %%%%");
074.e.printStackTrace();
079.*  Close the single hibernate session instance.
081.*  @throws HibernateException
083.publicstaticvoidcloseSession() throwsHibernateException {
084.Session session = (Session) threadLocal.get();
085.threadLocal.set(null);
087.if(session != null) {
088.session.close();
093.*  return session factory
096.publicstaticorg.hibernate.SessionFactory getSessionFactory() {
097.returnsessionFactory;
101.*  return session factory
103.*    session factory will be rebuilded in the next call
105.publicstaticvoidsetConfigFile(String configFile) {
106.HibernateSessionFactory.configFile = configFile;
107.sessionFactory = null;
111.*  return hibernate configuration
114.publicstaticConfiguration getConfiguration() {
115.returnconfiguration;


ExportToDB.java:
01.packagecn.edu.ahau.mgc.hibernate.many2one.export;
03.importorg.hibernate.cfg.Configuration;
04.importorg.hibernate.tool.hbm2ddl.SchemaExport;
06.publicclassExportToDB {
08.publicstaticvoidmain(String[] args) {
09.Configuration cfg = newConfiguration().configure();
10.SchemaExport export = newSchemaExport(cfg);
11.export.create(true, true);


ExportDBAddCascade.java:
01.packagecn.edu.ahau.mgc.hibernate.many2one.export;
03.importorg.hibernate.Session;
04.importorg.hibernate.SessionFactory;
05.importorg.hibernate.cfg.Configuration;
07.importcn.edu.ahau.mgc.hibernate.many2one.factory.HibernateSessionFactory;
08.importcn.edu.ahau.mgc.hibernate.many2one.pojo.Group;
09.importcn.edu.ahau.mgc.hibernate.many2one.pojo.User;
11.publicclassExportDBAddCascade {
13.publicstaticvoidmain(String[] args) {
14.Session session = HibernateSessionFactory.getSession();
15.session.beginTransaction();
17.Group group = newGroup();
18.group.setName("J2EE Developer");
20.for(inti = 0; i < 10; i++) {
21.User user = newUser();
22.user.setUsername("Magci_"+ i);
23.user.setPassword("123");
24.user.setGroup(group);
25.session.save(user);
30.HibernateSessionFactory.closeSession();


原文地址:https://www.cnblogs.com/a1280055207/p/2869394.html