Search in sources :

Example 26 with PersistenceUnitMetaData

use of org.datanucleus.metadata.PersistenceUnitMetaData in project tutorials by eugenp.

the class GuideToJDOIntegrationTest method givenProduct_WhenNewThenPerformTransaction.

@Test
public void givenProduct_WhenNewThenPerformTransaction() {
    PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
    pumd.addClassName("com.baeldung.jdo.Product");
    pumd.setExcludeUnlistedClasses();
    pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
    pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
    pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
    pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
    pumd.addProperty("datanucleus.autoCreateSchema", "true");
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        for (int i = 0; i < 100; i++) {
            String nam = "Product-" + i;
            Product productx = new Product(nam, (double) i);
            pm.makePersistent(productx);
        }
        tx.commit();
    } catch (Throwable thr) {
        fail("Failed test : " + thr.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
    pmf.close();
}
Also used : Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager) PersistenceManagerFactory(javax.jdo.PersistenceManagerFactory) JDOPersistenceManagerFactory(org.datanucleus.api.jdo.JDOPersistenceManagerFactory) JDOPersistenceManagerFactory(org.datanucleus.api.jdo.JDOPersistenceManagerFactory) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) Test(org.junit.Test)

Example 27 with PersistenceUnitMetaData

use of org.datanucleus.metadata.PersistenceUnitMetaData in project datanucleus-core by datanucleus.

the class PersistenceFileMetaDataHandler method endElement.

/**
 * Handler method called at the end of an element.
 * @param uri URI of the tag
 * @param localName local name
 * @param qName Name of element just ending
 * @throws SAXException in parsing errors
 */
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (localName.length() < 1) {
        localName = qName;
    }
    // Save the current string for elements that have a body value
    String currentString = getString().trim();
    MetaData md = getStack();
    if (currentString.length() > 0) {
        if (localName.equals("description")) {
            // Unit description
            ((PersistenceUnitMetaData) md).setDescription(currentString);
        } else if (localName.equals("provider")) {
            // Unit provider
            ((PersistenceUnitMetaData) md).setProvider(currentString);
        } else if (localName.equals("jta-data-source")) {
            // JTA data source
            ((PersistenceUnitMetaData) md).setJtaDataSource(currentString);
        } else if (localName.equals("non-jta-data-source")) {
            // Non-JTA data source
            ((PersistenceUnitMetaData) md).setNonJtaDataSource(currentString);
        } else if (localName.equals("mapping-file")) {
            // New mapping file
            ((PersistenceUnitMetaData) md).addMappingFile(currentString);
        } else if (localName.equals("jar-file")) {
            // New jar file
            ((PersistenceUnitMetaData) md).addJarFile(currentString);
        } else if (localName.equals("class")) {
            // New persistent class
            ((PersistenceUnitMetaData) md).addClassName(currentString);
        } else if (localName.equals("shared-cache-mode")) {
            ((PersistenceUnitMetaData) md).setSharedCacheMode(currentString);
        } else if (localName.equals("validation-mode")) {
            ((PersistenceUnitMetaData) md).setValidationMode(currentString);
        }
    }
    // Handle outside the preceding conditional stmt so handles an empty element tag.
    if (localName.equals("exclude-unlisted-classes")) {
        if (StringUtils.isWhitespace(currentString)) {
            currentString = "true";
        }
        Boolean val = Boolean.valueOf(currentString);
        if (val != null) {
            ((PersistenceUnitMetaData) md).setExcludeUnlistedClasses(val.booleanValue());
        }
    }
    // If startElement pushes an element onto the stack need a remove here for that type
    if (qName.equals("persistence-unit")) {
        popStack();
    }
}
Also used : PersistenceFileMetaData(org.datanucleus.metadata.PersistenceFileMetaData) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) MetaData(org.datanucleus.metadata.MetaData) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData)

Example 28 with PersistenceUnitMetaData

use of org.datanucleus.metadata.PersistenceUnitMetaData in project datanucleus-core by datanucleus.

the class DataNucleusEnhancer method getFileMetadataForInput.

/**
 * Method that processes the registered components to enhance, and loads the metadata for
 * them into the MetaDataManager, returning the associated FileMetaData.
 * @return The FileMetaData for the registered components.
 */
