Hibernate schema简单分析
Hibernate有很多值得学习的地方,这里我们主要介绍Hibernate schema,包括介绍切换Schema等方面。
Hibernate schema
如果你在调用Hibernate的时候需要切换schema怎么办呢。
在oracle中,不同的用户,使用不同的schema.在Hibernate的POJO中,会指定了schema
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.csc.poimanager.dao.Poi" table="POI" schema="P_BEIJING"> <id name="poiId" type="java.lang.Long"> <column name="POI_ID" precision="10" scale="0" /> <generator class="increment" /> </id> <property name="cnName" type="java.lang.String"> <column name="CN_NAME" length="1000" /> </property> </class> </hibernate-mapping>
上面的代码部分,就指定了Schema.如果在操作的时候想切换Schema.操作如下:
默认的配置<property name="Hibernate.default_schema">POI_BEIJING</property>
上面的映射文件改为:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.csc.poimanager.dao.Poi" table="POI" > <id name="poiId" type="java.lang.Long"> <column name="POI_ID" precision="10" scale="0" /> <generator class="increment" /> </id> <property name="cnName" type="java.lang.String"> <column name="CN_NAME" length="1000" /> </property> </class> </hibernate-mapping>
在操作的,可以用下面的方法来重新build你的SessionFactory
public static void rebuildSessionFactoryForChangeSchema(String newSchema){ try { Properties p = configuration.getProperties(); System.out.println("---" + p); p.put("hibernate.default_schema", newSchema); sessionFactory = configuration.buildSessionFactory(); System.out.println(" change schema successfully ......... "); } catch (Exception e) { System.err .println("%%%% rebuild session factory failed for changing schema %%%%"); e.printStackTrace(); } }
如果需要改变Schema,就需要在需要的时候调用此方法。
比如在SchemaAction中
HibernateSessionFactory.rebuildSessionFactoryForChangeSchema("POI_SHANGHAI"); System.out.println(" change successfully---"); PoiDAO pd = new PoiDAO(); Transaction t =pd.getSession().beginTransaction(); pd.save(new Poi("jsfjksdf")); t.commit();