熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Hibernate中配置復合主鍵映射

2022-06-13   來源: Java開源技術 

  通常將復合主鍵單獨建一個類

    復合主鍵類必須實現javaioSerializable接口必須重寫hashCode和equals方法

    在映射文件中配置復合主鍵

  hibernatecfgxml:

  scott

  jdbc:oracle:thin:@::MGC

  orghibernatedialectOracleDialect

  MGC

  tiger

  oraclejdbcdriverOracleDriver

  true

    YearPeriodPKjava:

  package cneduahaumgchibernatepojo;

  import javaioSerializable;

  public class YearPeriodPK implements Serializable{

  private int year;
        private int period;

  public int getYear() {
            return year;
        }

  public void setYear(int year) {
            thisyear = year;
        }

  public int getPeriod() {
            return period;
        }

  public void setPeriod(int period) {
            thisperiod = period;
        }

  @Override
        public int hashCode() {
            final int prime = ;
            int result = ;
            result = prime * result + period;
            result = prime * result + year;
            return result;
        }

  @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != objgetClass())
                return false;
            final YearPeriodPK other = (YearPeriodPK) obj;
            if (period != otherperiod)
                return false;
            if (year != otheryear)
                return false;
            return true;
        }
    }

  YearPeriodjava:

  package cneduahaumgchibernatepojo;

  import javautilCalendar;

  public class YearPeriod {

  private YearPeriodPK yearPeriodPK;
        private Calendar beginDate;
        private Calendar endDate;

  public YearPeriodPK getYearPeriodPK() {
            return yearPeriodPK;
        }

  public void setYearPeriodPK(YearPeriodPK yearPeriodPK) {
            thisyearPeriodPK = yearPeriodPK;
        }

  public Calendar getBeginDate() {
            return beginDate;
        }

  public void setBeginDate(Calendar beginDate) {
            thisbeginDate = beginDate;
        }

  public Calendar getEndDate() {
            return endDate;
        }

  public void setEndDate(Calendar endDate) {
            thisendDate = endDate;
        }

  }

  YearPeriodhbmxml:

  HibernateSessionFactoryjava:

  package cneduahaumgchibernatemanyonefactory;

  import orghibernateHibernateException;
    import orghibernateSession;
    import orghibernatecfgConfiguration;

  /**
     * Configures and provides access to Hibernate sessions tied to the
     * current thread of execution  Follows the Thread Local Session
     * pattern see {@link ;}
     */
    public class HibernateSessionFactory {

  /**
         * Location of hibernatecfgxml file
         * Location should be on the classpath as Hibernate uses
         * #resourceAsStream style lookup for its configuration file
         * The default classpath location of the hibernate config file is
         * in the default package Use #setConfigFile() to update
         * the location of the configuration file for the current session
         */
        private static String CONFIG_FILE_LOCATION = /hibernatecfgxml;
        private static final ThreadLocal threadLocal = new ThreadLocal();
        private  static Configuration configuration = new Configuration();
        private static orghibernateSessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION;

  static {
            try {
                nfigure(configFile);
                sessionFactory = configurationbuildSessionFactory();
            } catch (Exception e) {
                Systemerr
                        println(%%%% Error Creating SessionFactory %%%%);
                eprintStackTrace();
           }
        }
        private HibernateSessionFactory() {
        }

  /**
         * Returns the ThreadLocal Session instance  Lazy initialize
         * the SessionFactory if needed
         *
         *  @return Session
         *  @throws HibernateException
         */
        public static Session getSession() throws HibernateException {
            Session session = (Session) threadLocalget();

  if (session == null || !sessionisOpen()) {
                if (sessionFactory == null) {
                    rebuildSessionFactory();
                }
               session = (sessionFactory != null) ? sessionFactoryopenSession()
                        : null;
                threadLocalset(session);
            }

  return session;
        }

  /**
         *  Rebuild hibernate session factory
         *
         */
        public static void rebuildSessionFactory() {
            try {
                nfigure(configFile);
               sessionFactory = configurationbuildSessionFactory();
            } catch (Exception e) {
                Systemerr
                        println(%%%% Error Creating SessionFactory %%%%);
                eprintStackTrace();
            }
        }

  /**
         *  Close the single hibernate session instance
         *
         *  @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocalget();
            threadLocalset(null);

  if (session != null) {
                sessionclose();
            }
        }

  /**
         *  return session factory
         *
         */
        public static orghibernateSessionFactory getSessionFactory() {
            return sessionFactory;
        }

  /**
         *  return session factory
         *
         *    session factory will be rebuilded in the next call
         */
        public static void setConfigFile(String configFile) {
            HibernanfigFile = configFile;
            sessionFactory = null;
        }

  /**
         *  return hibernate configuration
        *
         */
        public static Configuration getConfiguration() {
            return configuration;
        }

  }

  ExportToDBCreatejava:

  package cneduahaumgchibernateexport;

  import orghibernatecfgConfiguration;
    import orghibernatetoolhbmddlSchemaExport;

  public class ExportToDBCreate {

  public static void main(String[] args) {
            Configuration cfg = new Configuration(nfigure();
            SchemaExport export = new SchemaExport(cfg);
           exportcreate(true true);
        }

  }

  InitDatajava:

  package cneduahaumgchibernateexport;

  import javautilCalendar;

  import orghibernateSession;

  import cneduahaumgchibernatefactoryHibernateSessionFactory;
    import cneduahaumgchibernatepojoYearPeriod;
    import cneduahaumgchibernatepojoYearPeriodPK;

  public class InitData {

  public static void main(String[] args) {
           Session session = null;
            try {
                session = HibernateSessionFactorygetSession();
               sessionbeginTransaction();

  YearPeriodPK yearPeriodPK = new YearPeriodPK();
               yearPeriodPKsetYear();
                yearPeriodPKsetPeriod();

  YearPeriod yearPeriod = new YearPeriod();
                yearPeriodsetYearPeriodPK(yearPeriodPK);
                Calendar beginDate = CalendargetInstance();
                beginDateset( );
                Calendar endDate = CalendargetInstance();
                endDateset( );
                yearPeriodsetBeginDate(beginDate);
                yearPeriodsetEndDate(endDate);

  sessionsave(yearPeriod);
                sessiongetTransaction(mit();
            } catch (Exception e) {
               sessiongetTransaction()rollback();
                eprintStackTrace();
           } finally {
                HibernateSessionFactorycloseSession();
            }
        }

  }

  LoadDatajava:

  package cneduahaumgchibernateexport;

  import javatextSimpleDateFormat;

  import orghibernateSession;

  import cneduahaumgchibernatefactoryHibernateSessionFactory;
    import cneduahaumgchibernatepojoYearPeriod;
    import cneduahaumgchibernatepojoYearPeriodPK;

  public class LoadData {

  public static void main(String[] args) {
            Session session = null;
            try {
                session = HibernateSessionFactorygetSession();
                YearPeriodPK yearPeriodPK = new YearPeriodPK();
                yearPeriodPKsetYear();
                yearPeriodPKsetPeriod();

  YearPeriod yearPeriod = (YearPeriod) sessionload(YearPeriodclass yearPeriodPK);
                SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMdd);
                Systemoutprintln(Begin Date: + sdfformat(yearPeriodgetBeginDate()getTime()));
                Systemoutprintln(End Date: + sdfformat(yearPeriodgetEndDate()getTime()));

  } catch (Exception e) {
                eprintStackTrace();
            } finally {
                HibernateSessionFactorycloseSession();
            }
        }
    }


From:http://tw.wingwit.com/Article/program/Java/ky/201311/27962.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.