protected Collection<FileMetaData> getFileMetadataForInput() {
    Iterator<EnhanceComponent> iter = componentsToEnhance.iterator();
    Collection<FileMetaData> fileMetaData = new ArrayList<FileMetaData>();
    while (iter.hasNext()) {
        EnhanceComponent comp = iter.next();
        FileMetaData[] filemds = null;
        switch(comp.getType()) {
            case // Of the form "mydomain.MyClass"
            EnhanceComponent.CLASS:
                if (comp.getValue() instanceof String) {
                    // Single class
                    String className = (String) comp.getValue();
                    if (bytesForClassesToEnhanceByClassName != null && bytesForClassesToEnhanceByClassName.get(className) != null) {
                        // Retrieve the meta-data "file"
                        AbstractClassMetaData cmd = metadataMgr.getMetaDataForClass(className, clr);
                        if (cmd != null) {
                            filemds = new FileMetaData[] { cmd.getPackageMetaData().getFileMetaData() };
                        } else {
                        // No meta-data has been registered for this byte-defined class!
                        }
                    } else {
                        filemds = metadataMgr.loadClasses(new String[] { (String) comp.getValue() }, userClassLoader);
                    }
                } else {
                    // Multiple classes
                    filemds = metadataMgr.loadClasses((String[]) comp.getValue(), userClassLoader);
                }
                break;
            case // Absolute/relative filename(s)
            EnhanceComponent.CLASS_FILE:
                if (comp.getValue() instanceof String) {
                    // Single class file
                    String className = null;
                    String classFilename = (String) comp.getValue();
                    if (!StringUtils.getFileForFilename(classFilename).exists()) {
                        String msg = Localiser.msg("005003", classFilename);
                        addMessage(msg, true);
                    } else {
                        className = ClassEnhancerImpl.getClassNameForFileName(classFilename);
                    }
                    if (className != null) {
                        filemds = metadataMgr.loadClasses(new String[] { className }, userClassLoader);
                    }
                } else {
                    // Multiple class files
                    Collection<String> classNames = new ArrayList<String>();
                    String[] classFilenames = (String[]) comp.getValue();
                    for (int i = 0; i < classFilenames.length; i++) {
                        String className = null;
                        if (!StringUtils.getFileForFilename(classFilenames[i]).exists()) {
                            String msg = Localiser.msg("005003", classFilenames[i]);
                            addMessage(msg, true);
                        } else {
                            className = ClassEnhancerImpl.getClassNameForFileName(classFilenames[i]);
                        }
                        if (className != null) {
                            classNames.add(className);
                        }
                    }
                    filemds = metadataMgr.loadClasses(classNames.toArray(new String[classNames.size()]), userClassLoader);
                }
                break;
            case // Absolute/relative filename(s)
            EnhanceComponent.MAPPING_FILE:
                if (comp.getValue() instanceof String) {
                    // Single mapping file
                    filemds = metadataMgr.loadMetadataFiles(new String[] { (String) comp.getValue() }, userClassLoader);
                } else {
                    // Multiple mapping files
                    filemds = metadataMgr.loadMetadataFiles((String[]) comp.getValue(), userClassLoader);
                }
                break;
            case // Absolute/relative filename(s)
            EnhanceComponent.JAR_FILE:
                if (comp.getValue() instanceof String) {
                    // Single jar file
                    filemds = metadataMgr.loadJar((String) comp.getValue(), userClassLoader);
                } else {
                    // Multiple jar files
                    String[] jarFilenames = (String[]) comp.getValue();
                    Collection<FileMetaData> filemdsColl = new HashSet<FileMetaData>();
                    for (int i = 0; i < jarFilenames.length; i++) {
                        FileMetaData[] fmds = metadataMgr.loadJar(jarFilenames[i], userClassLoader);
                        for (int j = 0; j < fmds.length; j++) {
                            filemdsColl.add(fmds[j]);
                        }
                    }
                    filemds = filemdsColl.toArray(new FileMetaData[filemdsColl.size()]);
                }
                break;
            case EnhanceComponent.PERSISTENCE_UNIT:
                PersistenceUnitMetaData pumd = null;
                try {
                    Object puValue = comp.getValue();
                    if (puValue instanceof String) {
                        // Extract the metadata for the persistence-unit
                        NucleusContext nucleusCtx = metadataMgr.getNucleusContext();
                        String filename = nucleusCtx.getConfiguration().getStringProperty(PropertyNames.PROPERTY_PERSISTENCE_XML_FILENAME);
                        boolean validateXML = nucleusCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_XML_VALIDATE);
                        boolean supportXMLNamespaces = nucleusCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_XML_NAMESPACE_AWARE);
                        pumd = MetaDataUtils.getMetaDataForPersistenceUnit(nucleusCtx.getPluginManager(), filename, (String) comp.getValue(), validateXML, supportXMLNamespaces, clr);
                    } else {
                        pumd = (PersistenceUnitMetaData) puValue;
                    }
                } catch (NucleusException ne) {
                    // No "persistence.xml" files found yet they have specified a persistence-unit name!
                    throw new NucleusEnhanceException(Localiser.msg("005008", comp.getValue()));
                }
                if (pumd == null) {
                    throw new NucleusEnhanceException(Localiser.msg("005009", comp.getValue()));
                }
                filemds = metadataMgr.loadPersistenceUnit(pumd, userClassLoader);
                break;
            default:
                break;
        }
        if (filemds != null) {
            for (int i = 0; i < filemds.length; i++) {
                fileMetaData.add(filemds[i]);
            }
        }
    }
    return fileMetaData;
}
Also used : NucleusContext(org.datanucleus.NucleusContext) ArrayList(java.util.ArrayList) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) NucleusException(org.datanucleus.exceptions.NucleusException) FileMetaData(org.datanucleus.metadata.FileMetaData) HashSet(java.util.HashSet)

