facebook

Hibernate – Using Multiple cfg.xml

  1. MyEclipse Archived
  2.  > 
  3. Database Tools (DB Explorer, Hibernate, etc.)
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #297796 Reply

    I’m new to MyEclipse (used Eclipse for a couple years) and Hibernate (since Monday) and this forum (first post). I’ve been looking around trying to figure out how to connect one set of Hibernate reverse engineered POJOs and DOAs to multiple copies of a single DB table that exist on different servers. I’ve found some information but still haven’t quite figure out my problem yet.

    I have to pull data from multiple DBs that all have the same table. I figured I could do this by creating two hibernate.cfg.xml files. For purposes of my test code, I have hibernate.cfg.xml and nike.hibernate.cfg.xml. It is throwing a couple exceptions at present.

    I have a work around, I can manually create a SessionFactory and a Session and then pull back an object, but I cannot seem to use the generated HibernateSessionFactory methods or the generated DAO objects.

    Can anybody give me some pointers? Details below.

    If I use the generated HibernateSessionFactory.setConfigFile(xmlPath) method I get the following error:

    
    %%%% Error Creating SessionFactory %%%%
    org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/agora_inc/hibernate/signup/submission/SnpSubmission.hbm.xml
        at org.hibernate.cfg.Configuration.addResource(Configuration.java:569)
        at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1587)
        at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
        at com.agora_inc.hibernate.signup.submission.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:69)
        at com.agora_inc.hibernate.signup.submission.HibernateSessionFactory.getSession(HibernateSessionFactory.java:53)
        at com.agora_inc.hibernate.signup.submission.BaseHibernateDAO.getSession(BaseHibernateDAO.java:13)
        at com.agora_inc.hibernate.signup.submission.SnpSubmissionDAO.findById(SnpSubmissionDAO.java:77)
        at com.agora_inc.hibernate.signup.submission.HibernateExample.listLocalSubmission(HibernateExample.java:61)
        at com.agora_inc.hibernate.signup.submission.HibernateExample.main(HibernateExample.java:33)
    Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.agora_inc.hibernate.signup.submission.SnpSubmission
        at org.hibernate.cfg.Mappings.addClass(Mappings.java:118)
        at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:145)
        at org.hibernate.cfg.Configuration.add(Configuration.java:669)
        at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:504)
        at org.hibernate.cfg.Configuration.addResource(Configuration.java:566)
        ... 11 more
    
    package com.agora_inc.hibernate.signup.submission;
    
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;
    
    /**
     * Configures and provides access to Hibernate sessions, tied to the
     * current thread of execution.  Follows the Thread Local Session
     * pattern, see {@link http://hibernate.org/42.html }.
     */
    public class HibernateSessionFactory {
    
        /** 
         * Location of hibernate.cfg.xml 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 = "/hibernate.cfg.xml";
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private  static Configuration configuration = new Configuration();    
        private static org.hibernate.SessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION;
    
        static {
            try {
                configuration.configure(configFile);
                sessionFactory = configuration.buildSessionFactory();
            } catch (Exception e) {
                System.err
                        .println("%%%% Error Creating SessionFactory %%%%");
                e.printStackTrace();
            }
        }
        private HibernateSessionFactory() {
        }
        
        /**
         * Returns the ThreadLocal Session instance.  Lazy initialize
         * the <code>SessionFactory</code> if needed.
         *
         *  @return Session
         *  @throws HibernateException
         */
        public static Session getSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
    
            if (session == null || !session.isOpen()) {
                if (sessionFactory == null) {
                    rebuildSessionFactory();
                }
                session = (sessionFactory != null) ? sessionFactory.openSession()
                        : null;
                threadLocal.set(session);
            }
    
            return session;
        }
    
        /**
         *  Rebuild hibernate session factory
         *
         */
        public static void rebuildSessionFactory() {
            try {
                configuration.configure(configFile);
                sessionFactory = configuration.buildSessionFactory();
            } catch (Exception e) {
                System.err
                        .println("%%%% Error Creating SessionFactory %%%%");
                e.printStackTrace();
            }
        }
    
        /**
         *  Close the single hibernate session instance.
         *
         *  @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
            threadLocal.set(null);
    
            if (session != null) {
                session.close();
            }
        }
    
        /**
         *  return session factory
         *
         */
        public static org.hibernate.SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    
        /**
         *  return session factory
         *
         *    session factory will be rebuilded in the next call
         */
        public static void setConfigFile(String configFile) {
            HibernateSessionFactory.configFile = configFile;
            sessionFactory = null;
        }
    
        /**
         *  return hibernate configuration
         *
         */
        public static Configuration getConfiguration() {
            return configuration;
        }
    
    }
    package com.agora_inc.hibernate.signup.submission;
    
    import java.util.List;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.hibernate.LockMode;
    import org.hibernate.Query;
    import org.hibernate.criterion.Example;
    
    /**
     * A data access object (DAO) providing persistence and search support for
     * SnpSubmission entities. Transaction control of the save(), update() and
     * delete() operations can directly support Spring container-managed
     * transactions or they can be augmented to handle user-managed Spring
     * transactions. Each of these methods provides additional information for how
     * to configure it for the desired type of transaction control.
     * 
     * @see com.agora_inc.hibernate.signup.submission.SnpSubmission
     * @author MyEclipse Persistence Tools
     */
    
    public class SnpSubmissionDAO extends BaseHibernateDAO {
        private static final Log log = LogFactory.getLog(SnpSubmissionDAO.class);
        // property constants
        public static final String CUSTOMER_IP = "customerIp";
        public static final String TIMESTAMP = "timestamp";
        public static final String LIST_CODE = "listCode";
        public static final String SOURCE_ID = "sourceId";
        public static final String FIRST_NAME = "firstName";
        public static final String LAST_NAME = "lastName";
        public static final String ADDRESS1 = "address1";
        public static final String ADDRESS2 = "address2";
        public static final String CITY = "city";
        public static final String STATE_PROVINCE_CODE = "stateProvinceCode";
        public static final String POSTAL_CODE = "postalCode";
        public static final String COUNTRY = "country";
        public static final String PHONE_NUMBER = "phoneNumber";
        public static final String PHONE_NUMBER2 = "phoneNumber2";
        public static final String PHONE_NUMBER3 = "phoneNumber3";
        public static final String EMAIL_ADDRESS = "emailAddress";
        public static final String HTTP_REFERER = "httpReferer";
        public static final String USER1 = "user1";
        public static final String USER2 = "user2";
        public static final String USER3 = "user3";
        public static final String EMAIL_FROM = "emailFrom";
        public static final String EMAIL_SUBJECT = "emailSubject";
        public static final String EMAIL_PAGE = "emailPage";
        public static final String TITLE = "title";
        public static final String REMOVE_CODE = "removeCode";
        public static final String AFFILIATE_ID = "affiliateId";
    
        public void save(SnpSubmission transientInstance) {
            log.debug("saving SnpSubmission instance");
            try {
                getSession().save(transientInstance);
                log.debug("save successful");
            } catch (RuntimeException re) {
                log.error("save failed", re);
                throw re;
            }
        }
    
        public void delete(SnpSubmission persistentInstance) {
            log.debug("deleting SnpSubmission instance");
            try {
                getSession().delete(persistentInstance);
                log.debug("delete successful");
            } catch (RuntimeException re) {
                log.error("delete failed", re);
                throw re;
            }
        }
    
        public SnpSubmission findById(java.lang.Integer id) {
            log.debug("getting SnpSubmission instance with id: " + id);
            try {
                SnpSubmission instance = (SnpSubmission) getSession().get(
                        "com.agora_inc.hibernate.signup.submission.SnpSubmission",
                        id);
                return instance;
            } catch (RuntimeException re) {
                log.error("get failed", re);
                throw re;
            }
        }
    
        public List findByExample(SnpSubmission instance) {
            log.debug("finding SnpSubmission instance by example");
            try {
                List results = getSession().createCriteria(
                        "com.agora_inc.hibernate.signup.submission.SnpSubmission")
                        .add(Example.create(instance)).list();
                log.debug("find by example successful, result size: "
                        + results.size());
                return results;
            } catch (RuntimeException re) {
                log.error("find by example failed", re);
                throw re;
            }
        }
    
        public List findByProperty(String propertyName, Object value) {
            log.debug("finding SnpSubmission instance with property: "
                    + propertyName + ", value: " + value);
            try {
                String queryString = "from SnpSubmission as model where model."
                        + propertyName + "= ?";
                Query queryObject = getSession().createQuery(queryString);
                queryObject.setParameter(0, value);
                return queryObject.list();
            } catch (RuntimeException re) {
                log.error("find by property name failed", re);
                throw re;
            }
        }
    
        public List findByCustomerIp(Object customerIp) {
            return findByProperty(CUSTOMER_IP, customerIp);
        }
    
        public List findByTimestamp(Object timestamp) {
            return findByProperty(TIMESTAMP, timestamp);
        }
    
        public List findByListCode(Object listCode) {
            return findByProperty(LIST_CODE, listCode);
        }
    
        public List findBySourceId(Object sourceId) {
            return findByProperty(SOURCE_ID, sourceId);
        }
    
        public List findByFirstName(Object firstName) {
            return findByProperty(FIRST_NAME, firstName);
        }
    
        public List findByLastName(Object lastName) {
            return findByProperty(LAST_NAME, lastName);
        }
    
        public List findByAddress1(Object address1) {
            return findByProperty(ADDRESS1, address1);
        }
    
        public List findByAddress2(Object address2) {
            return findByProperty(ADDRESS2, address2);
        }
    
        public List findByCity(Object city) {
            return findByProperty(CITY, city);
        }
    
        public List findByStateProvinceCode(Object stateProvinceCode) {
            return findByProperty(STATE_PROVINCE_CODE, stateProvinceCode);
        }
    
        public List findByPostalCode(Object postalCode) {
            return findByProperty(POSTAL_CODE, postalCode);
        }
    
        public List findByCountry(Object country) {
            return findByProperty(COUNTRY, country);
        }
    
        public List findByPhoneNumber(Object phoneNumber) {
            return findByProperty(PHONE_NUMBER, phoneNumber);
        }
    
        public List findByPhoneNumber2(Object phoneNumber2) {
            return findByProperty(PHONE_NUMBER2, phoneNumber2);
        }
    
        public List findByPhoneNumber3(Object phoneNumber3) {
            return findByProperty(PHONE_NUMBER3, phoneNumber3);
        }
    
        public List findByEmailAddress(Object emailAddress) {
            return findByProperty(EMAIL_ADDRESS, emailAddress);
        }
    
        public List findByHttpReferer(Object httpReferer) {
            return findByProperty(HTTP_REFERER, httpReferer);
        }
    
        public List findByUser1(Object user1) {
            return findByProperty(USER1, user1);
        }
    
        public List findByUser2(Object user2) {
            return findByProperty(USER2, user2);
        }
    
        public List findByUser3(Object user3) {
            return findByProperty(USER3, user3);
        }
    
        public List findByEmailFrom(Object emailFrom) {
            return findByProperty(EMAIL_FROM, emailFrom);
        }
    
        public List findByEmailSubject(Object emailSubject) {
            return findByProperty(EMAIL_SUBJECT, emailSubject);
        }
    
        public List findByEmailPage(Object emailPage) {
            return findByProperty(EMAIL_PAGE, emailPage);
        }
    
        public List findByTitle(Object title) {
            return findByProperty(TITLE, title);
        }
    
        public List findByRemoveCode(Object removeCode) {
            return findByProperty(REMOVE_CODE, removeCode);
        }
    
        public List findByAffiliateId(Object affiliateId) {
            return findByProperty(AFFILIATE_ID, affiliateId);
        }
    
        public List findAll() {
            log.debug("finding all SnpSubmission instances");
            try {
                String queryString = "from SnpSubmission";
                Query queryObject = getSession().createQuery(queryString);
                return queryObject.list();
            } catch (RuntimeException re) {
                log.error("find all failed", re);
                throw re;
            }
        }
    
        public SnpSubmission merge(SnpSubmission detachedInstance) {
            log.debug("merging SnpSubmission instance");
            try {
                SnpSubmission result = (SnpSubmission) getSession().merge(
                        detachedInstance);
                log.debug("merge successful");
                return result;
            } catch (RuntimeException re) {
                log.error("merge failed", re);
                throw re;
            }
        }
    
        public void attachDirty(SnpSubmission instance) {
            log.debug("attaching dirty SnpSubmission instance");
            try {
                getSession().saveOrUpdate(instance);
                log.debug("attach successful");
            } catch (RuntimeException re) {
                log.error("attach failed", re);
                throw re;
            }
        }
    
        public void attachClean(SnpSubmission instance) {
            log.debug("attaching clean SnpSubmission instance");
            try {
                getSession().lock(instance, LockMode.NONE);
                log.debug("attach successful");
            } catch (RuntimeException re) {
                log.error("attach failed", re);
                throw re;
            }
        }
    }
    #297932 Reply

    Brian Fernandes
    Moderator

    I apologize for the delayed response, I hope this helps.

    I’ve been looking around trying to figure out how to connect one set of Hibernate reverse engineered POJOs and DOAs to multiple copies of a single DB table that exist on different servers. I’ve found some information but still haven’t quite figure out my problem yet.

    Do you need to do this for testing or do you actually have entities distributed across different servers which you will need simultaneously at runtime?

    For simultaneous access, you can have a look at Hibernate shards: http://shards.hibernate.org/

    If you need to access only one server at a time, you may need to delete / rename the unrelated .cfg.xml file before launching the application, you probably know that already.

    Please let me know if we can help further.

    #297937 Reply

    @Support-Brian wrote:

    If you need to access only one server at a time, you may need to delete / rename the unrelated .cfg.xml file before launching the application, you probably know that already.

    Please let me know if we can help further.

    This. Simultaneous is not a big issue. We just need to round robin between a few different servers.

    I’m working on a number of issues at once and have kinda put this aside for the time. This is my first Hibernate project so I don’t know much yet.

    So what you’re saying is that I need to rename the default hibernate.cfg.xml? Will that allow me to then use the setConfigFile(String) method on the HibernateSessionFactory that is reverse-engineered from one of the tables to then return a factory for each of the different DB servers?

    #297944 Reply

    Brian Fernandes
    Moderator

    So what you’re saying is that I need to rename the default hibernate.cfg.xml? Will that allow me to then use the setConfigFile(String) method on the HibernateSessionFactory that is reverse-engineered from one of the tables to then return a factory for each of the different DB servers?

    Correct, Hibernate tends to search for all configuration files in the classpath and load them as well, so while not referenced in your session factory, it is probably still being fed into the Hibernate model. Just to be sure, I would suggest temporarily deleting the default hibernate.cfg.xml file for your first test – since I cannot recall the logic used by Hibernate to locate configuration files atm and I’m not sure what parts of the filename you would need to change to ensure the file is ignored.

    #297946 Reply

    Sweet thanks. I’ll give that a go.

    #298036 Reply

    I’m posting this for my own personal documentation as well as for other folks just getting started with Hibernate.

    @Support-Brian wrote:

    For simultaneous access, you can have a look at Hibernate shards: http://shards.hibernate.org/

    Whoa. Looks likes Shards is definitely the answer for me. I do need to support multiple databases with different configurations (number of rows, row names, table names, etc.).

    Shards is going to be perfect for me. Thanks for the suggestion.

Viewing 6 posts - 1 through 6 (of 6 total)
Reply To: Hibernate – Using Multiple cfg.xml

You must be logged in to post in the forum log in