2010-04-15 15 views
17

मैं एक मुख्य विधि SchemaUpdate का उपयोग कर सांत्वना क्या टेबल बदल/बनाने के लिए पर प्रदर्शित करने के लिए है और यह मेरी हाइबरनेट परियोजना में ठीक काम करता है:एक जेपीए persistence.xml के साथ Hibernate SchemaUpdate कक्षा का उपयोग कैसे करें?

public static void main(String[] args) throws IOException { 
    //first we prepare the configuration 
    Properties hibProps = new Properties(); 
    hibProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jbbconfigs.properties")); 
    Configuration cfg = new AnnotationConfiguration(); 
    cfg.configure("/hibernate.cfg.xml").addProperties(hibProps); 

    //We create the SchemaUpdate thanks to the configs 
    SchemaUpdate schemaUpdate = new SchemaUpdate(cfg); 


    //The update is executed in script mode only 
    schemaUpdate.execute(true, false); 
    ... 

मैं एक जेपीए परियोजना में इस कोड को पुन: उपयोग करना चाहते हैं, कोई hibernate.cfg.xml फ़ाइल नहीं है (और नहीं .properties फ़ाइल), लेकिन एक persistence.xml फ़ाइल (जेपीए spec द्वारा निर्दिष्ट मेटा-आईएनएफ निर्देशिका में autodetected)।

मैं इस बहुत आसान अनुकूलन की कोशिश की,

Configuration cfg = new AnnotationConfiguration(); 
cfg.configure(); 

लेकिन यह है कि अपवाद के साथ विफल रहा है।

Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found 

क्या किसी ने ऐसा किया है? धन्यवाद।

उत्तर

7

करीम सही रास्ते पर है, लेकिन मुझे स्पष्टीकरण देने का प्रयास करने दें।

मान लीजिए कि आपके पास वेनिला जेपीए-मानक कॉन्फ़िगरेशन है, जिसमें क्लासपाथ पर हाइबरनेट जार को छोड़कर हाइबरनेट-विशिष्ट कुछ भी नहीं है। आप J2SE बूटस्ट्रैप मोड में चल रहा है, तो आप पहले से ही कुछ कोड है कि इस तरह दिखता है, या तो जावा SchemaUpdate चलाने के लिए या वसंत विन्यास, आदि .: रूप

Map<String, Object> props = getJPAProperties(); 
EntityManagerFactory emf = 
    Persistence.createEntityManagerFactory("persistence-unit-name", props); 

है, बस इस के बजाय का उपयोग करें:

Map<String, Object> props = getJPAProperties(); 
Ejb3Configuration conf = 
    new Ejb3Configuration().configure("persistence-unit-name", props); 
new SchemaUpdate(conf.getHibernateConfiguration()).execute(true, false); 

मुझे यकीन नहीं है कि यह एक कंटेनर वातावरण में कैसे काम करेगा, लेकिन एक साधारण जे 2 एसई या स्प्रिंग प्रकार के कॉन्फ़िगरेशन में, यह सब कुछ है।

+0

प्ले फ्रेमवर्क पर, मैं Ejb3Configuration पर getHibernateConfiguration() का उपयोग करें और मैं एक "कोई प्रदान की डेटा स्रोत" प्राप्त करते हैं। मैं एक कनेक्शन (DB.datasource.getConnection() खेलने पर कैसे प्रदान कर सकता हूं)? –

3

आपको सामान्य कॉन्फ़िगरेशन के बजाय Ejb3 कॉन्फ़िगरेशन का उपयोग करना चाहिए। हाइबरनेट दस्तावेज में bootstrapping section के अंत में, इकाई प्रबंधक दस्तावेज़ का संदर्भ लें।

(लघु रूपांतरों के साथ स्रोत ऊपर से नकल)

Ejb3Configuration cfg = new Ejb3Configuration(); 
EntityManagerFactory emf = 
    cfg.addProperties(properties)     // add some properties 
    .setInterceptor(myInterceptorImpl)   // set an interceptor 
    .addAnnotatedClass(MyAnnotatedClass.class) // add a class to be mapped 
    .addClass(NonAnnotatedClass.class)   // add an hbm.xml file using the Hibernate convention 
    .addResource("mypath/MyOtherCLass.hbm.xml") // add an hbm.xml file 
    .addResource("mypath/orm.xml")    // add an EJB3 deployment descriptor 
    .configure("/mypath/hibernate.cfg.xml")  // add a regular hibernate.cfg.xml 
    .buildEntityManagerFactory();    // create the entity manager factory 

आप देख सकते हैं, आप विन्यास के विभिन्न प्रकार के एक बहुत मिश्रण कर सकते हैं।

यदि यह केवल स्कीमा अद्यतन भाग के लिए है, तो आप सिर्फ अपने persistence.xml में एक गुण सेट कर सकते हैं: hibernate.hbm2ddl.auto:

<persistence-unit name="app1"> 
    <provider>org.hibernate.ejb.HibernatePersistence</provider> 
    <properties> 
    … 
    <property name="hibernate.hbm2ddl.auto" value="update"/> 
    </properties> 
</properties> 

कुछ और संदर्भ के लिए here देखें।

1

धन्यवाद पीटर, आपका जवाब ठीक काम करता है। यहाँ हमारे SchemaUpdater वर्ग का पूरा कोड है:

package reformyourcountry.dbupdate; 

import java.io.BufferedReader; 
import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintStream; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import org.hibernate.ejb.Ejb3Configuration; 
import org.hibernate.tool.hbm2ddl.SchemaUpdate; 

import reformyourcountry.misc.DateUtil; 

/** Small utility to be run by a developer to identify the difference between 
* its entities and its DB schema. It produces an SQL to be copy/pasted and applied 
* on the DB manually. Each developers having its own DB, when a developer commits its 
* Java code with new entity attributes (needing new DB columns), he also commits 
* an updated SQL file with the SQL that other developers need to apply on their local DB. 
* Later, when deploying the next version of the application in production, 
* this SQL file with cumulated changes will be applied onto the production DB. 
* 
* Limitations: 
* 1. the Hibernate schema update does not detect removed attributes. 
* If you have to delete a column, you need to write the SQL manually; 
* 
* 2. the Hibernate schema update does not detect changes on existing columns. 
* for example, if you add @Column(nullable=false), it will not generates an 
* additional DB constraint. 
* 
* @author Cédric Fieux & John Rizzo & Aymeric Levaux 
* 
*/ 
public class SchemaUpdater { 

    @SuppressWarnings({ "deprecation", "unchecked" }) 
    public static void main(String[] arg) throws IOException { 

     ////// 1. Prepare the configuration (connection parameters to the DB, ect.) 
     // Empty map. We add no additional property, everything is already in the persistence.xml 
     Map<String,Object> map=new HashMap<String,Object>(); 
     // Get the config from the persistence.xml file, with the unit name as parameter. 
     Ejb3Configuration conf = new Ejb3Configuration().configure("ConnectionPostgres",map); 
     SchemaUpdate schemaUpdate =new SchemaUpdate(conf.getHibernateConfiguration()); 

     /////// 2. Get the SQL 
     // Before we run the update, we start capturing the console output (to add ";" later) 
     PrintStream initOut = System.out; 
     ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); 
     PrintStream newOut = new PrintStream(outputStream); 
     System.setOut(newOut); 

     //The update is executed in script mode only 
     schemaUpdate.execute(true, false); 

     //We reset the original out 
     System.setOut(initOut); 

     ////// 3. Prints that SQL at the console with a good format (adding a ";" after each line). 
     System.out.println("--*******************************************Begin of SQL********************************************"); 
     System.out.println("-- "+DateUtil.formatyyyyMMdd(new Date())); 
     BufferedReader ouReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray()))); 
     String str = ouReader.readLine(); 
     while(str != null){ // For each (sometimes multiline) SQL statement 
      // now, str equals "". 
      str = ouReader.readLine(); // 
      while (str != null && !str.trim().equals("")) { // for each line of the same statement 
       System.out.println(); // previous line is finished. 
       System.out.print(str.toLowerCase()); 
       str = ouReader.readLine(); 
      } 
      // Statement is now finished 
      System.out.println(";"); 
     } 
     System.out.println("--*******************************************End of SQL********************************************"); 

     ////// 4. Print eventual exceptions. 
     //If some exception occurred we display them 
     if(!schemaUpdate.getExceptions().isEmpty()){ 
      System.out.println(); 
      System.out.println("SOME EXCEPTIONS OCCURED WHILE GENERATING THE UPDATE SCRIPT:"); 
      for (Exception e: (List<Exception>)schemaUpdate.getExceptions()) { 
       System.out.println(e.getMessage()); 
      } 
     } 
    } 

}