Example 29 with PersistenceUnitMetaData

use of org.datanucleus.metadata.PersistenceUnitMetaData in project tests by datanucleus.

the class AnnotationPlusXMLTest method testOneToManyBiJoin.

/**
 * Test of JPA 1-N unidir FK relation.
 * This is really a 1-N uni join since JPA doesnt support 1-N uni FK.
 */
/*public void testOneToManyUniFK()
    {
        NucleusContext nucleusCtx = new NucleusContext("JPA", null);
        ClassLoaderResolver clr = new ClassLoaderResolverImpl();
        MetaDataManager metaDataMgr = new JPAMetaDataManager(pmfcontext);
        PersistenceUnitMetaData pumd = metaDataMgr.getMetaDataForPersistenceUnit("JPATest");
        metaDataMgr.initialise(pumd, clr);

        // owner side
        ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Site.class.getName(), clr);
        AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("offices");
        assertNotNull("Site.offices is null!", fmd1);
        assertEquals("Site.offices mapped-by is incorrect", fmd1.getMappedBy(), null);
        assertEquals("Site.offices relationType is incorrect",
            fmd1.getRelationType(clr), Relation.ONE_TO_MANY_UNI);
        assertEquals("Site.offices jointable name is incorrect", fmd1.getTable(), null);
        assertNotNull("Site.offices should have join but doesnt", fmd1.getJoinMetaData());

        ElementMetaData elemmd = fmd1.getElementMetaData();
        assertNotNull("Site.offices has no element column info but should", elemmd);
        ColumnMetaData[] colmds = elemmd.getColumnMetaData();
        assertNotNull("Site.offices has incorrect element columns", colmds);
        assertEquals("Site.offices has incorrect number of element columns", colmds.length, 1);
        assertEquals("Site.offices has incorrect element column name", colmds[0].getName(), "SITE_ID");
    }*/
/**
 * Test of JPA 1-N bidir JoinTable relation
 */
public void testOneToManyBiJoin() {
    NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null);
    ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null);
    MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx);
    PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest");
    metaDataMgr.loadPersistenceUnit(pumd, null);
    // owner side
    ClassMetaData cmd1 = (ClassMetaData) metaDataMgr.getMetaDataForClass(Manager.class.getName(), clr);
    assertEquals("Manager has incorrect table name", cmd1.getTable(), "JPA_AX_MANAGER");
    AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("subordinates");
    assertNotNull("Manager.subordinates is null!", fmd1);
    assertEquals("Manager.subordinates mapped-by is incorrect", fmd1.getMappedBy(), "manager");
    assertEquals("Manager.subordinates relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_BI);
    assertEquals("Manager.subordinates jointable name is incorrect", fmd1.getTable(), "JPA_AX_MGR_EMPLOYEES");
    // non-owner side
    ClassMetaData cmd2 = (ClassMetaData) metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr);
    assertEquals("Employee has incorrect table name", cmd2.getTable(), "JPA_AX_EMPLOYEE");
    AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("manager");
    assertNotNull("Employee.manager is null!", fmd2);
    assertEquals("Employee.manager mapped-by is incorrect", fmd2.getMappedBy(), null);
    assertEquals("Employee.manager relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_ONE_BI);
    assertEquals("Employee.manager jointable name is incorrect", fmd2.getTable(), null);
    // join-table
    JoinMetaData joinmd = fmd1.getJoinMetaData();
    assertNotNull("Manager.subordinates has no join table!", joinmd);
    assertNotNull("Manager.subordinates has incorrect join columns", joinmd.getColumnMetaData());
    assertEquals("Manager.subordinates has incorrect number of join columns", 1, joinmd.getColumnMetaData().length);
    assertEquals("Manager.subordinates has incorrect owner join column name", "MGR_ID", joinmd.getColumnMetaData()[0].getName());
    ElementMetaData elemmd = fmd1.getElementMetaData();
    assertNotNull("Manager.subordinates has no element column info but should", elemmd);
    assertNotNull("Manager.subordinates has incorrect element columns", elemmd.getColumnMetaData());
    assertEquals("Manager.subordinates has incorrect number of element columns", 1, elemmd.getColumnMetaData().length);
    assertEquals("Manager.subordinates has incorrect element join column name", "EMP_ID", elemmd.getColumnMetaData()[0].getName());
}
Also used : JPAMetaDataManager(org.datanucleus.api.jpa.metadata.JPAMetaDataManager) ElementMetaData(org.datanucleus.metadata.ElementMetaData) NucleusContext(org.datanucleus.NucleusContext) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) JPAMetaDataManager(org.datanucleus.api.jpa.metadata.JPAMetaDataManager) MetaDataManager(org.datanucleus.metadata.MetaDataManager) PersistenceNucleusContextImpl(org.datanucleus.PersistenceNucleusContextImpl) JoinMetaData(org.datanucleus.metadata.JoinMetaData) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData)

