Hibernate dynamic database evolution Edition

Source: Internet
Author: User

Gossip:

Import org. hibernate. hibernateException; import org. hibernate. cfg. configuration;/*** Hibernate Configuration * @ author chendaojun **/public class DynamicHibernateConfiguration extends Configuration {public DynamicHibernateConfiguration () {super ();} public void reset () {super. reset ();} public DynamicHibernateConfiguration (String dialect, String driverClass, String ipAddress, String port, String dataBaseName, String username, String password) throws HibernateException {String connection_url = ""; if (dialect. indexOf ("MySQL")>-1) {connection_url = "jdbc: mysql: //" + ipAddress + "/" + dataBaseName;} else if (dialect. indexOf ("SQLServer")>-1) {connection_url = "jdbc: sqlserver: //" + ipAddress + ":" + port + "; DataBaseName =" + dataBaseName ;} else if (dialect. indexOf ("Oracle")>-1) {connection_url = "jdbc: oracle: thin: @" + ipAddress + ":" + port + ":" + dataBaseName ;} else {throw new HibernateException ("The dialect was not allowed. = fd = "+ dialect);} super. setProperty ("hibernate. connection. provider_class "," com. jolbox. bonecp. provider. boneCPConnectionProvider "); super. setProperty ("hibernate. dialect ", dialect); super. setProperty ("hibernate. connection. url ", connection_url); super. setProperty ("hibernate. connection. driver_class ", driverClass); super. setProperty ("hibernate. connection. username ", username); super. setProperty ("hibernate. connection. password ", password); super. setProperty ("bonecp. idleMaxAge "," 60 "); super. setProperty ("bonecp. idleConnectionTestPeriod "," 5 "); super. setProperty ("bonecp. maxConnectionsPerPartition "," 60 "); super. setProperty ("bonecp. minConnectionsPerPartition "," 20 "); super. setProperty ("bonecp. partitionCount "," 3 "); super. setProperty ("bonecp. acquireIncrement "," 10 "); super. setProperty ("bonecp. statementsCacheSize "," 50 "); super. setProperty ("bonecp. preparedStatementCacheSize "," 50 "); super. setProperty ("bonecp. releaseHelperThreads "," 3 "); super. setProperty ("bonecp. connectionTestStatement "," select 1 from dual "); // super. setProperty ("hibernate. show_ SQL "," true ");} public DynamicHibernateConfiguration (String dialect, String driverClass, String ipAddress, String port, String dataBaseName, String username, String password, String schema, String catalog) throws HibernateException {String connection_url = ""; if (dialect. indexOf ("MySQL")>-1) {connection_url = "jdbc: mysql: //" + ipAddress + "/" + dataBaseName;} else if (dialect. indexOf ("SQLServer")>-1) {connection_url = "jdbc: sqlserver: //" + ipAddress + ":" + port + "; DataBaseName =" + dataBaseName ;} else if (dialect. indexOf ("Oracle")>-1) {connection_url = "jdbc: oracle: thin: @" + ipAddress + ":" + port + ":" + dataBaseName ;} else {throw new HibernateException ("The dialect was not allowed. = fd = "+ dialect);} super. setProperty ("hibernate. connection. provider_class "," com. jolbox. bonecp. provider. boneCPConnectionProvider "); super. setProperty ("hibernate. dialect ", dialect); super. setProperty ("hibernate. connection. url ", connection_url); super. setProperty ("hibernate. connection. driver_class ", driverClass); super. setProperty ("hibernate. connection. username ", username); super. setProperty ("hibernate. connection. password ", password); super. setProperty ("hibernate. default_schema ", schema); // super. setProperty ("hibernate. default_catalog ", catalog); // super. setProperty ("hibernate. show_ SQL "," true "); super. setProperty ("bonecp. idleMaxAge "," 60 "); super. setProperty ("bonecp. idleConnectionTestPeriod "," 5 "); super. setProperty ("bonecp. maxConnectionsPerPartition "," 60 "); super. setProperty ("bonecp. minConnectionsPerPartition "," 20 "); super. setProperty ("bonecp. partitionCount "," 3 "); super. setProperty ("bonecp. acquireIncrement "," 10 "); super. setProperty ("bonecp. statementsCacheSize "," 50 "); super. setProperty ("bonecp. preparedStatementCacheSize "," 50 "); super. setProperty ("bonecp. releaseHelperThreads "," 3 "); super. setProperty ("bonecp. connectionTestStatement "," select 1 from dual ");}}
Import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import org. hibernate. hibernateException; import org. hibernate. session; import org. hibernate. sessionFactory;/*** dynamic session factory class * @ author **/public class DynamicSessionFactory {// private static String CONFIG_FILE_LOCATION = "/hibernate. cfg. xml "; private static final ThreadLocal <Session> threadLocal = new ThreadLocal <Session> (); private static DynamicHibernateConfiguration configuration = new DynamicHibernateConfiguration (); private static org. hibernate. sessionFactory sessionFactory; private static List <DynamicHibernateConfiguration> configurationList = new ArrayList <DynamicHibernateConfiguration> (); private static Map <String, SessionFactory> sessinFactoryMap = new HashMap <String, SessionFactory> (); // Private static String configFile = CONFIG_FILE_LOCATION;/* static {try {configuration. configure (configFile); sessionFactory = configuration. buildSessionFactory ();} catch (Exception e) {System. err. println ("% temporary session creation factory error %"); e. printStackTrace () ;}} */private DynamicSessionFactory () {}/ *** 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 ("% rebuilding temporary session factory error %"); e. printStackTrace () ;}} public static void reflashSessionF Acloud (DynamicHibernateConfiguration tempConfiguration) {try {// configuration. configure (configFile); // the flag with the same hibernate configuration boolean flag = false; for (DynamicHibernateConfiguration config: configurationList) {if (tempConfiguration. getProperty ("hibernate. dialect "). equals (config. getProperty ("hibernate. dialect ") & tempConfiguration. getProperty ("hibernate. connection. url "). equalsIgnoreCase (config. GetProperty ("hibernate. connection. url ") & tempConfiguration. getProperty ("hibernate. connection. username "). equals (config. getProperty ("hibernate. connection. username ") & tempConfiguration. getProperty ("hibernate. connection. password "). equals (config. getProperty ("hibernate. connection. password ") {configuration = config; sessionFactory = sessinFactoryMap. get (configuration. getProperty ("hibernate. conne Ction. url ") + configuration. getProperty (" hibernate. connection. username "); flag = true; break ;}} if (! Flag) {closeSession (); closeSessionFactory (); configuration. reset (); configuration = tempConfiguration; configurationList. add (configuration); sessionFactory = configuration. buildSessionFactory (); sessinFactoryMap. put (configuration. getProperty ("hibernate. connection. url ") + configuration. getProperty ("hibernate. connection. username "), sessionFactory); // System. out. println ("% session factory start again here %");} ca Tch (Exception e) {System. err. println ("% session factory re-start error %"); e. printStackTrace () ;}} public static void closeSessionFactory () throws HibernateException {try {if (sessionFactory! = Null) {sessionFactory. close () ;}} catch (Exception e) {System. err. println ("% session factory close error %"); 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) {TempSessionFactory. configFile = configFile; sessionFactory = null;} * // *** return hibernate configuration **/public static DynamicHibernateConfiguration getConfiguration () {return configuration ;}}

Import java. util. list; import java. util. map; import java. util. set; import org. hibernate. query; import org. hibernate. session; import org. hibernate. transform. transformers;/*** database operation ** @ author **/public class DynamicHibernateDAO {public Session session Session = null; private Query query = null ;; /*** @ param Dialect * // database Dialect * @ param dbDriver * // data driver * @ param dbUrl * // database address * @ param DbPort * // database port * @ Param DbName * // database name * @ param DbUserName * // database username * @ param DbUserPassword * // Database Password * @ return */public DynamicHibernateConfiguration setHibernateConfig (String dialect, string driverClass, String ipAddress, String port, String dataBaseName, String username, String password, String schema, String catalog) {DynamicHibernateConfiguration configuration = null; if (schema! = Null & schema! = "") {Configuration = new DynamicHibernateConfiguration (dialect, driverClass, ipAddress, port, dataBaseName, username, password, schema, catalog);} else {configuration = new DynamicHibernateConfiguration (dialect, driverClass, ipAddress, port, dataBaseName, username, password);} return configuration;}/*** get session ** @ return */public void reflashDbConnection (DynamicHibernateConfiguration encryption atio N, String dialect, String driverClass, String ipAddress, String port, String dataBaseName, String username, String password, String tableName) {session = DynamicSessionFactory. getSession ();} public Session getSession () {return session;}/*** get sqlSession ** @ return */public Session getTempSession () {return DynamicSessionFactory. getSession ();}/*** execute this method before performing Database Operations ** @ param dialect * @ param driverClas S * @ param ipAddress * @ param port * @ param dataBaseName * @ param username * @ param password * @ param schema * @ param catalog * @ param tableName */public void dynamicSqlOperateBefore (String dialect, string driverClass, String ipAddress, String port, String dataBaseName, String username, String password, String schema, String catalog, String tableName) {DynamicHibernateConfiguration configuration = se THibernateConfig (dialect, driverClass, ipAddress, port, dataBaseName, username, password, schema, catalog); DynamicSessionFactory. reflashSessionFactory (configuration); session = DynamicSessionFactory. getSession ();} /*** get object ** @ param dialect * @ param driverClass * @ param ipAddress * @ param port * @ param dataBaseName * @ param username * @ param password * @ param schema *@ param catalog * @ param tableNa Me * @ param idColumn * @ param id * @ return */public Object get (String dialect, String driverClass, String ipAddress, String port, String dataBaseName, String username, String password, string schema, String catalog, String tableName, String idColumn, Long id) {dynamicSqlOperateBefore (dialect, driverClass, ipAddress, port, dataBaseName, username, password, schema, catalog, tableName ); stringBuilder SQL = New StringBuilder (); SQL. append ("select * from" + tableName + "where" + idColumn + "=" + id); query = session. createSQLQuery (SQL. toString ()). setResultTransformer (Transformers. ALIAS_TO_ENTITY_MAP); Object object = query. uniqueResult (); // session. close (); return object ;} /*** get Object List ** @ param dialect * @ param driverClass * @ param ipAddress * @ param port * @ param dataBaseName * @ param username * @ para M password * @ param schema * @ param catalog * @ param tableName * @ param sortColumn * @ param params * @ param iDisplayStart * @ param iDisplayLength * @ return */public List <Map <string, object> getObjectList (String dialect, String driverClass, String ipAddress, String port, String dataBaseName, String username, String password, String schema, String catalog, String tableName, String sortColumn, map <Stri Ng, String> params, Integer iDisplayStart, Integer iDisplayLength) {dynamicSqlOperateBefore (dialect, driverClass, ipAddress, port, dataBaseName, username, password, schema, catalog, tableName ); if (iDisplayStart = null) {iDisplayStart = 1; if (iDisplayLength = null) {iDisplayLength = 10 ;}} StringBuilder SQL = new StringBuilder (); String dbType = DynamicSessionFactory. getConfiguration (). getProperty ("hi Bernate. connection. driver_class "); if (dbType. contains ("oracle") {// oracle paging SQL. append ("select * from (select. *, rownum rn from (");} else if (dbType. contains ("mysql") {} SQL. append ("select * from" + tableName + "where 1 = 1"); if (params! = Null) {if (! Params. isEmpty () {Set <String> keys = params. keySet (); for (String paramKey: keys) {String paramVal = params. get (paramKey); SQL. append ("and" + paramKey + "= '" + paramVal + "'") ;}} if (sortColumn! = Null & sortColumn! = "") {SQL. append ("order by" + sortColumn + "desc");} if (dbType. contains ("oracle") {SQL. append (") A where rownum <=" + iDisplayLength + ") where rn> =" + iDisplayStart);} else if (dbType. contains ("mysql") {// mysql paging SQL. append ("limit" + iDisplayStart + "," + iDisplayLength);} query = session. createSQLQuery (SQL. toString ()). setResultTransformer (Transformers. ALIAS_TO_ENTITY_MAP); List <Map <String, Object> list = query. list (); return list ;} /*** query the total number of records * @ param dialect * @ param driverClass * @ param ipAddress * @ param port * @ param dataBaseName * @ param username * @ param password * @ param schema * @ param catalog * @ param tableName * @ param params * @ param iDisplayStart * @ param iDisplayLength * @ return */public int getTotalCount (String dialect, string driverClass, String ipAddress, String port, String dataBaseName, String username, String password, String schema, String catalog, String tableName, Map <String, String> params, Integer iDisplayStart, integer iDisplayLength) {dynamicSqlOperateBefore (dialect, driverClass, ipAddress, port, dataBaseName, username, password, schema, catalog, tableName); StringBuilder SQL = new StringBuilder (); SQL. append ("select count (*) from" + tableName); query = session. createSQLQuery (SQL. toString (); int totalCount = (Number) query. uniqueResult ()). intValue (); return totalCount ;}}

import java.util.Map;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.transform.Transformers;public class DynamicHibernateTest {public static void main(String[] args) {      try{                    Session session=null;                  // oracle        DynamicHibernateConfiguration configuration1 = new DynamicHibernateConfiguration("org.hibernate.dialect.OracleDialect","oracle.jdbc.driver.OracleDriver",                  "ip","1521","orcl","uname","pwd");          System.out.println("hibernate.connection.url==1="+DynamicSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));          DynamicSessionFactory.reflashSessionFactory(configuration1);                     System.out.println("hibernate.connection.url==2="+DynamicSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));                    session=DynamicSessionFactory.getSession();          Query query1 = session.createSQLQuery("select * from WCMDBA.WCM_NEWS where NID=20825").setResultTransformer(                  Transformers.ALIAS_TO_ENTITY_MAP);          Map obj1 = (Map)query1.setMaxResults(1).uniqueResult();          System.out.println("fd1111===="+obj1.get("NID"));                                // mysql          System.out.println("hibernate.connection.url==3="+DynamicSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));          DynamicHibernateConfiguration configuration2 = new DynamicHibernateConfiguration("org.hibernate.dialect.MySQLInnoDBDialect","com.mysql.jdbc.Driver",                  "127.0.0.1","3306","mobileCampus","root","root");                      DynamicSessionFactory.reflashSessionFactory(configuration2);                    System.out.println("hibernate.connection.url==4="+DynamicSessionFactory.getConfiguration().getProperty("hibernate.connection.url"));          session=DynamicSessionFactory.getSession();          Query query2 = session.createSQLQuery("select * from phone_app ").setResultTransformer(                  Transformers.ALIAS_TO_ENTITY_MAP);          Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();          System.out.println("fd2222===="+obj2.get("app_id"));                }catch (Exception e) {          System.err.println(e);      }  } }

Reference: http://feicer.iteye.com/blog/583079

Address: http://download.csdn.net/detail/hellojava1234/5926509

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.