Hibernate dynamic multi-database, hibernate Database

Source: Internet
Author: User

Hibernate dynamic multi-database, hibernate Database
Recently, the teacher gave me a task. The requirement is as follows:
Server A has A table containing several server information. The table fields include:

    private int id;    private String serverName;    private String host;    private String userName;    private String passWord;
We need to read the server information on database A to obtain data from the corresponding database.

First, let's analyze this problem. multi-database is not difficult for hibernate. There are many online materials, such:
Hibernate accesses multiple databases
However, most examples on the Internet are the same as those in the previous blog. They know the information of several databases, each database, and then manually generate xml.

However, we need to know exactly a few databases when the program is running.
The process of generating xml in advance cannot be achieved.

At this time, I want to be able to automatically generate xml in dom4j every time I add, delete, and modify the table in server?
The final conclusion is too complicated. Discard.

Does hibernate only start with xml?
Of course not. You can also start with hibernate. properties.
Both properties and xml are files. If you say this, you have not said it.

No, do you forget the java. util. Properties class?
Refer to Hibernate for more information: Do not use hibernate. cfg. xml


I'm not happy with one of the above items.
// Create a ing (only the Class object needs to be specified and the ing file is automatically searched)
If hibernate and spring are used together
    <bean id="sessionFactory"        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">        <property name="dataSource">            <ref bean="dataSource" />        </property>        <property name="packagesToScan">            <list>                <value>com.core.model</value>            </list>        </property>    </bean>
You can also scan the packagesToScan attribute.
Now we can only add addClass one by one.

Okay. Now let's look at the code.
In hibernate, We will abstract the UtilDAO class.
package com.core.dao;@Componentpublic class UtilDAO extends HibernateDaoSupport {    protected void initDao() {        // do nothing    }    public void save(Object transientInstance) {        try {            getHibernateTemplate().save(transientInstance);            // log.debug("save successful");        } catch (RuntimeException re) {            // log.error("save failed", re);            throw re;        }    }        public void update(Object transientInstance) {        try {            getHibernateTemplate().update(transientInstance);            // log.debug("save successful");        } catch (RuntimeException re) {            // log.error("save failed", re);            throw re;        }    }    public List<?> findAllList(String entity){        try {            String queryString = null;            queryString = "from "+entity;            return getHibernateTemplate().find(queryString);        } catch (RuntimeException re) {            // log.error("find by property name failed", re);            throw re;        }    }        public void delete(Object transientInstance){        try {            getHibernateTemplate().delete(transientInstance);            // log.debug("save successful");        } catch (RuntimeException re) {            // log.error("save failed", re);            throw re;        }    }       @Resource    public void setSessionFactory0(SessionFactory sessionFactory){          super.setSessionFactory(sessionFactory);      }}
Let's take a look at the last method setSessionFactory0 and inject the sessionFactory generated by the Properties class.

The method for implementing multi-database query is as follows:
@ SuppressWarnings ("unchecked") public String getTreeFromRemote () {UtilDAO _ utilDAO = new UtilDAO (); JSONArray ja = new JSONArray (); list <Server> servers = (List <Server>) utilDAO. findAllList ("Server"); // Server is the Server for (Server server: servers) {_ utilDAO = Hibernate3WithoutConfig. getUtilDAO (server); ja. add (getAPPTree (_ utilDAO, server. getServerName ();} System. out. println ("_________"); System. out. println (ja); return SUCCESS ;}
In the database, we have a Server table.

As follows:


As for the getAPPTree, I will not show it to you. I already have utildao, and this utildao is the dao of the database corresponding to server. getServerName (). What else do I need to talk about?
By the way, there is another one:
Hibernate3WithoutConfig. javapublic static UtilDAO getUtilDAO (Server s) {Properties p = new Properties (); p. put ("hibernate. connection. driver_class "," com. mysql. jdbc. driver "); p. put ("hibernate. connection. url "," jdbc: mysql: // "+ s. getHost () + "/WG? UseUnicode = true & characterEncoding = UTF-8 "); p. put ("hibernate. connection. username ", s. getUserName (); p. put ("hibernate. connection. password ", s. getPassWord (); p. put ("hibernate. dialect "," org. hibernate. dialect. mySQLInnoDBDialect "); p. put ("hibernate. hbm2ddl. auto "," update "); p. put ("hibernate. current_session_context_class "," thread "); p. put ("hibernate. show_ SQL "," true "); Configuration conf = new AnnotationConfiguration (). setProperties (p); conf. addClass (User. class); // these classes are the class conf that I need. addClass (Collection. class); conf. addClass (Groups. class); conf. addClass (Item. class); SessionFactory sf = conf. buildSessionFactory (); UtilDAO utilDAO = new UtilDAO (); utilDAO. setSessionFactory0 (sf); return utilDAO ;}


When doing this, you must connect to another server from the local machine, and enable the mysql remote access permission is indispensable.
There are also a lot of online materials
ERROR 2003: Can't connect to MySQL server on 10.150.0.83 (10038)
The above problem gave me a headache for a long time. Finally, my brother said, Have you shut down the remote server firewall?
Then the problem is solved.



References

Http://developer.51cto.com/art/200907/133239.htm

Http://blog.csdn.net/xiazdong/article/details/7562765

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.