Example 30 with PersistenceUnitMetaData

use of org.datanucleus.metadata.PersistenceUnitMetaData in project tests by datanucleus.

the class AnnotationPlusXMLTest method testSequenceGenerator.

/**
 * Test of JPA <sequence-generator>
 */
public void testSequenceGenerator() {
    NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null);
    ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null);
    MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx);
    PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest");
    metaDataMgr.loadPersistenceUnit(pumd, null);
    ClassMetaData cmd1 = (ClassMetaData) metaDataMgr.getMetaDataForClass(Department.class.getName(), clr);
    PackageMetaData pmd = cmd1.getPackageMetaData();
    assertEquals("Number of Sequences registered for Department class is wrong", pmd.getNoOfSequences(), 1);
    SequenceMetaData seqmd = pmd.getSequences()[0];
    assertEquals("SequenceGenerator has incorrect name", seqmd.getName(), "DepartmentGenerator");
    assertEquals("SequenceGenerator has incorrect sequence name", seqmd.getDatastoreSequence(), "DEPT_SEQ");
    assertEquals("SequenceGenerator has incorrect initial value", seqmd.getInitialValue(), 1);
    assertEquals("SequenceGenerator has incorrect allocation size", seqmd.getAllocationSize(), 50);
}
Also used : JPAMetaDataManager(org.datanucleus.api.jpa.metadata.JPAMetaDataManager) PackageMetaData(org.datanucleus.metadata.PackageMetaData) NucleusContext(org.datanucleus.NucleusContext) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) JPAMetaDataManager(org.datanucleus.api.jpa.metadata.JPAMetaDataManager) MetaDataManager(org.datanucleus.metadata.MetaDataManager) PersistenceNucleusContextImpl(org.datanucleus.PersistenceNucleusContextImpl) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) SequenceMetaData(org.datanucleus.metadata.SequenceMetaData)

Aggregations

PersistenceUnitMetaData (org.datanucleus.metadata.PersistenceUnitMetaData)48 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)40 PersistenceNucleusContextImpl (org.datanucleus.PersistenceNucleusContextImpl)40 NucleusContext (org.datanucleus.NucleusContext)39 JPAMetaDataManager (org.datanucleus.api.jpa.metadata.JPAMetaDataManager)38 ClassMetaData (org.datanucleus.metadata.ClassMetaData)38 MetaDataManager (org.datanucleus.metadata.MetaDataManager)38 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)23 ElementMetaData (org.datanucleus.metadata.ElementMetaData)12 JoinMetaData (org.datanucleus.metadata.JoinMetaData)9 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)6 PackageMetaData (org.datanucleus.metadata.PackageMetaData)6 JDOPersistenceManagerFactory (org.datanucleus.api.jdo.JDOPersistenceManagerFactory)4 EventListenerMetaData (org.datanucleus.metadata.EventListenerMetaData)3 KeyMetaData (org.datanucleus.metadata.KeyMetaData)3 MapMetaData (org.datanucleus.metadata.MapMetaData)3 SequenceMetaData (org.datanucleus.metadata.SequenceMetaData)3 TableGeneratorMetaData (org.datanucleus.metadata.TableGeneratorMetaData)3 ArrayList (java.util.ArrayList)2 PersistenceManager (javax.jdo.PersistenceManager)2