Re: Mapping of empty Embeddables
Tobias, A feature[1] was added to OpenJPA 2.2.1 (and later) that *may* provide the behavior you are looking for. It allows embeddable entities to be treated as true null references if they are marked lazy. One difference is that they are lazy, so if you detach the entity it will not load the embeddable when you try to access it. You need to use a custom annotation or OpenJPA's ORM extensions to get this behavior. Check out the commits associated with the JIRA if you need an example of how to use this feature with ORM extensions. WebSphere allows the use of OpenJPA annotations for application usage so unless you have a policy against using non-spec APIs, using annotations is much simpler than creating a custom orm file. example: import org.apache.openjpa.persistence.Persistent; ... @Persistent(fetch=FetchType.LAZY, embedded=true) private MyEmbeddable myEmbed; The @Persistent annotation is used instead of @Embedded. I'm not sure if this will give you exactly what you are looking for, but I think it is worth checking out. I'm afraid that if you need to access the embeddable, which will trigger a load, you could end up with the same behavior you have now. I don't recall the exact behavior of the feature, though. -Jeremy [1] https://issues.apache.org/jira/browse/OPENJPA-2141 On Tue, Aug 6, 2013 at 10:59 AM, Meyer, Tobias tobias.me...@capgemini.comwrote: Hi, I am migrating an application from Glassfish/EclipseLink to WebSphere/OpenJPA 2.2.2 and I have to following problem. Eclipselink and OpenJPA handle “empty” Embeddables (i.e. Embeddables with all fields null) differently. OpenJPA’s default assumption is that an Embeddable is always “non-null”, but EclipseLink does the opposite, meaning if all persistent members are null, the whole Embeddable is null. The application heavily uses validation annotations on the members of the embeddables and @NotNull is one of them. Now think of an entity that contains an embeddable which may be null. There is no problem in persisting the entity. There is also no problem when you try to load that entity from the database. But when you modify some attribute of the entity and OpenJPA tries to update it in the database, then you get a javax.validation.ConstraintViolationException because OpenJPA validated the “empty” embeddable it created when it loaded the entity from the database and there is a @NotNull annotation on a member of the embeddable which is now null. I know this isn’t a bug of OpenJPA since JPA does not specify what to expect when all members of an Embeddable are null. But my question is: *Is there a way to configure OpenJPA (globally) to behave like eclipselink in the case of “empty” embeddables*, without the need to use OpenJPA specific annotations in the code like “@EmbeddedMapping(nullIndicatorColumnName=”xyz”)? The java code has to be strictly JPA provider neutral, because the application (EAR) has to work on both platforms. Provider specific properties in persistence.xml or other configuration files, which don’t interfere with EclipseLink would be okay. Thanks for your help, Tobias ___ [image: Email_CBE.gif]*Tobias Meyer* Custom Solution Development | Application Services Capgemini | Hamburg Phone: +4940254491291 – Mobile: +4915140250554 e-mail: tobias.me...@capgemini.com www.de.capgemini.com Luebecker Strasse 128, D-22087 Hamburg, Germany *People matter, results count.* ___ -- Firma: Capgemini Deutschland GmbH Geschäftsführer: Dr. Michael Schulte (Sprecher) • Dr. Uwe Dumslaff • Josef Ranner Aufsichtsratsvorsitzender: Antonio Schnieder Amtsgericht Berlin-Charlottenburg, HRB 98814 This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message.
Re: record delete during flo
Glad to hear you were able to resolve this issue. Thanks for replying back to the list. -Jeremy On Mon, Jul 15, 2013 at 5:54 PM, mysakjs my...@us.ibm.com wrote: Update: This turned out to be a code issue.The managed entity was being updated in an unexpected location and when the transaction was committed the associated db rows were deleted. So this does not appear to be a JPA issue, but a code issue. -- View this message in context: http://openjpa.208410.n2.nabble.com/record-delete-during-flo-tp7584399p7584424.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
[CVE-2013-1768] Apache OpenJPA security vulnerability
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 CVE-2013-1768: Apache OpenJPA security vulnerability Severity: Important Vendor: The Apache Software Foundation Versions Affected: OpenJPA 1.0.0 to 1.0.4 OpenJPA 1.1.0 OpenJPA 1.3.0 OpenJPA 1.2.0 to 1.2.2 OpenJPA 2.0.0 to 2.0.1 OpenJPA 2.1.0 to 2.1.1 OpenJPA 2.2.0 to 2.2.1 Description: Deserialization of a maliciously crafted OpenJPA object can result in an executable file being written to the file system. An attacker needs to discover an unprotected server program to exploit the vulnerability. It then needs to exploit another unprotected server program to execute the file and gain access to the system. OpenJPA usage by itself does not introduce the vulnerability. Mitigation: Users of OpenJPA using a release based upon the JPA 1.0 specification level should upgrade to the OpenJPA 1.2.3 release. Users of OpenJPA using a release based upon the JPA 2.0 specification level should upgrade to the OpenJPA 2.2.2 release. Users needing to stay on their current release should get the latest code from svn for the corresponding branch level or apply a source patch and build a new binary package. Nightly snapshots of the latest source builds are also available for many branches. OpenJPA release branch levels and corresponding fix revisions: OpenJPA 1.0.x revision 1462558: http://svn.apache.org/viewvc?view=revisionrevision=1462558 OpenJPA 1.1.x revision 1462512: http://svn.apache.org/viewvc?view=revisionrevision=1462512 OpenJPA 1.2.x revision 1462488: http://svn.apache.org/viewvc?view=revisionrevision=1462488 OpenJPA 1.3.x revision 1462328: http://svn.apache.org/viewvc?view=revisionrevision=1462328 OpenJPA 2.0.x revision 1462318: http://svn.apache.org/viewvc?view=revisionrevision=1462318 OpenJPA 2.1.x revision 1462268: http://svn.apache.org/viewvc?view=revisionrevision=1462268 OpenJPA 2.2.1.x revision 1462225: http://svn.apache.org/viewvc?view=revisionrevision=1462225 OpenJPA 2.2.x revision 1462076: http://svn.apache.org/viewvc?view=revisionrevision=1462076 Example: An attacker creates a customized serialization of an OpenJPA object. The attacker exploits an unprotected server program to execute the object. The object includes logic that results in malicious trace being written to a file, such as a JSP. The file containing malicious commands is written to a potentially vulnerable area of the system. The attacker exploits a second unprotected server program to execute the file and gain access to the system. Credit: This issue was discovered by Pierre Ernst of IBM Corporation. -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.20 (MingW32) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iQIcBAEBAgAGBQJRuMz9AAoJEALD36U3PPjRdzMQAKYkGuFQ/jT6Txy5UemN7oC3 bAUsJRlAsV11uZTnTNo4hgtZVA9Q9fN2NbswjcWFS+/U1MljgrF9lqHspm/SV9o5 Yi4S39AtMKva0eBMGaRGBpARhu7QbMOxD7D9dqp79bHcgxfZROG71bwx4dTL3q3Z 3dxOEnkqPUM9vZFm3zrMKF4Hy3q/TuMIJtFtj/B5KuNtlJFXUe908wzoQyQjm9Al M7xZhWGdGnVwD1ynlrG5exWZ8xlQ5W4TGeK/h3zJ05kYQHXIwhgiympApNfIYCQZ 1zexnGv7pWQI/NVXPv8XaxtZ6HYUn+1GpZ8ipF4nCoXy0KTfLJmd9wcpxU8b+4c1 tguzC8rYbol7TxkMy/HpAgHTavIfDXFZyjl5/z2X6e+s6YtP+TRCN8Jy7fpg0AuU OFQp+LoY06vFJmoJiL0+TiNeotcZuH1l8OL6PuvXHF/4saAUfADNHqJIR5xBTdPY rIy8gtS06IM6aOhSbCrJphIpSOk5qQQV5Uhzfo5NXFeglBxP+YEPFq5sBmVIPEOG IL6u6CAclmMKg+vqXUeY1EsmV2lrhqshyBh7umTSSm7YWNgoQJJxUn/8phxATJ3K DlaZWId//mmnz36349m9HF2hc5iPea01MDcWHUwe2a0d0Wmwz6CXlvWuBNtTmZoV 7iGIxMiN7yJ14RZoDsKw =LVgy -END PGP SIGNATURE-
Re: FieldStrategy found
I'm very glad to hear you got this working. If you don't mind and can share the root issue and solution, we may be able to improve OpenJPA and/or it may help someone with the same or similar issue. Regardless, thanks for the follow-up! -Jeremy On Tue, Jun 4, 2013 at 8:43 AM, rwheeler rwhee...@novatusinc.com wrote: Thanks for all of the help I finally got this working -- View this message in context: http://openjpa.208410.n2.nabble.com/FieldStrategy-not-found-tp7584021p7584069.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: FieldStrategy found
Hi, Are you in an OSGi environment? If so, make sure you have a package import for the org.apache.openjpa. persistence.jdbc package. Otherwise, the Strategy annotation won't be visible from the classloader. OpenJPA will not find the annotation when it scans the entity class. If you are not using OSGi or have the import, the next step would be to take an openjpa trace via: property name=openjpa.Log value=TRACE/ The trace will show which strategy is used for each field mapping. Minimally, you'll be able to see whether the strategy you've defined is being used. Also, you likely don't need to implement a field strategy from zero. Instead, you can extend one of the OpenJPA handlers. This blog may help: http://www.webspherepersistence.blogspot.com/2009/04/custom-orm-with-openjpa.html hth, -Jeremy On Fri, May 24, 2013 at 12:45 PM, rwheeler rwhee...@novatusinc.com wrote: I am trying to implement a @Strategy using the FieldStrategy interface. The problem I am having is that when I go to persist my object it is always going with the default handlers. I am not receiving any exceptions until it goes to do the insert. I am wondering if I have done this correctly or not so any feedback is appreciated. package test.openjpa.entity; import java.io.Serializable; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import org.apache.openjpa.persistence.jdbc.Strategy; @Entity public class Company implements Serializable { /** * */ private static final long serialVersionUID = 6741913908217906576L; @Id @Strategy(test.openjpa.entity.OpenUuid) protected UUID id; @Column(name=name) private String companyName; public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Id = ).append(id).append( - ); sb.append(Name = ).append(companyName); return sb.toString(); } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } @PrePersist public void assignUUID(){ this.setId(UUID.randomUUID()); } } package test.openjpa.entity; import java.sql.SQLException; import java.util.UUID; import org.apache.openjpa.jdbc.kernel.JDBCFetchConfiguration; import org.apache.openjpa.jdbc.kernel.JDBCStore; import org.apache.openjpa.jdbc.meta.FieldMapping; import org.apache.openjpa.jdbc.meta.FieldStrategy; import org.apache.openjpa.jdbc.sql.Joins; import org.apache.openjpa.jdbc.sql.Result; import org.apache.openjpa.jdbc.sql.RowManager; import org.apache.openjpa.jdbc.sql.SQLBuffer; import org.apache.openjpa.jdbc.sql.Select; import org.apache.openjpa.jdbc.sql.SelectExecutor; import org.apache.openjpa.kernel.OpenJPAStateManager; import org.apache.openjpa.persistence.jdbc.Strategy; public class OpenUuid implements FieldStrategy { /** * */ private static final long serialVersionUID = -7313412704454986736L; public class PostgresUuid extends org.postgresql.util.PGobject { public static final long serialVersionUID = 89469482L; public PostgresUuid(UUID u) throws java.sql.SQLException { super(); this.setType(uuid); this.setValue(u.toString()); } public PostgresUuid() throws java.sql.SQLException { super(); this.setType(uuid); this.setValue(null); } } @Override public String getAlias() { // TODO Auto-generated method stub return null; } @Override public void map(boolean adapt) { // TODO Auto-generated method stub } @Override public void initialize() { // TODO Auto-generated method stub } @Override public void insert(OpenJPAStateManager sm, JDBCStore store, RowManager rm) throws SQLException { System.out.println(I am inside the insert); } @Override public void update(OpenJPAStateManager sm, JDBCStore store, RowManager rm) throws SQLException { // TODO Auto-generated method stub } @Override public void
Re: FieldStrategy found
It looks like the strategy you've defined isn't being picked up on the annotation scan. If it were a problem related to loading your handler/strategy class, you see an exception from createEntityManager(). The most common cause is a missing OSGi bundle import. I've also seen cases where this issue is caused by having multiple copies of OpenJPA binaries in the environment, each being loaded by different classloaders. That can result in the @Strategy class being scanned by the runtime != @Strategy class used by the application. Beyond that, you might look into using the OSGi console, if possible, to determine whether your bundle is able to resolve the import. -Jeremy On Fri, May 24, 2013 at 1:36 PM, rwheeler rwhee...@novatusinc.com wrote: Sorry yes I am in OSGI enviroment. I do have org.apache.openjpa.persistence.jdbc being imported. This is what I have from my trace log for that particular field 39598 camel TRACE [Camel (557-camel-32) thread #19 - timer://myTimer] openjpa.MetaData - id has mapping strategy org.apache.openjpa.jdbc.meta.strats.HandlerFieldStrategy. -- View this message in context: http://openjpa.208410.n2.nabble.com/FieldStrategy-not-found-tp7584021p7584023.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
[ANNOUNCE] OpenJPA 1.2.3 Released
The Apache OpenJPA community is proud to announce the release of OpenJPA 1.2.3. Please visit our project website to learn more about Apache OpenJPA and how to download or include our persistence provider in your builds. http://openjpa.apache.org/ Apache OpenJPA PMC
Re: generate jpa entities without schema name included in @Table annotation
Hi, The reverse mapping tool can operate over multiple schemas so the table annotation includes the schema name to ensure that the mappings match. I checked the code and config and didn't spot any way to change this behavior with the existing configuration options. The only option that came to mind is to write a custom MetaDataFactory plugin that supplies a custom AnnotationPersistenceMappingSerializer. Your custom serializer would then need to override the serializeClassMappingContent method. This method calls the (private) serializeTable method to create the @Table annotation that is used in the generated Java source. You could easily write your own version of serializeTable to eliminate the schema name from the annotation. A little tedious and a little extra configuration, but doable... This seems like a useful general feature for the reverse mapping tool, though. A switch to disable adding the schema name to the mapping should be fairly simple to add. You could open a JIRA for the feature request - https://issues.apache.org/jira/browse/OPENJPA. If you come up with a patch you could contribute it to the project or someone else in the community may pick up the JIRA and code up the feature. -Jeremy On Mon, Apr 1, 2013 at 3:57 PM, mysakjs my...@us.ibm.com wrote: Is there an option for org.apache.openjpa.jdbc.meta.ReverseMappingTool that will effectively avoid adding the schema name for the @Table annotation on generated entities? I want to remove the schema name so the jpa entities don't have to be updated in order to target an alternate set of schemas. (instead we'll use openjpa.jdbc.Schema to set the default schema in persistence.xml ). -useSchemaName=false doesn't seem to help, as it only affects whether or not the schema name is included in the generated class name. Is there another property I can set for this, e.g. to avoid having to post-process the entities to remove the schema name from the @Table annotation? -- View this message in context: http://openjpa.208410.n2.nabble.com/generate-jpa-entities-without-schema-name-included-in-Table-annotation-tp7583310.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: CLOB loading - query per row
Hi Simon, What database are you using? Each DB/JDBC driver handles retrieving lob data differently (although, that is continually getting better and more standardized with new rev's of JDBC). Some DBs allow inlining, sometimes they requires a separate fetch or vendor specific API. Normally, this via DB/driver specific code is isolated in the DB dictionaries. It is odd that OpenJPA is behaving differently with one path vs. another, though. Any chance you could post a very simple testcase? -Jeremy On Mon, Feb 6, 2012 at 6:19 PM, Simon Droscher simon.drosc...@elasticpath.com wrote: Hi. Just wondering if anyone had encountered a similar issue to us with CLOB loading and/or can explain the behaviour: When we have entities with CLOB fields and do a EntityManager.get() of one of those objects, OpenJPA will load the CLOBs with the rest of the data as part of a single query. But when we load the same object using a named query, for example SELECT t FROM Thing t WHERE t.code = ?1, OpenJPA generates a separate SQL query for each CLOB row after it has loaded the rest of the data for that object. We see this behaviour even when we are only querying for a single field of the object (not even the CLOB field). This is having a big impact on performance for us as it involves a lot more roundtrips to the DB. FYI we are running OpenJPA 1.2.1 -- View this message in context: http://openjpa.208410.n2.nabble.com/CLOB-loading-query-per-row-tp7260505p7260505.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: may be OpenJPA limitation
Based on the SQLCODE, it looks like the table USER in schema DBSCHEMA does not exist. Is that table located in a different schema than the default? If so, you have a few options - specify the schema on the @Table annotation, use the openjpa.jdbc.Schema property, or depending on the driver and platform, specify a different default schema on the connection URL[2]. Or, if possible, define the table in DBSSCHEMA. [1] http://openjpa.apache.org/builds/latest/docs/manual/ref_guide_schema_def.html [2] http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.apdv.java.doc/doc/cjvcfgpr.htm -Jeremy On Tue, Jun 7, 2011 at 6:45 PM, Pinaki Poddar ppod...@apache.org wrote: Right now I do not have a computing environment to give you a definite answer. But if you do not mind, please try passing a Long (not long). Why did you think that the application connects to multiple DBs could be relevant in this context? Given rather straightforward nature of the use case, I am thinking whether something else is causing the reported failure. - Pinaki -- View this message in context: http://openjpa.208410.n2.nabble.com/may-be-OpenJPA-limitation-tp6450246p6451867.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: The name A is not a recognized entity or identifier. Perhaps you meant ....
Another thing to verify is whether you have ProfileAuditDetail listed as a class in your persistence.xml. I've forgotten that simple detail or mistyped a package or class name a time or ten. -Jeremy On Tue, Jun 7, 2011 at 10:34 AM, infinity2heaven infinity2hea...@gmail.com wrote: openjpa build time enhancement http://openjpa.208410.n2.nabble.com/openjpa-build-time-enhance-using-maven-plugin-DOESN-T-WORK-td6446547.html#a6450082 does'nt work as specified and I'm aware that RuntimeEnhancement http://openjpa.208410.n2.nabble.com/Externalizer-in-1-0-1-does-not-work-on-persist-td216632.html#a6436083 doesn't work all the time either. But right now, we need to get a build for our deployment environment so I've temporarily enabled Runtime enhancement. It seems to work most of the time. Here's the complete stacktrace. openjpa-1.2.2-r422266:898935 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter DELETE FROM ProfileAuditDetail. Error message: The name ProfileAuditDetail is not a recognized entity or identifier. Perhaps you meant ProfileAudit, which is a close match. Known entity names: [xxx, yyy, ProfileAudit, ErrorCode, ProfileLoadError] at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:118) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:177) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:150) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:225) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:195) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:188) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.access$600(JPQLExpressionBuilder.java:69) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.populate(JPQLExpressionBuilder.java:1756) at org.apache.openjpa.kernel.jpql.JPQLParser.populate(JPQLParser.java:56) at org.apache.openjpa.kernel.ExpressionStoreQuery.populateFromCompilation(ExpressionStoreQuery.java:153) at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:658) at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:639) at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:605) at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:667) at org.apache.openjpa.kernel.QueryImpl.getOperation(QueryImpl.java:1492) at org.apache.openjpa.kernel.DelegatingQuery.getOperation(DelegatingQuery.java:123) at org.apache.openjpa.persistence.QueryImpl.executeUpdate(QueryImpl.java:325) at xxx.tcms.profile.dao.JPAProfileDao.deleteAll(JPAProfileDao.java:204) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:59) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:39) at java.lang.reflect.Method.invoke(Method.java:612) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy19.deleteAll(Unknown Source) at xxx.profile.service.ProfileServiceImpl.deleteProfileData(ProfileServiceImpl.java:429) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:59) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:39) at java.lang.reflect.Method.invoke(Method.java:612) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at
Re: JEE 5: Bean Validation API and JPA 2.0
Hi Chintan, The WebSphere Version 8 Beta documentation in the IBM infocenter has a good writeup on migration considerations for bean validation[1] when moving to a full EE6 app server. The short answer is that you'll no longer need to set a system property to point to the validation API and you'll no longer have to include a bean validation provider in your application or shared library. The application server will provide both the API classes and a default provider. The easiest way to verify your application continues to work the full EE 6 environment may be to download the V8 beta[2] and give it a try. -Jeremy [1] http://publib.boulder.ibm.com/infocenter/wasinfo/beta/topic/com.ibm.websphere.nd.doc/info/ae/ae/cdat_beanvaljpamigration.html [2] https://www14.software.ibm.com/iwm/web/cc/earlyprograms/websphere/wsasoa/index.shtml On Wed, May 25, 2011 at 3:53 PM, chintan4181 chintan4...@gmail.com wrote: Thanks Kevin, Jeremy. One more question. If i use OSGi/JPA 2.0 feature pack with Apache Bean Validation in Websphere 7.0 and in future if i migrate to JEE 6, are there any migration issue in terms of Bean Validation usage? Chintan -- View this message in context: http://openjpa.208410.n2.nabble.com/JEE-5-Bean-Validation-API-and-JPA-2-0-tp6403780p6404442.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JEE 5: Bean Validation API and JPA 2.0
Chintan, While Bean Validation is one of the Java EE 6 specifications, each provider will have its own Java SE version requirements. For example, Apache BVAL[1] can be used with Java SE 1.5. Some/most Java EE 5 application servers will most likely allow you to use a Java 1.5 compatible Bean Validation provider using JSE-style APIs. You'll lack EE6 features like JNDI lookup of validation factories and integration with other technologies such as JPA, JSF, and JCA. An exception is that the WebSphere Version 7.0 Feature Pack for OSGi/JPA 2.0 provides a mechanism to support bean validation integration with JPA 2.0 in an EE 5 + JPA 2.0 environment. If you are interested, I wrote up a blog post several months ago that provides a step-by-step procedure to do the enablement.[2] It is a bit out of date as far as versions go, though. You'll want to use the new 0.3 version of BVAL instead 0.1. -Jeremy [1] http://incubator.apache.org/bval/cwiki/index.html [2]http://webspherepersistence.blogspot.com/2010/07/using-bean-validation-with-osgijpa-20.html On Wed, May 25, 2011 at 12:53 PM, chintan4181 chintan4...@gmail.com wrote: Hi, We are running on JEE 5 stack and using JPA 2.0 for persistence layer. In our application architecture, we have following layers Service, BC(Business Component) and DAC(Data Access component). As per secure coding guideliens, each layer should be responsible of doing validation. considering that approach, Our business rule validation will be done in BC layer. and Data type, constraint will be done in DAC layer. For data validation at DAC layer, i can think of Bean Validation API (JSR 303) however it's part of JEE 6. can i use in JEE 5 ? Thanks Chintan -- View this message in context: http://openjpa.208410.n2.nabble.com/JEE-5-Bean-Validation-API-and-JPA-2-0-tp6403780p6403780.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Issues with GeneratedValue and SequenceGenerator
I agree. The OpenJPA documentation is confusing/contradictory. 1.2. Final Entity classes may not be final. No method of an entity class can be final. *Note* OpenJPA supports final classes and final methods. I wonder if the distinction is Entity vs. a plain old class? Either way, I think the note should be removed from the documentation. -Jeremy On Mon, Apr 11, 2011 at 2:35 PM, Rick Curtis curti...@gmail.com wrote: 1.2. Final Entity classes may not be final. No method of an entity class can be final. Note OpenJPA supports final classes and final methods. Confusing? Perhaps. It seems pretty clear that we don't support final Entities or final Entity methods. I'm not sure what the Note is referring to though. If you want, open a JIRA and I can remove that Note. It's more confusing than anything. Thanks, Rick On Mon, Apr 11, 2011 at 2:23 PM, realdepp thepsy...@freenet.de wrote: I'm not sure about that - the final modifier seems to be the cause for the problem. The JPA spec sais: Entity classes may not be final. No method of an entity class can be final. BUT the OpenJPA docs say: OpenJPA supports final classes and final methods. http://openjpa.apache.org/builds/2.1.0/apache-openjpa-2.1.0/docs/manual/jpa_overview_pc.html#jpa_overview_pc_final So this is either an implementation bug or a documentation bug
Re: @PersistenceContext is null
Hi Chintan, Which application server are you using? Regardless of the server type, I'd start by checking the server logs. They may show some sort of injection failure due to a data source or some other configuration problem. -Jeremy On Thu, Apr 7, 2011 at 6:42 PM, chintan4181 chintan4...@gmail.com wrote: Hi, I am trying to access JPA entities using Stateless EJBs, Earlier i have one Stateless EJB which was injecting PersistenceContext using annotation. It is working fine. Since Stateless EJB is haveing data access code, I have introduced DAO mechanism to separate data access from EJB. For that I have added below classes GenericeDAO: public interface GenericDAOlt;E,K extends Serializablegt; { void persist(E entity); void remove(E entity); E findById(K id); } ApplicationDAO: defined DAO as Stateless EJB @Stateless public class ApplicationDAOlt;E,K extends Serializablegt; implements GenericDAOlt;E,Kgt; { protected Class entityClass; @PersistenceContext(name = MIApplicationJPA, unitName = MIApplicationJPA) public EntityManager entityManager; @SuppressWarnings(unchecked) public ApplicationDAO() { ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[1]; } public void persist(E entity) { entityManager.persist(entity); } public void remove(E entity){ entityManager.remove(entity); } public E findById(K id) { E entity; entity = (E) entityManager.find(entityClass, id); return entity; } } CertDAOImpl: public class CertDAOImpl extends ApplicationDAOlt;Cert,Integergt;{ @Override public Certificate findByCertNumber(String certId) throws Exception { Certificate cert = (Certificate) entityManager.createNamedQuery(findByCert_Number) .setParameter(Cert_Number,certId) .getSingleResult(); return cert; } } However when i access entityManager from CertDAOImpl. entitymanage is coming as null. Even though it is in same EJB jar. can anybody tell me what could be the issue? Thanks Chintan -- View this message in context: http://openjpa.208410.n2.nabble.com/PersistenceContext-is-null-tp6251959p6251959.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Issues with GeneratedValue and SequenceGenerator
IIRC, the identity value should be getting returned by the JDBC driver as a result of the insert. OpenJPA then populates the entity with that value. What version of MySQL DB and JDBC driver are you using? -Jeremy On Wed, Apr 6, 2011 at 10:16 AM, realdepp thepsy...@freenet.de wrote: Thanks, but that didn't solve the problem. EntityManager.refresh() has no effect, like expected. I'm not enhancing with an eclipse tool, I'm calling the java program via ant: (I also tried the ant task, doesn't seem to make a difference) However, I get a bunch of warning messages: (I thought ignoring would be ok since I get no errors like class not enhanced) openjpa.MetaData - Meta class x.y.z.TimeSettings_ for entity class x.y.z.TimeSettings can not be registered with following exception java.security.PrivilegedActionException: java.lang.ClassNotFoundException: x.y.z.TimeSettings_ I haven't checked yet if the warning message appears for every class, but most of them produce it. But I have to correct myself: initialValue AND allocationSize are ignored. The IDs start with 1 and they get increased by 50 (default value?) with every new persisted entity. (And, of course, I don't see any way to get the ids into the application) Is that probably related to MySQL? -- View this message in context: http://openjpa.208410.n2.nabble.com/Issues-with-GeneratedValue-and-SequenceGenerator-tp6244055p6246413.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OneToMany cascading persist and sequence ID generator
No problem. I'm happy to hear that you are up and running. -Jeremy On Wed, Mar 2, 2011 at 11:26 PM, Phill ph...@bicispace.com wrote: Many thanks Jeremy, to my embarrassment I've discovered that lead wasn't getting set properly on the other end of the association. I jumped to the wrong conclusion about the id generation not working... sorry for taking up your time with this. On 02/mar/2011, at 21.42, Jeremy Bauer wrote: Hi Phill, I tried a similar configuration, but was unable to reproduce the failure. Since cascade is defined on the Lead-side of the relationship, I'm assuming that you are persisting the Lead entity, right? I'm also assuming that you've set all bi-directional references in your code. ie answer.setLead(lead), lead.setAnswers(answers). If both of those assumptions are correct, the next step would be to provide an OpenJPA trace using: property name=openjpa.Log value=DefaultLevel=TRACE/ please enable parameter value trace as well using: property name=openjpa.ConnectionFactoryProperties value=PrintParameters=true/ That may help us spot the problem. Or, if possible, please provide a simple test that can be used to reproduce the problem. -Jeremy On Wed, Mar 2, 2011 at 11:08 AM, Phill ph...@bicispace.com wrote: Yes it also uses a sequence generator. SurveyAnswer.java @SequenceGenerator(name = Survey_Result_Id_Gen, sequenceName = survey_result_seq, allocationSize = 10) @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Survey_Result_Id_Gen) @Column(name = result_id) protected long id; On 02/mar/2011, at 17.24, Jeremy Bauer wrote: Thanks, Phill. Sorry, I forgot to ask - does SurveyAnswer also use the same id generation strategy as Lead? In the meantime, I'll begin trying to reproduce the failure you are seeing. -Jeremy On Wed, Mar 2, 2011 at 9:26 AM, Phill ph...@bicispace.com wrote: OpenJPA 2.1.0 and PostgreSQL 9 I have separate DDL. Phill On 02/mar/2011, at 16.22, Jeremy Bauer wrote: Hi Phill, What database and version of OpenJPA are you using? Also, does OpenJPA generate the tables or do you have separate DDL? -Jeremy
Re: OneToMany cascading persist and sequence ID generator
Hi Phill, What database and version of OpenJPA are you using? Also, does OpenJPA generate the tables or do you have separate DDL? -Jeremy On Wed, Mar 2, 2011 at 8:49 AM, Phill ph...@bicispace.com wrote: I'm having some problems with a cascading @OneToMany persist, my class with the @ManyToOne has a sequence id generator and this Id is not getting populated in the cascaded entity. Here are the relevant snippets: Lead.java -- @SequenceGenerator(name = Lead_Id_Gen, sequenceName = lead_id_seq) @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Lead_Id_Gen) @Column(name = lead_id) private Long id; @OneToMany(mappedBy = lead, cascade = CascadeType.ALL) private ListSurveyAnswer answers = new ArrayListSurveyAnswer(); SurveyAnswer.java -- @ManyToOne @JoinColumn(name = lead_id) protected Lead lead; org.apache.openjpa.lib.jdbc.ReportingSQLException: ERROR: null value in column lead_id violates not-null constraint {prepstmnt 26568269 INSERT INTO survey_result (result_id, result_boolean, result_number, result_int, result_text, answer_type, lead_id, survey_id, question_id, single_choice) Should this not happen automatically or am I missing something? Thanks Phill
Re: same jpa query generates different SQLs
Hi Marc, I'm wondering if this isn't caused by an inconsistent parameter type mapping as a result of using the QuerySQLCache. I saw a similar issue a few weeks ago, but it was oddly specific to DB2 on zOS. Please try: property name=openjpa.jdbc.QuerySQLCache value=false/ -Jeremy On Wed, Mar 2, 2011 at 9:43 AM, Marc Logemann l...@logemann.org wrote: Hi, i am totally astonished: I am using this query: public ListOrder findByDate(Date date) { TypedQueryOrder query = getEntityManager(). createQuery(select o FROM Order o where o.createdYmd = ?1 order by o.id, Order.class); query.setParameter(1, date, TemporalType.DATE); return query.getResultList(); } This query is called by a service class which is scheduled ever 30 seconds. See the caller: // get yesterdays Date Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.DATE, -1); Date yesterday = calendar.getTime(); ListOrder list = orderDao.findByDate(yesterday); Now, on the second run, the query parameter is of type timestamp with full time specified, giving me 0 records of course. First query returns records because there TemporalType seems to work. See log. FIRST RUN - [DEBUG myScheduler-3 16:36:30] | t 941878577, conn 650647154 executing prepstmnt 1488869003 SELECT t0.oid, t0.`_version`, t1.oid, t1.`_version`, t1.cleared, t1.id, t1.lastused, t2.oid, t2.`_version`, t2.created, t2.createdymd, t2.custnr, t2.greenoption, t2.ordernr, t2.invaddress_oid, t2.iscardowner, t2.cost, t2.currency, t2.pricing, t2.paymenttype, t2.printed, t2.printedby, t2.totalprice, t1.boxtype, t0.created, t0.createdymd, t0.custnr, t3.oid, t3.jpatype, t3.`_version`, t3.addresstype, t3.city, t3.company, t3.country, t3.department, t3.email, t3.firstname, t3.gender, t3.lastname, t3.middlename, t3.phone, t3.zip, t3.postofficebox, t3.street, t3.housenr, t3.title, t3.deliverymode, t0.greenoption, t0.ordernr, t4.oid, t4.jpatype, t4.`_version`, t4.addresstype, t4.city, t4.company, t4.country, t4.department, t4.email, t4.firstname, t4.gender, t4.lastname, t4.middlename, t4.phone, t4.zip, t4.postofficebox, t4.street, t4.housenr, t4.title, t4.deliverymode, t4.order_oid, t0.iscardowner, t0.cost, t0.currency, t0.pricing, t0.paymenttype, t0.printed, t0.printedby, t0.totalprice FROM orders t0 LEFT OUTER JOIN boxes t1 ON t0.box_oid = t1.oid LEFT OUTER JOIN address t3 ON t0.oid = t3.order_oid LEFT OUTER JOIN address t4 ON t0.invaddress_oid = t4.oid LEFT OUTER JOIN orders t2 ON t1.oid = t2.box_oid WHERE (t0.createdymd = ?) AND (t3.jpatype IS NULL OR t3.jpatype IN (?)) ORDER BY t0.ordernr ASC [params=(Date) 2011-03-01, (int) 2] SECOND RUN - [DEBUG myScheduler-2 16:37:00] | t 1835085919, conn 1503676955 executing prepstmnt 154018541 SELECT t0.oid, t0.`_version`, t1.oid, t1.`_version`, t1.cleared, t1.id, t1.lastused, t2.oid, t2.`_version`, t2.created, t2.createdymd, t2.custnr, t2.greenoption, t2.ordernr, t2.invaddress_oid, t2.iscardowner, t2.cost, t2.currency, t2.pricing, t2.paymenttype, t2.printed, t2.printedby, t2.totalprice, t1.boxtype, t0.created, t0.createdymd, t0.custnr, t3.oid, t3.jpatype, t3.`_version`, t3.addresstype, t3.city, t3.company, t3.country, t3.department, t3.email, t3.firstname, t3.gender, t3.lastname, t3.middlename, t3.phone, t3.zip, t3.postofficebox, t3.street, t3.housenr, t3.title, t3.deliverymode, t0.greenoption, t0.ordernr, t4.oid, t4.jpatype, t4.`_version`, t4.addresstype, t4.city, t4.company, t4.country, t4.department, t4.email, t4.firstname, t4.gender, t4.lastname, t4.middlename, t4.phone, t4.zip, t4.postofficebox, t4.street, t4.housenr, t4.title, t4.deliverymode, t4.order_oid, t0.iscardowner, t0.cost, t0.currency, t0.pricing, t0.paymenttype, t0.printed, t0.printedby, t0.totalprice FROM orders t0 LEFT OUTER JOIN boxes t1 ON t0.box_oid = t1.oid LEFT OUTER JOIN address t3 ON t0.oid = t3.order_oid LEFT OUTER JOIN address t4 ON t0.invaddress_oid = t4.oid LEFT OUTER JOIN orders t2 ON t1.oid = t2.box_oid WHERE (t0.createdymd = ?) AND (t3.jpatype IS NULL OR t3.jpatype IN (?)) ORDER BY t0.ordernr ASC [params=(Timestamp) 2011-03-01 16:37:00.001, (int) 2] I have completely no clue what to do now ;-) Thanks for input. --- regards Marc Logemann http://www.logemann.org http://www.logentis.de
Re: same jpa query generates different SQLs
Marc, I'm glad that worked for you. You could actually just exclude that query for the time being, that way you still get caching benefits for your other statements. To exclude the query you can either set the query hint via query.setHint(openjpa.hint.IgnorePreparedQuery, true) on the query or exclude it via persistence property: property name=openjpa.jdbc.QuerySQLCache value=true(excludes='select o FROM Order o where o.createdYmd = ?1 order by o.id')/ You can get more specifics on cache exclusion in this section of the OpenJPA manual[1]. That should get you by for the time being, but please open a JIRA for this problem so that it gets fixed. [1] http://openjpa.apache.org/builds/latest/docs/manual/ref_guide_cache_querysql.html -Jeremy On Wed, Mar 2, 2011 at 10:51 AM, Marc Logemann l...@logemann.org wrote: Hi Jeremy, thanks for your instant feedback. I directly tried your suggestion and now it works. So there is a bug in the cache implementation with regard to Type Mappings. And its not a DB2 thingy because i am using MySQL ;-) if you need more infos in the error case, i am willing to help if you want I would like to see this solved because disabling the cache means decreasing the performance somehow right? --- regards Marc Logemann http://www.logemann.org http://www.logentis.de Am 02.03.2011 um 17:31 schrieb Jeremy Bauer: Hi Marc, I'm wondering if this isn't caused by an inconsistent parameter type mapping as a result of using the QuerySQLCache. I saw a similar issue a few weeks ago, but it was oddly specific to DB2 on zOS. Please try: property name=openjpa.jdbc.QuerySQLCache value=false/ -Jeremy On Wed, Mar 2, 2011 at 9:43 AM, Marc Logemann l...@logemann.org wrote: Hi, i am totally astonished: I am using this query: public ListOrder findByDate(Date date) { TypedQueryOrder query = getEntityManager(). createQuery(select o FROM Order o where o.createdYmd = ?1 order by o.id, Order.class); query.setParameter(1, date, TemporalType.DATE); return query.getResultList(); } This query is called by a service class which is scheduled ever 30 seconds. See the caller: // get yesterdays Date Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.DATE, -1); Date yesterday = calendar.getTime(); ListOrder list = orderDao.findByDate(yesterday); Now, on the second run, the query parameter is of type timestamp with full time specified, giving me 0 records of course. First query returns records because there TemporalType seems to work. See log. FIRST RUN - [DEBUG myScheduler-3 16:36:30] | t 941878577, conn 650647154 executing prepstmnt 1488869003 SELECT t0.oid, t0.`_version`, t1.oid, t1.`_version`, t1.cleared, t1.id, t1.lastused, t2.oid, t2.`_version`, t2.created, t2.createdymd, t2.custnr, t2.greenoption, t2.ordernr, t2.invaddress_oid, t2.iscardowner, t2.cost, t2.currency, t2.pricing, t2.paymenttype, t2.printed, t2.printedby, t2.totalprice, t1.boxtype, t0.created, t0.createdymd, t0.custnr, t3.oid, t3.jpatype, t3.`_version`, t3.addresstype, t3.city, t3.company, t3.country, t3.department, t3.email, t3.firstname, t3.gender, t3.lastname, t3.middlename, t3.phone, t3.zip, t3.postofficebox, t3.street, t3.housenr, t3.title, t3.deliverymode, t0.greenoption, t0.ordernr, t4.oid, t4.jpatype, t4.`_version`, t4.addresstype, t4.city, t4.company, t4.country, t4.department, t4.email, t4.firstname, t4.gender, t4.lastname, t4.middlename, t4.phone, t4.zip, t4.postofficebox, t4.street, t4.housenr, t4.title, t4.deliverymode, t4.order_oid, t0.iscardowner, t0.cost, t0.currency, t0.pricing, t0.paymenttype, t0.printed, t0.printedby, t0.totalprice FROM orders t0 LEFT OUTER JOIN boxes t1 ON t0.box_oid = t1.oid LEFT OUTER JOIN address t3 ON t0.oid = t3.order_oid LEFT OUTER JOIN address t4 ON t0.invaddress_oid = t4.oid LEFT OUTER JOIN orders t2 ON t1.oid = t2.box_oid WHERE (t0.createdymd = ?) AND (t3.jpatype IS NULL OR t3.jpatype IN (?)) ORDER BY t0.ordernr ASC [params=(Date) 2011-03-01, (int) 2] SECOND RUN - [DEBUG myScheduler-2 16:37:00] | t 1835085919, conn 1503676955 executing prepstmnt 154018541 SELECT t0.oid, t0.`_version`, t1.oid, t1.`_version`, t1.cleared, t1.id, t1.lastused, t2.oid, t2.`_version`, t2.created, t2.createdymd, t2.custnr, t2.greenoption, t2.ordernr, t2.invaddress_oid, t2.iscardowner, t2.cost, t2.currency, t2.pricing, t2.paymenttype, t2.printed, t2.printedby, t2.totalprice, t1.boxtype, t0.created, t0.createdymd, t0.custnr, t3.oid, t3.jpatype, t3.`_version`, t3.addresstype, t3.city, t3.company, t3.country, t3.department, t3.email, t3.firstname, t3.gender, t3.lastname, t3.middlename, t3.phone, t3.zip, t3.postofficebox, t3.street, t3.housenr, t3.title, t3.deliverymode, t0.greenoption, t0
Re: correct use of GenerationType.TABLE
Hi Henno, Whether the table generator will be a performance bottleneck will depend on your application. If it is insert/persist heavy and/or has many clients simultaneously persisting new entities, the table generator could become a bottleneck. As you mentioned, increasing the allocation size will reduce trips to the database and contention on the table. Using a separate table via a custom table generator can help remove contention on any single table. A custom table generator also provides the ability to reuse a single table by using a different PK value for each generated id. (ie. each generator has its own table row) That can provide better performance and help reduce the number of DB tables you need to manage. Also, if you'd like to continue using the system/default table generator you can change the default allocation size by setting this persistence property: property name=openjpa.Sequence value=table(Increment=1000)/ We have existing data that is migrated to the database schema generated by OpenJPA. Am I correct that after migration I should initialize the SEQUENCE_VALUE to the maximum over all entity id's? Yes. Initializing SEQUENCE_VALUE to a value larger than your current maximum entity ID should do the trick. hth, -Jeremy On Wed, Feb 23, 2011 at 3:37 AM, Henno Vermeulen he...@huizemolenaar.nlwrote: Hello, All of our entities inherit from AbstractEntity which is a MappedSuperclass that defines an automatically generated identity column of type Long. Because of issues we are having with GenerationType.IDENTITY ( https://issues.apache.org/jira/browse/OPENJPA-1949) I would like to switch to GenerationType.TABLE. When I annotate the id column in our mapped super class as @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; OpenJPA creates a sequence table with only one row (with ID 0). This means that all our entities will share this sequence to generate new id's. This is not a problem for our application, but I was wondering if there are any performance issues with this. Would this be solved by defining my own tablegenerator with an allocationSize of something like 1000? We have existing data that is migrated to the database schema generated by OpenJPA. Am I correct that after migration I should initialize the SEQUENCE_VALUE to the maximum over all entity id's? (I guess it can also be solved by pulling up the id column so that all our entities have to define it's own id and use the same generator table. This gives a lot of unnecessary code duplication while our design choice that all of our entities have a synthetic id works perfectly fine for us. We use this in many places with our notification, caching and application level lock system.) Henno
Re: How to get generated keys without requerying the database?
Hi, Based on the code snippets you've provided, it looks like you my just either need to call em.flush() to force the DB update or commit the transaction before getting the recId from the dto. If that doesn't help, repost and I'll dig a little deeper. OpenJPA refreshes primary key identity fields after a flush or commit. I think it will/should do the same for non-PK generated fields. hth, -Jeremy On Mon, Jan 24, 2011 at 8:33 PM, robsinner robsin...@yahoo.com wrote: I have an Entity with a non primary key identity column. This entity Part.java has the following fields among others @EmbeddedId private PartPK pk; @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=REC_ID) private Integer recId; Note the EmbeddedId does not contain the Generated Value , the PartPk is made up of two strings, one for company and one for part number. So the Entity has a primary key which is a business composite key. This table also has a column in DB2 which is a IDENTITY column which is not part of the primary key. This identity column which is not part of the primary key is called REC_ID. After insert I would like the recId to be populated onto the entity however it is not. In JDBC this is usually accomplished via statement.getGeneratedKeys after the insert statements has been run. For example in a straight JDBC Data Access Object this would be accomplished after the insert statement by // retrieve values from auto-increment columns rs = stmt.getGeneratedKeys(); if (rs != null rs.next()) { dto.setRecId( new Integer( rs.getInt(1) ) ); } However when I run a junit test using a simple JPA data access object the recId column is null after insert. public void testInsert() { log.info(insert); log.info(part=+part); manager = getManager(); pk.setIncomp(comp); pk.setInpart(part); dto.setPk(pk); log.info(dto); manager.insert(dto); log.info(recId=+dto.getRecId()); assertFalse(recId is null after insert should not be, dto.getRecId() == null); //fails here } The manager class is wrapping this data access object code public PK insert(DTO dto) throws Exception { EntityManager em = getEntityManager(); em.persist(dto); return dto.getPk(); } How do I specify the mapping in the entity with a non primary key identity column such that after an insert the non primary key identity column is populated onto the entity. Among other things I am using Db2 with spring and openjpa 2.2.0. I believe this has something to do with getGeneratedKeys and how I'm doing the mapping in the entity and possibly DB2 with openjpa. The table are legacy and are not easily modifiable to accomplish this. Im trying to avoid having to relook up the non primary key with a seperate query by the primary key after the insert. Thank you in advance for your assistance. I searched in the nabble users list and could not find anything related. If you need more detailed information I can post more. I believe this is a simple configuration done incorrectly at the entity level. Thank you in advance for any assistance you provide. -- View this message in context: http://openjpa.208410.n2.nabble.com/How-to-get-generated-keys-without-requerying-the-database-tp5957346p5957346.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JPAB results
It looks like benchmark is configured to use openjpa-all-2.0.0 so it wouldn't be using auto-enablement of DBCP. The auto-enablement wasn't available until recently in openjpa-all-2.1.0-SNAPSHOT. I scanned some of the benchmark config files and they are using direct-to-DB jdbc URL's, so nor does it look like pooling is explicitly enabled. Like so many other JSE-based benchmarks, I think we'd see more favorable OpenJPA results with connection pooling. -Jeremy On Tue, Nov 2, 2010 at 9:15 AM, Rick Curtis curti...@gmail.com wrote: I also took a quick look and it appears that this is another out of the box test. Caching would probably bridge the gap between us and Hibernate... also I'm not sure they are running with the auto connection pooling stuff Donald has been working on. Thanks, Rick On Tue, Nov 2, 2010 at 8:49 AM, Kevin Sutter kwsut...@gmail.com wrote: Although this benchmark is obviously biased, it's still good to be reminded of potential pitfalls and/or inconsistencies. For example, I took a quick look at one set of results and it seems to indicate a repeating issue with obtaining a primary key sequence from the OpenJPA sequence table. This could be a problem with the application, or it could be a problem with the OpenJPA processing. Digging in a bit on these type of issues would probably be worthwhile. But, spending a lot of time attempting to match the results of ObjectDB is probably not that interesting... Kevin On Tue, Nov 2, 2010 at 7:58 AM, Georgi Naplatanov go...@oles.biz wrote: Hi gkorland. Do not trust on this tests. It is better to make your own test and then decide which implementation is good for you. My testing indicates that OpenJPA (with or without cache) is faster than Hibernate on mostly write and less read operations. On read operation probably all JPA implementation are very close due the cache. Best regards Georgi gkorland wrote: Did anyone review the JPAB (http://www.jpab.org/) results? It seems like all the other JPA guys are running faster and even better...
Re: Problems with trunk build
Hi Georgi, A few of us were having some build issues this morning due to a dependency update. The change was backed out and trunk is now building again. The error you've posted doesn't look the same, but I'm doing an install vs. package. I'd try doing a clean before package with the very latest code. You may have better luck. -Jeremy On Mon, Nov 1, 2010 at 12:47 PM, Georgi Naplatanov go...@oles.biz wrote: Hi all. I have the following problems when i try to build OpenJPA from trunk: 1. After mvn compile execution the following error occurs : [ERROR] BUILD ERROR [INFO] [INFO] An Ant BuildException has occured: The following error occurred while executing this line: /home/gosho/eclipse_workplaces/openjpa/trunk/openjpa-examples/openbooks/build.xml:116: *** Error: The directory for OpenJPA libraries can not be located at /home/gosho/.m2/repository/org/apache/openjpa/openjpa-all/2.1.0-SNAPSHOT. Make sure openjpa.lib property value is correct in build.properties file. 2. After mvn package -DskipTests execution - the same error as above 3. If i change HSQLDictionary.java file for example, the compiled file is in trunk/openjpa-jdbc/target/classes/org/apache/openjpa/jdbc/sql directory which is correct, but in the trunk/openjpa-project/target/site/downloads/apache-openjpa-2.1.0-SNAPSHOT-binary.zip is unmodified file. What is wrong ? Best regards Georgi
Re: Migrate EntityBean NamedSequenceTable to OpenJPA
C, JPA provides similar, but not exact capabilities through table generators. The main difference in JPA is that a table generator can be used to generate IDs for multiple entities from a single table while the approach you've provided appears to be capable of only managing a single ID per table. JPA table generators are able to manage multiple id's by having a sequence name and sequence value column in the table. A TableGenerator keys off the value defined by pkColumnValue (default is DEFAULT if not specified) in column pkColumnName to generate a new block of keys. Here is a example of defining a TableGenerator and using within GeneratedValue for an entity. @Entity @Table(name=Entity_TBL) @TableGenerator(name=WebCartSequence, schema=dbo, table=WebCartSequence, pkColumnName=Sequence_Name, valueColumnName=Sequence, pkColumnValue=MyEntityID) public class MyEntity { @Id @GeneratedValue(strategy=GenerationType.TABLE, generator=WebCartSequence) private int id; ... } Again, this will not work with the same table definition as you currently use. Based on the names in the example, you could add a column named Sequence_Name to your existing table and set its value to MyEntityID and that may do the trick. -Jeremy On Wed, Oct 13, 2010 at 12:41 PM, corstad cully.ors...@gmail.com wrote: Greetings: I am attempting to migrate Entity Beans to OpenJPA. Each Entity Bean represents a single table in the DB. The Entity Beans are deployed on WebLogic 10.0 using WLS 8 version of the deployment descriptors. (I just work here). Each table has a corresponding sequence table with a single column named Sequence. The current DD for these use the following XML within the weblogic-cmp-jar.xml file for each weblogic-rdbms-bean defined. automatic-key-generation generator-typeNAMED_SEQUENCE_TABLE/generator-type generator-nameWebCartSequence/generator-name key-cache-size1/key-cache-size /automatic-key-generation The SQL used to create the sequence table is: CREATE TABLE [dbo].[WebCartSequence]( [Sequence] [int] NOT NULL ) ON [PRIMARY] My question is what would the OpenJPA annotations look like to use this id generation strategy? Thanks, C. -- View this message in context: http://openjpa.208410.n2.nabble.com/Migrate-EntityBean-NamedSequenceTable-to-OpenJPA-tp5631958p5631958.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Re: @Externalizer not working during maven test phase
Heiko, Thanks for following up so quickly. I put together a quick test and wasn't able to produce the same result. I was just about to type up an email asking for more info. I'm glad to hear you were able to work around the issue with a simple change. I agree that having the exception surfaced from OpenJPA, if possible, would be more helpful. If you can supply a simple test to show the problem we could certainly look into propagating the exception. Filing a JIRA[1] would be the best route. That way, you can attach the test directly to the JIRA and keep and eye out for a fix. -Jeremy [1] https://issues.apache.org/jira/browse/OPENJPA On Wed, Sep 29, 2010 at 1:09 AM, it-media.k...@daimler.com wrote: Hello Jeremy, thank you for your investigations. I might have come up with a reason for this problem. I tried to simply load the class TypeMapping during the maven integration test exactly before the openJPA test begun. It did not load, but an ExceptionInInitializer was thrown. Though openJPA was in its final decision right as the class was 'bad' cause it was not loadable. However, the really interesting thing is why in the maven test phase the static initializer failed and thus the class did not load. Within the static initializer we load an xml-file via Thread.currentThread().getContextClassLoader().getResourceAsStream( /TypeMapping.xml) As this seems to work well inside the application server, it does not work when maven's integration phase is running. The xml file is not found. Without the leading slash it works for both, the application server AND maven's integration phase. To summarize: 1) openJPA does not cause this the problem 2) the actual cause WHY the class is bad for meta data is hidden and leads to difficult-to-find problems. If the stack trace contained the ExceptionInInitializer-Exception, this mail would have never been written ;-) 3) Maybe providing the causing exception in future versions of openJPA (although I'm stuck at openJPA 1.0.4 right now) would be an improvement. Best regards, and thank you again for your short reply. Heiko techhu...@gmail.com schrieb am 28.09.2010 16:14:10: Hi Heiko, Odd problem, indeed. I'll setup a similar environment and let you know if I have any suggestions. Which version of maven are you using and which OS? -Jeremy On Tue, Sep 28, 2010 at 5:10 AM, Heiko Kopp it-media.k...@daimler.comwrote: Hello, I've encountered a problem when using openJPA inside mavens integration test phase. Alot of my entities respectively their members have been annotated with @Factory and @Externalizer to automatically convert database datatypes into schema relevent enumerations. An example for this is: @Entity @Table(name = PARTNER, schema = PART) public class Partner { @Column(name = I_SCHL_WERTBEZ) @Externalizer(TypeMapping.MARSHAL_SALUTATION_INDIVIDUAL) @Factory(TypeMapping.UNMARSHAL_SALUTATION_INDIVIDUAL) private SalutationIndividualEnum salutationIndividual; ... } The Externalizer- and Factory-Methods have been extracted into a separate class called 'TypeMapping'. In this class we additionally have the following string constants as used above: public static final String MARSHAL_SALUTATION_INDIVIDUAL = com.mbbank.partner.pas.common.system.typemapping.TypeMapping. marshalSalutationIndividual; public static final String UNMARSHAL_SALUTATION_INDIVIDUAL = com.mbbank.partner.pas.common.system.typemapping.TypeMapping. unmarshalSalutationIndividual; These strings referr to the actuall methods. The TypeMapping-class is located in a different package than the entity class. And this seems to be a problem during test test phase in maven. While the code works perfectly in the application server, it fails in the maven test phase with the following exception: openjpa-1.0.4-SNAPSHOT-r420667:809016 fatal user error org.apache.openjpa.persistence.ArgumentException: Der Klassenname com.mbbank.partner.pas.common.system.typemapping.TypeMapping, der in der Metadatenerweiterung im Feld com.mbbank.partner.pas.common.system.database.model.Person. salutationIndividual verwendet wird, ist nicht gültig. at org.apache.openjpa.meta.JavaTypes.classForName(JavaTypes.java:227) at org.apache.openjpa.meta.JavaTypes.classForName(JavaTypes.java:194) at org.apache.openjpa.meta.JavaTypes.classForName(JavaTypes.java:185) at org.apache.openjpa.meta.FieldMetaData.findMethod(FieldMetaData.java:1533) at org.apache.openjpa.meta.FieldMetaData. getExternalizerMethod(FieldMetaData.java:1465) at org.apache.openjpa.meta.FieldMetaData.resolve(FieldMetaData.java:1640) at org.apache.openjpa.jdbc.meta.FieldMapping.resolve(FieldMapping.java:400) at
Re: @Externalizer not working during maven test phase
Hi Heiko, Odd problem, indeed. I'll setup a similar environment and let you know if I have any suggestions. Which version of maven are you using and which OS? -Jeremy On Tue, Sep 28, 2010 at 5:10 AM, Heiko Kopp it-media.k...@daimler.comwrote: Hello, I've encountered a problem when using openJPA inside mavens integration test phase. Alot of my entities respectively their members have been annotated with @Factory and @Externalizer to automatically convert database datatypes into schema relevent enumerations. An example for this is: @Entity @Table(name = PARTNER, schema = PART) public class Partner { @Column(name = I_SCHL_WERTBEZ) @Externalizer(TypeMapping.MARSHAL_SALUTATION_INDIVIDUAL) @Factory(TypeMapping.UNMARSHAL_SALUTATION_INDIVIDUAL) private SalutationIndividualEnum salutationIndividual; ... } The Externalizer- and Factory-Methods have been extracted into a separate class called 'TypeMapping'. In this class we additionally have the following string constants as used above: public static final String MARSHAL_SALUTATION_INDIVIDUAL = com.mbbank.partner.pas.common.system.typemapping.TypeMapping.marshalSalutationIndividual; public static final String UNMARSHAL_SALUTATION_INDIVIDUAL = com.mbbank.partner.pas.common.system.typemapping.TypeMapping.unmarshalSalutationIndividual; These strings referr to the actuall methods. The TypeMapping-class is located in a different package than the entity class. And this seems to be a problem during test test phase in maven. While the code works perfectly in the application server, it fails in the maven test phase with the following exception: openjpa-1.0.4-SNAPSHOT-r420667:809016 fatal user error org.apache.openjpa.persistence.ArgumentException: Der Klassenname com.mbbank.partner.pas.common.system.typemapping.TypeMapping, der in der Metadatenerweiterung im Feld com.mbbank.partner.pas.common.system.database.model.Person.salutationIndividual verwendet wird, ist nicht gültig. at org.apache.openjpa.meta.JavaTypes.classForName(JavaTypes.java:227) at org.apache.openjpa.meta.JavaTypes.classForName(JavaTypes.java:194) at org.apache.openjpa.meta.JavaTypes.classForName(JavaTypes.java:185) at org.apache.openjpa.meta.FieldMetaData.findMethod(FieldMetaData.java:1533) at org.apache.openjpa.meta.FieldMetaData.getExternalizerMethod(FieldMetaData.java:1465) at org.apache.openjpa.meta.FieldMetaData.resolve(FieldMetaData.java:1640) at org.apache.openjpa.jdbc.meta.FieldMapping.resolve(FieldMapping.java:400) at org.apache.openjpa.meta.ClassMetaData.resolveMeta(ClassMetaData.java:1688) at org.apache.openjpa.meta.ClassMetaData.resolve(ClassMetaData.java:1623) at org.apache.openjpa.meta.MetaDataRepository.processBuffer(MetaDataRepository.java:675) at org.apache.openjpa.meta.MetaDataRepository.resolveMeta(MetaDataRepository.java:574) at org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:499) at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:301) at org.apache.openjpa.kernel.BrokerImpl.newObjectId(BrokerImpl.java:1060) at org.apache.openjpa.kernel.DelegatingBroker.newObjectId(DelegatingBroker.java:252) at org.apache.openjpa.persistence.EntityManagerImpl.find(EntityManagerImpl.java:347) The string is localized into German, the original one is referred to as 'bad-class'. It's English representation is: bad-class: The class name {0} used in a metadata extension on field {1} is not valid. As both class files are present in the same module and even during the test phase, I've actually no clue on how to fix this issue. It can be fixed, when I put the static methods in the same package/class as the annotated field, but that is no solutation for us as it will duplicate a lot of code. Has anyone an idea why this appends and what can be done to prevent it? Thank you very much. As seen in the stack trace above, I'm using openJPA 1.0.4-something, which is part of the Websphere Application Server 6.1.0.29. Best regards, Heiko -- View this message in context: http://openjpa.208410.n2.nabble.com/Externalizer-not-working-during-maven-test-phase-tp5578748p5578748.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: DataCache on Class with a collection of DataCache off - n+1 select
Hi Marc, If you are using OpenJPA 1.x, specifying @org.apache.openjpa.persistence.DataCache(enabled=false) annotation on your inventory entities will inform OpenJPA that these entities should not be cached. If you are using OpenJPA 2.x, you have a few more options. You can continue to use the OpenJPA specific @DataCache annotation or use the JPA 2.0 standard @javax.persistence.Cacheable(false) annotation to prevent inventory entities from being cached. At an operation level, you can specify the property javax.persistence.cache.storeMode with value of javax.persistence.CacheStoreMode BYPASS on the finder or query to indicate not to cache the result. In addition, you could consider using LAZY fetch to not return the inventory relation. If that is too stringent, OpenJPA provides configurable fetch groups[1] which let your further tune what should/should not be returned in the query result. hth, Jeremy [1] http://openjpa.apache.org/builds/latest/manual/ref_guide_fetch.html On Mon, Sep 20, 2010 at 11:00 AM, killbulle marco.go...@gmail.com wrote: Hi , we encounters a recently a little performance problem A class product(cached) have a map off inventory (not Cached) when we retrieve the product in a new Entitymanager it generate a n+1 select with a find all method. Is there a way to not cache the collection stub (1 - inventory...) ? Regards Marc -- View this message in context: http://openjpa.208410.n2.nabble.com/DataCache-on-Class-with-a-collection-of-DataCache-off-n-1-select-tp5551060p5551060.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Need id to set in VO .
Hi Himadri, One option is to add a PostPersist lifecycle method to your entity class. The id is guaranteed to be available during this callback. During the lifecycle method you can set the id on your value object. The simplest (but not pretty) way to do that might be to store a transient reference to the value object within the entity. Note: make sure to return that same ref from your EJB method. PostPersist will fire after commit, modifying the id of the value object en route. For example: @Entity public class MyEntity { transient public MyValue _value; ... @PostPersist public void postPersist() { _value.id = getId(); } } hth, -Jeremy On Mon, Aug 30, 2010 at 11:44 PM, Himadri hima_...@yahoo.co.in wrote: Hi, Am using EJB3.0 Entity on WL 10.3 . The application is designed in ValueObject model i.e Entities are not directly passed to client but converted into value objects and then sent to client. I cannot change this design now. Value object also has primary key (id) column . My requirement is to create an entity and send VO back with id of newly created entity set. Now I understand , id is not generated untill the entity is inserted into database.. At the end of method when i convert Entity to VO , I donot get the primay key as the transaction is not committed yet. So to overcome this problem , I have user em.flush() ... and then I could get the key.. I understand its a bad practice to use flush .. but can anyone suggest how else can I get the system generated primary key at the end of method and set it back in VO ? Thanks Himadri -- View this message in context: http://openjpa.208410.n2.nabble.com/Need-id-to-set-in-VO-tp5481138p5481138.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: [VOTE] Apache OpenJPA 2.0.1 release candidate
+1 Thanks, Donald! -Jeremy On Thu, Aug 26, 2010 at 10:55 AM, Donald Woods dwo...@apache.org wrote: I've staged a release candidate for OpenJPA 2.0.1 with the following artifacts up for a vote: SVN source tag (r989424) made from the 2.0.x branch: https://svn.apache.org/repos/asf/openjpa/tags/2.0.1/ Source release: https://repository.apache.org/content/repositories/orgapacheopenjpa-147/org/apache/openjpa/apache-openjpa/2.0.1/apache-openjpa-2.0.1-source.zip Maven staging repo: https://repository.apache.org/content/repositories/orgapacheopenjpa-147/ Staging site for Downloads, Javadoc and User Guide: http://people.apache.org/~dwoods/openjpa/2.0.1/staging-site/http://people.apache.org/%7Edwoods/openjpa/2.0.1/staging-site/ PGP release keys (signed using D018E6B1): https://svn.apache.org/repos/asf/openjpa/KEYS For changes in this release, please visit the release notes: https://svn.apache.org/repos/asf/openjpa/tags/2.0.1/openjpa-project/CHANGES.txt Vote will be open for 72 hours. [ ] +1 approve [ ] +0 no opinion [ ] -1 disapprove (and reason why) Thanks, Donald
Re: Integrating existing customized Datasource and Connection objects in JPA
Hyndavi, Have you considered registering your own Datasource in JNDI during initialization (before OpenJPA needs it)? Provided your data source fully implements javax.jdbc.DataSource and hands out fully implemented and/or wrapped connections, theoretically OpenJPA should look up the data source by name and use it to create connections. If you are in an app server environment there may be some restrictions on whether you can register your own objects in JNDI. I haven't tried this so I have no idea whether it'll work, but It might be worth a try. -Jeremy On Tue, Aug 17, 2010 at 2:31 AM, hyndavi hyndav...@hcl.in wrote: Hi Mike, Thank you very much for your response. Yes. I have existing customized API that helps us to create Datasource and Connection objects based on Database availablility. This also maintains connection pools, checks Database availablility and etc. We are planning to use JPA going forward. With that we would like to integrate this customized API. -Hyndavi. -- View this message in context: http://openjpa.208410.n2.nabble.com/Integrating-existing-customized-Datasource-and-Connection-objects-in-JPA-tp5411498p5430996.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Glassfishv3 + OpenJPA-2.0.0: Enhancer not working
Sounds like you are getting closer. I scaled back to only including the openjpa-2.0.0.jar and serp in my app. Injection (into a servlet) and integrated/container enhancement continued to work. So, it doesn't look like an incompatibility with any of the Glassfish provided common or API libs. Hopefully, the Glassfish folks will be able to figure out what is up with injection. If you can share your app, I'd be happy to give it a go in my environment. -Jeremy On Tue, Jul 20, 2010 at 7:29 AM, Stefan Schilling mail.s...@gmx.de wrote: Jeremy, I just finished testing. I used the following setup: - manual enhancement via maven: disabled - manual MetaDataFactory setup: disabled - using Injection: enabled This one brings the Enhancer to life, I dont need to manually enhance a class or anything. BUT: The @PersistenceUnit dependency does *NOT* get shot into the class; the variable stays null. When I remove the @PersistenceUnit entries, the enhancer stops working as well. I used: @PersistenceUnit(unitName=myApplicationPersistenceUnit) private EntityManagerFactory emfTmp; private EntityManagerFactory emf = Persistence.createEntityManagerFactory(myApplicationPersistenceUnit); persistence.xml: persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd; version=1.0 persistence-unit name=myApplicationPersistenceUnit providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider jta-data-sourcejdbc/MyDataSource/jta-data-source properties property name=openjpa.TransactionMode value=managed/ property name=openjpa.ConnectionFactoryMode value=managed/ property name=openjpa.jdbc.DBDictionary value=mysql/ !-- property name=openjpa.MetaDataFactory value=jpa(Types=my.domain.entity.Class1;my.domain.entity.Class2)/ -- property name=openjpa.Log value=DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE/ /properties /persistence-unit /persistence emf is usable, emfTmp stays null; but the Enhancer is working. I'll report this one back to the Glassfish forum as well. Thanks. Stefan PS: yes, I know, OpenJPA delivers those 3 geronimo libraries as well, but these should be available as I'm using an app server. The commons-* and serp libraries are added to Glassfish's lib directory along w/ OpenJPA-2.0.0.jar. Original-Nachricht Datum: Mon, 19 Jul 2010 16:26:55 -0500 Von: Jeremy Bauer techhu...@gmail.com An: users@openjpa.apache.org Betreff: Re: Glassfishv3 + OpenJPA-2.0.0: Enhancer not working Stefan, Are you using an injected entity manager or entity manager factory: @PersistenceUnit private EntityManagerFactory emf; or going the application managed route: emf = Persistence.createEntityManagerFactory(myApplicationPersistenceUnit); ? In my simple test, I found that OpenJPA 2.0.0 OpenJPA 2.0.0 worked well with GlassFish v3 (74.2) when injecting an emf. The classes did not need to be listed in the persistence.xml and OpenJPA's class transformer hooked into the container - so I did not need to pre-enhance the entities. However, this did not happen when I went the app managed route - which is like running in JSE mode (which requires classes to be listed). I had to perform enhancement by other means and my entities needed to be listed in the persistence.xml. Injection into a servlet or EJB looks to be the best way to go, if possible. -Jeremy On Mon, Jul 19, 2010 at 8:04 AM, Stefan Schilling mail.s...@gmx.de wrote: Hello, I have a Glassfishv3 running here and *need* to use OpenJPA-2.0.0. I'm currently having two different setups in our persistence.xml; here's the working one: persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd; version=1.0 persistence-unit name=myApplicationPersistenceUnit transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider jta-data-sourcejdbc/MyDataSource/jta-data-source properties property name=openjpa.Log value=DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE/ !-- property name=openjpa.jdbc.SynchronizeMappings value=buildSchema/ -- /properties /persistence-unit /persistence This one has the disadvantage, that the entity classes used (here: Class1 and Class2) need to be listed twice (in persistence.xml and pom.xml), to configure the Enhancer outside of Glassfish and push the results
Re: Glassfishv3 + OpenJPA-2.0.0: Enhancer not working
Stefan, It does not look like your persistent classes are being discovered. I think I have glassfish v3 installed somewhere, so I'll see if I can reproduce the issue. BTW, there's a developer's edition of WebSphere Application Server V7[1] and a feature pack for OSGi/JPA 2.0[2] available for it. That'll give you nearly the same environment as your target platform. -Jeremy [1] http://www.ibm.com/developerworks/downloads/ws/wasdevelopers/ [2] http://www-01.ibm.com/software/webservers/appserv/was/featurepacks/osgi/ On Mon, Jul 19, 2010 at 8:04 AM, Stefan Schilling mail.s...@gmx.de wrote: Hello, I have a Glassfishv3 running here and *need* to use OpenJPA-2.0.0. I'm currently having two different setups in our persistence.xml; here's the working one: persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd; version=1.0 persistence-unit name=myApplicationPersistenceUnit transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider jta-data-sourcejdbc/MyDataSource/jta-data-source properties property name=openjpa.Log value=DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE/ !-- property name=openjpa.jdbc.SynchronizeMappings value=buildSchema/ -- /properties /persistence-unit /persistence This one has the disadvantage, that the entity classes used (here: Class1 and Class2) need to be listed twice (in persistence.xml and pom.xml), to configure the Enhancer outside of Glassfish and push the results into OpenJPA's MetaDataFactory. Of course, keeping two lists of classes up to date is error prone, especially as the following error is produced, if this step is omitted or some classes are forgotten: openjpa-2.0.0-r422266:935683 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter SELECT g FROM Class1 g ORDER BY g.dateCreated DESC. Error message: The name Class1 is not a recognized entity or identifier. Known entity names: [] at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:119) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:197) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:167) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:242) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:212) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:205) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.access$200(JPQLExpressionBuilder.java:81) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.populate(JPQLExpressionBuilder.java:2387) at org.apache.openjpa.kernel.jpql.JPQLParser.populate(JPQLParser.java:61) at org.apache.openjpa.kernel.ExpressionStoreQuery.populateFromCompilation(ExpressionStoreQuery.java:154) at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:671) at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:652) at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:618) at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:680) at org.apache.openjpa.kernel.QueryImpl.compile(QueryImpl.java:587) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:985) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:971) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:100) at my.domain.database.DatabaseAccess.getAllClass1(DatabaseAccess.java:159) at my.domain.portlets.MyPortlet.doView(MyPortlet.java:74) at javax.portlet.GenericPortlet.doDispatch(GenericPortlet.java:328) at javax.portlet.GenericPortlet.render(GenericPortlet.java:233) at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:103) at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:66) at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:91) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:802) at
Re: Glassfishv3 + OpenJPA-2.0.0: Enhancer not working
Stefan, Are you using an injected entity manager or entity manager factory: @PersistenceUnit private EntityManagerFactory emf; or going the application managed route: emf = Persistence.createEntityManagerFactory(myApplicationPersistenceUnit); ? In my simple test, I found that OpenJPA 2.0.0 OpenJPA 2.0.0 worked well with GlassFish v3 (74.2) when injecting an emf. The classes did not need to be listed in the persistence.xml and OpenJPA's class transformer hooked into the container - so I did not need to pre-enhance the entities. However, this did not happen when I went the app managed route - which is like running in JSE mode (which requires classes to be listed). I had to perform enhancement by other means and my entities needed to be listed in the persistence.xml. Injection into a servlet or EJB looks to be the best way to go, if possible. -Jeremy On Mon, Jul 19, 2010 at 8:04 AM, Stefan Schilling mail.s...@gmx.de wrote: Hello, I have a Glassfishv3 running here and *need* to use OpenJPA-2.0.0. I'm currently having two different setups in our persistence.xml; here's the working one: persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd; version=1.0 persistence-unit name=myApplicationPersistenceUnit transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider jta-data-sourcejdbc/MyDataSource/jta-data-source properties property name=openjpa.Log value=DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE/ !-- property name=openjpa.jdbc.SynchronizeMappings value=buildSchema/ -- /properties /persistence-unit /persistence This one has the disadvantage, that the entity classes used (here: Class1 and Class2) need to be listed twice (in persistence.xml and pom.xml), to configure the Enhancer outside of Glassfish and push the results into OpenJPA's MetaDataFactory. Of course, keeping two lists of classes up to date is error prone, especially as the following error is produced, if this step is omitted or some classes are forgotten: openjpa-2.0.0-r422266:935683 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter SELECT g FROM Class1 g ORDER BY g.dateCreated DESC. Error message: The name Class1 is not a recognized entity or identifier. Known entity names: [] at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:119) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:197) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:167) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:242) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:212) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:205) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.access$200(JPQLExpressionBuilder.java:81) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.populate(JPQLExpressionBuilder.java:2387) at org.apache.openjpa.kernel.jpql.JPQLParser.populate(JPQLParser.java:61) at org.apache.openjpa.kernel.ExpressionStoreQuery.populateFromCompilation(ExpressionStoreQuery.java:154) at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:671) at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:652) at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:618) at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:680) at org.apache.openjpa.kernel.QueryImpl.compile(QueryImpl.java:587) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:985) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:971) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:100) at my.domain.database.DatabaseAccess.getAllClass1(DatabaseAccess.java:159) at my.domain.portlets.MyPortlet.doView(MyPortlet.java:74) at javax.portlet.GenericPortlet.doDispatch(GenericPortlet.java:328) at javax.portlet.GenericPortlet.render(GenericPortlet.java:233) at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:103) at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:66)
Re: Glassfishv3 + OpenJPA-2.0.0: Enhancer not working
Stefan, I took another look at your stack and it looks like you are using an app managed persistence unit. It may simplify things for you if you can switch to using injection to get an instance of the emf. BTW, I have these libs bundled with my app: commons-collections-3.2.1.jar commons-lang-2.1.jar commons-pool-1.5.3.jar geronimo-jpa_2.0_spec-1.0.jar (not sure if this lib is required, but NetBeans complained if it wasn't there) openjpa-2.0.0.jar serp-1.13.1.jar -Jeremy On Mon, Jul 19, 2010 at 4:26 PM, Jeremy Bauer techhu...@gmail.com wrote: Stefan, Are you using an injected entity manager or entity manager factory: @PersistenceUnit private EntityManagerFactory emf; or going the application managed route: emf = Persistence.createEntityManagerFactory(myApplicationPersistenceUnit); ? In my simple test, I found that OpenJPA 2.0.0 OpenJPA 2.0.0 worked well with GlassFish v3 (74.2) when injecting an emf. The classes did not need to be listed in the persistence.xml and OpenJPA's class transformer hooked into the container - so I did not need to pre-enhance the entities. However, this did not happen when I went the app managed route - which is like running in JSE mode (which requires classes to be listed). I had to perform enhancement by other means and my entities needed to be listed in the persistence.xml. Injection into a servlet or EJB looks to be the best way to go, if possible. -Jeremy On Mon, Jul 19, 2010 at 8:04 AM, Stefan Schilling mail.s...@gmx.dewrote: Hello, I have a Glassfishv3 running here and *need* to use OpenJPA-2.0.0. I'm currently having two different setups in our persistence.xml; here's the working one: persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd; version=1.0 persistence-unit name=myApplicationPersistenceUnit transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider jta-data-sourcejdbc/MyDataSource/jta-data-source properties property name=openjpa.Log value=DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE/ !-- property name=openjpa.jdbc.SynchronizeMappings value=buildSchema/ -- /properties /persistence-unit /persistence This one has the disadvantage, that the entity classes used (here: Class1 and Class2) need to be listed twice (in persistence.xml and pom.xml), to configure the Enhancer outside of Glassfish and push the results into OpenJPA's MetaDataFactory. Of course, keeping two lists of classes up to date is error prone, especially as the following error is produced, if this step is omitted or some classes are forgotten: openjpa-2.0.0-r422266:935683 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter SELECT g FROM Class1 g ORDER BY g.dateCreated DESC. Error message: The name Class1 is not a recognized entity or identifier. Known entity names: [] at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:119) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:197) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:167) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:242) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:212) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:205) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.access$200(JPQLExpressionBuilder.java:81) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.populate(JPQLExpressionBuilder.java:2387) at org.apache.openjpa.kernel.jpql.JPQLParser.populate(JPQLParser.java:61) at org.apache.openjpa.kernel.ExpressionStoreQuery.populateFromCompilation(ExpressionStoreQuery.java:154) at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:671) at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:652) at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:618) at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:680) at org.apache.openjpa.kernel.QueryImpl.compile(QueryImpl.java:587) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:985) at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:971
Re: Saving a double in prosgres
Hi Håkon, I also see the rounded value when using DECIMAL(10, 6). OpenJPA passes the double value as-is to the JDBC driver and the JDBC driver or PostgreSQL DB does the rounding. It looks like double precision is a better choice for a data type. @ElementColumn(name = ELEMENT, columnDefinition=double precision,nullable=false) Using this type, I was able to store and returned the unrounded value [2.1993] within my entity upon query. Note: If you use SQL Shell/psql to verify the value, the value gets displayed as rounded whether you use the decimal or double precision type. So, be sure you validate the value within your JPA code. -Jeremy On Fri, Jun 11, 2010 at 9:00 AM, Rick Curtis curti...@gmail.com wrote: Are you using OpenJPA to generate your tables? If so, what is the SQL that is being generated to create this table? 2010/6/11 Håkon Sagehaug hakon.sageh...@uni.no Hi I tried to add the column definition @ElementColumn(name = ELEMENT, columnDefinition=DECIMAL(10, 6),nullable=false) But got the same when I want to persist value 2.199 I end up with 2.2. Any other tips? I use openjpa 1.2.0 should I migrate to 2.0? cheers, Håkon On 10 June 2010 18:19, Jeremy Bauer techhu...@gmail.com wrote: Håkon, I did not find a DOUBLEUNSIGNED type supported for PostgreSQL, but could have missed something. This should provide what you are looking for though... @PersistentCollection @ElementColumn(name = ELEMENT, columnDefinition=DECIMAL(10, 6),nullable=false) private double[] doubleValues; JPA/OpenJPA 2.0 provides standardized support for column definitions by using @ElementCollection and @Column, but unlike @PersistentCollection, @ElementCollection cannot be applied to an array. Instead, you'd need to use a collection type. If you are using OpenJPA 2.0 you could modify your code as follows: @ElementCollection @Column(columnDefinition=DECIMAL(10,6),nullable=false) private ListDouble doubleValues; public void setDoubles(Double[] doubles) { doubleValues = Arrays.asList(doubles); } public Double[] getDoubles() { return (Double[])doubleValues.toArray(); } Since List does not support primitive types, you'd also need to use the Double object type. You could then modify your getter and setter to convert to and from a primitive array. I didn't go that far, but it would be fairly simple. In addition, if you need to maintain the order of the array in the DB, use the @OrderColumn annotation. There is an OpenJPA version for JPA 1.0 apps and a standardized version in JPA 2.0, same annotation name, different packages. hth, -Jeremy 2010/6/10 Håkon Sagehaug hakon.sageh...@uni.no Hi all, I've got a persitent collection in a entity looking like this @PersistentCollection double[] doubleValues; But when I store the values the, it's rounded up. So if I want to store the value 2.1993 in the database it's stored as 2.2. The driver I 'm using is postgresql-8.3-603.jdbc3.jar. Should I use another type in the entity or is there another solution. I guess it's this issue [1], I'm facing. I found that you could set column property like this @Column(columnDefinition=DOUBLEUNSIGNED,precision=10,scale=6,nullable=false) But hwo can I set hat on a persitent collection? cheers, Håkon [1] http://openjpa.apache.org/builds/latest/docs/manual/dbsupport_postgresql.html#dbsupport_postgresql_issues
Re: Saving a double in prosgres
Håkon, I did not find a DOUBLEUNSIGNED type supported for PostgreSQL, but could have missed something. This should provide what you are looking for though... @PersistentCollection @ElementColumn(name = ELEMENT, columnDefinition=DECIMAL(10, 6),nullable=false) private double[] doubleValues; JPA/OpenJPA 2.0 provides standardized support for column definitions by using @ElementCollection and @Column, but unlike @PersistentCollection, @ElementCollection cannot be applied to an array. Instead, you'd need to use a collection type. If you are using OpenJPA 2.0 you could modify your code as follows: @ElementCollection @Column(columnDefinition=DECIMAL(10,6),nullable=false) private ListDouble doubleValues; public void setDoubles(Double[] doubles) { doubleValues = Arrays.asList(doubles); } public Double[] getDoubles() { return (Double[])doubleValues.toArray(); } Since List does not support primitive types, you'd also need to use the Double object type. You could then modify your getter and setter to convert to and from a primitive array. I didn't go that far, but it would be fairly simple. In addition, if you need to maintain the order of the array in the DB, use the @OrderColumn annotation. There is an OpenJPA version for JPA 1.0 apps and a standardized version in JPA 2.0, same annotation name, different packages. hth, -Jeremy 2010/6/10 Håkon Sagehaug hakon.sageh...@uni.no Hi all, I've got a persitent collection in a entity looking like this @PersistentCollection double[] doubleValues; But when I store the values the, it's rounded up. So if I want to store the value 2.1993 in the database it's stored as 2.2. The driver I 'm using is postgresql-8.3-603.jdbc3.jar. Should I use another type in the entity or is there another solution. I guess it's this issue [1], I'm facing. I found that you could set column property like this @Column(columnDefinition=DOUBLEUNSIGNED,precision=10,scale=6,nullable=false) But hwo can I set hat on a persitent collection? cheers, Håkon [1] http://openjpa.apache.org/builds/latest/docs/manual/dbsupport_postgresql.html#dbsupport_postgresql_issues
Re: Attribute 'pk-column-value' is not allowed to appear in element 'generated-value'
Hi Gilberto, The generated-value element does not provide an attribute named pk-column-value, thus, the schema validator validating your orm.xml file is throwing an exception. This line is the culprit: generated-value strategy=TABLE generator=table_generator pk-column-value=person/ The schema definition for generated-value is as follows: xsd:complexType name=generated-value xsd:annotation xsd:documentation @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface GeneratedValue { GenerationType strategy() default AUTO; String generator() default ; } /xsd:documentation /xsd:annotation xsd:attribute name=strategy type=orm:generation-type/ xsd:attribute name=generator type=xsd:string/ /xsd:complexType The pk-column-name can only be specified on the table generator itself. I don't think it is possible to override the pk-column-name at an attribute level - certainly not via generated-value. According to the JPA 2.0 spec: spec 3. The sequence-generator, table-generator, named-query, named-native-query and sql-result-set-mapping elements are global to the persistence unit. It is undefined to have more than one sequence-generator or table-generator of the same name in the same or different mapping files in a persistence unit. /spec Once a table generator is defined, there can/should only be one definition for the persistence unit. You can define multiples with a different pk-column-name values, but the table-generator name needs to be unique. hth, -Jeremy On Wed, Jun 9, 2010 at 9:29 AM, gilbertoca gilbert...@gmail.com wrote: Hi, hope everyone is well! Can anyone help me understand the following exception ( http://code.google.com/p/construtor/source/browse/trunk/park-jpa/core/src/main/resources/META-INF/orm.xml my orm.xml file ): [CODE] [INFO] [compiler:compile {execution: default-compile}] [INFO] Compiling 13 source files to /home/gilberto/dev/netbeans-config/park-jpa/core/target/classes [INFO] [antrun:run {execution: default}] [INFO] Executing tasks 216 parkPU INFO [main] openjpa.Tool - No targets were given. Running on all classes in your persistent classes list, or all metadata files in classpath directories if you have not listed your persistent classes. Use -help to display tool usage information. openjpa-2.0.0-r422266:935683 nonfatal general error org.apache.openjpa.util.GeneralException: org.xml.sax.SAXException: file:/home/gilberto/dev/netbeans-config/park-jpa/core/target/classes/META-INF/orm.xml [Location: Line: 30, C: 105]: org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'pk-column-value' is not allowed to appear in element 'generated-value'. at org.apache.openjpa.persistence.PersistenceMetaDataFactory.parseXML(PersistenceMetaDataFactory.java:295) at org.apache.openjpa.persistence.PersistenceMetaDataFactory.load(PersistenceMetaDataFactory.java:228) at org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:554) at org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:374) at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:358) at org.apache.openjpa.enhance.PCEnhancer.init(PCEnhancer.java:256) at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4653) at org.apache.openjpa.ant.PCEnhancerTask.executeOn(PCEnhancerTask.java:89) at org.apache.openjpa.lib.ant.AbstractTask.execute(AbstractTask.java:171) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) at org.apache.tools.ant.Task.perform(Task.java:348) at org.apache.tools.ant.Target.execute(Target.java:357) at org.apache.maven.plugin.antrun.AbstractAntMojo.executeTasks(AbstractAntMojo.java:118) at org.apache.maven.plugin.antrun.AntRunMojo.execute(AntRunMojo.java:98) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at
Re: relation mySequence already exists
Hi Christopher, As it turns out, I don't think this problem is the same as OPENJPA-1259. There is special code in the PostgresDictionary that treats sequences suffixed with _SEQ as system managed sequences. The comment in PostgresDictionary.isSystemSequence reads: // filter out generated sequences used for bigserial cols, which are // of the form table_col_seq This explains why the same code worked for me on DB2. Are you able to modify the sequence name? (ex. sequenceName = seq_obj_item_id) If not, please file a new JIRA. It may/should be possible to make the code a bit smarter by actually verifying _seq suffixed sequences are for a bigserial column[1] instead of just making the assumption. -Jeremy [1] http://www.postgresql.org/docs/8.4/static/datatype-numeric.html#DATATYPE-SERIAL On Mon, Jun 7, 2010 at 2:39 PM, Jeremy Bauer techhu...@gmail.com wrote: Christopher, I am able to reproduce the problem now with PostgreSQL using your code snippet. For now, I think I should be able to get by without the original code. Thanks so much for the offer, though. If you could test the fix if/when it is ready, that would be a great. -Jeremy On Mon, Jun 7, 2010 at 1:51 PM, Christopher Schmidt fakod...@googlemail.com wrote: Hi Jeremy, thx for your answer... If it helps I can push the sources and tests to Github (in a view days)? On Mon, Jun 7, 2010 at 8:33 PM, Jeremy Bauer techhu...@gmail.com wrote: Hi Christopher, . . .
Re: relation mySequence already exists
Christopher, I am able to reproduce the problem now with PostgreSQL using your code snippet. For now, I think I should be able to get by without the original code. Thanks so much for the offer, though. If you could test the fix if/when it is ready, that would be a great. -Jeremy On Mon, Jun 7, 2010 at 1:51 PM, Christopher Schmidt fakod...@googlemail.com wrote: Hi Jeremy, thx for your answer... If it helps I can push the sources and tests to Github (in a view days)? On Mon, Jun 7, 2010 at 8:33 PM, Jeremy Bauer techhu...@gmail.com wrote: Hi Christopher, . . .
Re: OpenJPA confusing classes
Good call, Pinaki! That fixed the failing testcase. I did/do not see this change documented in our 1.0 - 2.0 migration considerations. I'll update the JIRA, including the need for documentation. -Jeremy On Tue, May 25, 2010 at 1:07 AM, Pinaki Poddar ppod...@apache.org wrote: This should work: property name=openjpa.Compatibility value=StrictIdentityValues=true/ - Pinaki -- View this message in context: http://openjpa.208410.n2.nabble.com/OpenJPA-confusing-classes-tp5094249p5097022.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OpenJPA confusing classes
I started putting together a doc update and found that this compatibility flag has been around a while. Can anyone explain why 2.0 behaves differently than 1.x by default? (ie. flag not needed on 1.2, but required for 2.0) Did some new 2.0 spec requirement require OpenJPA to behave differently in this scenario? -Jeremy On Tue, May 25, 2010 at 8:09 AM, Jeremy Bauer techhu...@gmail.com wrote: Good call, Pinaki! That fixed the failing testcase. I did/do not see this change documented in our 1.0 - 2.0 migration considerations. I'll update the JIRA, including the need for documentation. -Jeremy On Tue, May 25, 2010 at 1:07 AM, Pinaki Poddar ppod...@apache.org wrote: This should work: property name=openjpa.Compatibility value=StrictIdentityValues=true/ - Pinaki -- View this message in context: http://openjpa.208410.n2.nabble.com/OpenJPA-confusing-classes-tp5094249p5097022.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OpenJPA confusing classes
Hi Chris, I was able to reproduce this problem. A SQL trace is showing that OpenJPA is executing the finder against the base table instead of the individual table(s). Please file a JIRA for this bug. I'll get the test code into trunk and then someone (possibly myself) can look into fixing it. -Jeremy On Mon, May 24, 2010 at 11:55 AM, C N Davies c...@cndavies.com wrote: Hi Kevin, I have L2 disabled as it has been too problematic for me, so it looks like the issue is in the L1 cache. I don't have a test case I can send out yet since I'm up at 3am in the morning trying to sort out JPA issues, yet again. Chris From: Kevin Sutter [mailto:kwsut...@gmail.com] Sent: Tuesday, 25 May 2010 2:23 AM To: users@openjpa.apache.org; c...@cndavies.com Subject: Re: OpenJPA confusing classes Hi Chris, This isn't good if the exact same code was working okay in 1.2.2 and it's not now. Now that the configuration and usage of the L2 cache is defined by the spec, there may be an inconsistency that needs to be resolved. Do you have the L2 DataCache enabled? It's off by default. Or, are you referring to the Persistence Context cache (also known as the L1 cache)? How much have you been able to debug this problem in order to narrow down the source? You mention the cache, but I'm not sure which one you are referring to. Your scenario looks pretty straight forward. Have you been able to create a simple testcase to demonstrate the problem? Any suggestions for resolution? Thanks, Kevin On Mon, May 24, 2010 at 10:55 AM, C N Davies c...@cndavies.com wrote: Well that would make sense if I wasn't using table per class. I used this very same code in 1.2.2 with no issues but 2.0 broke it. The DB is not enforcing this contraint, it is OpenJPA or more specifically the cache Chris -Original Message- From: KARR, DAVID (ATTSI) [mailto:dk0...@att.com] Sent: Tuesday, 25 May 2010 1:33 AM To: users@openjpa.apache.org; c...@cndavies.com Subject: RE: OpenJPA confusing classes -Original Message- From: C N Davies [mailto:c...@cndavies.com] Sent: Monday, May 24, 2010 8:19 AM To: users@openjpa.apache.org Subject: OpenJPA confusing classes Here's a snippet of my ode, (Department) es.find(Department.class, N/A); (PrintQueue) es.find(PrintQueue.class, N/A); Both Department and PrintQueue entities are based upon the same super class but I use table per class so they are in separate tables. As you can see they both have the same key, but if I put the department line 1st the find of the print queue will generate a class cast exception trying to cast a Department to a PrintQueue. If I put the PrintQueue line 1st I will get a class cast exception trying to cast a PrintQueue to a Department. The second find doesn't generate any SQL if I have trace logging turned on so it looks to me that it is a cache issue. I can't see anything like this in the JIRA is it a known bug or not? I would assume keys in an inheritance tree have to be unique across the hierarchy. If not, then there's no way to tell what object it really refers to. The CCEs are due to the fact that caching in the session uses the PK as the key (obviously). You already loaded a Department with that PK, so the reference on the next line is going to load it from the session, which blows up.
Re: JPA2.0 Criteria API question select()
Zhanming, Have you generated metamodel classes (EntityName_.java) for your entities? This section of the OpenJPA manual explains how to generate them. http://openjpa.apache.org/builds/2.0.0/apache-openjpa-2.0.0/docs/manual/manual.html#d0e11088 -Jeremy On Mon, May 24, 2010 at 1:37 PM, Kevin Sutter kwsut...@gmail.com wrote: Hi, Your example looks okay to me. Your selection is singular. There should be no reason for the multiselect. Maybe Eclipse is complaining about a problem that doesn't exist. Which Eclipse are you using? And, did you re-configure your Eclipse environment to be using OpenJPA instead of EclipseLink? Does your example compile cleanly outside of Eclipse? Maybe somebody else can spot an error in your example, but it looks like it should work. Kevin On Mon, May 24, 2010 at 9:46 AM, Zhanming Qi openglo...@gmail.com wrote: Hi, I download OpenJPA2.0 and try to use Criteria Query, and I download JPA2.0 Spec final release document form jcp.org At page 263, it wrote this: CriteriaBuilder cb = ... CriteriaQueryString q = cb.createQuery(String.class); RootCustomer customer = q.from(Customer.class); JoinCustomer, Order order = customer.join(Customer_.orders); JoinOrder, Item item = order.join(Order_.lineItems); q.select(customer.get(Customer_.name)) .where(cb.equal(item.get(Item_.product).get(Product_.productType), printer)); and I try it like this @Test public void testCriteriaQueryJoins(){ EntityManager em = entityManagerProvider.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQueryCorporation q = cb.createQuery(Corporation.class); RootCorporation corporation = q.from(Corporation.class); JoinCorporation, Division division = corporation.join(Corporation_.divisions); JoinDivision, Department department = division.join(Division_.departments); q.select(corporation.get(Corporation_.name)) .where(cb.equal(department.get(Department_.division).get(Division_.name), DIVISION_NAME)); TypedQueryCorporation tq = em.createQuery(q); ListCorporation result = tq.getResultList(); assertThat(result, notNullValue()); for (Corporation c : result){ System.out.println(c.getName()); } em.clear(); } But there is something wrong in this example. At this line q.select(corporation.get(Corporation_.name)), and Eclipse tell me that: the select method is wrong, and advise me to use multiselect(...) instead Is my code wrong? or document wrong? or some other wrong? Thanks, Zhanming. -- View this message in context: http://openjpa.208410.n2.nabble.com/JPA2-0-Criteria-API-question-select-tp5094119p5094119.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Schema version problem upgrading to JPA 2.0
Hi David, Based on the version and schemaLocation attributes (primarily version), OpenJPA should provide the proper rsrc file to the XML parser so that it can validate the orm using the correct version of the schema. (ie. version=1.0 - orm-xsd.rsrc ; version=2.0 - orm_2_0-xsd.rsrc) The specification uses the same namespace for both versions so that you can move from one version to the next with minimal changes. If you are still experiencing this problem can you provide a stripped down version of your war or ear file? I don't have WebLogic, but given a template, I could try to reproduce the issue on another app server. -Jeremy On Wed, May 19, 2010 at 9:08 PM, KARR, DAVID (ATTSI) dk0...@att.com wrote: -Original Message- From: KARR, DAVID (ATTSI) Sent: Wednesday, May 19, 2010 6:31 PM To: users@openjpa.apache.org Subject: Schema version problem upgrading to JPA 2.0 I think I noticed some talk about this before, but I can't find it in the archives now. I tried to upgrade to version 2.0.0 today. The upgrade with no changes worked fine. Now I'm trying to modify it to use the small number of 2.0 features that I'm attempting to use. When I changed the schemaLocation attribute to point to the 2.0 xsd (I'm really surprised the namespace didn't change), then Eclipse complained that I had to change the version attribute also, which I did (to 2.0). I then added several order-column elements where I was previously using the OpenJPA OrderColumn annotation. When I attempted to build this, I got schema validation errors, claiming that there was no order-column element (even though Eclipse validates this). If I temporarily changed the version attribute value back to 1.0, then I could get through that part of the build, even though Eclipse is now complaining. I haven't attempted to run the app in this state. What am I missing? I noticed that in the openjpa jar file, there are two schema files, orm-xsd.rsrc and orm_2_0-xsd.rsrc. The first is the 1.x schema, and the second is clearly the 2.x schema. I'm really wondering more about the fact that the namespace is the same between them. That can't be right. I wonder what would happen if I removed the 1.x schema from the jar file?
Re: [VOTE] Apache OpenJPA 2.0.0 release candidate #2
+1 Looks great. Thanks again, Donald. -Jeremy On Mon, Apr 19, 2010 at 1:45 PM, Donald Woods dwo...@apache.org wrote: I've staged a RC2 for OpenJPA 2.0.0 based on r935683 of the code in the 2.0.x branch, which was tagged in svn to: https://svn.apache.org/repos/asf/openjpa/tags/2.0.0/ The following issues were resolved since the first RC vote on April 11th (svn r932976): OPENJPA-1091, OPENJPA-1605, OPENJPA-1628, OPENJPA-1630, OPENJPA-1631 Release Notes: http://svn.apache.org/viewvc/openjpa/tags/2.0.0/openjpa-project/RELEASE-NOTES.html?view=co Maven staging repo: http://people.apache.org/~dwoods/openjpa/2.0.0/staging-repo/http://people.apache.org/%7Edwoods/openjpa/2.0.0/staging-repo/ Site staging: http://people.apache.org/~dwoods/openjpa/2.0.0/staging-site/http://people.apache.org/%7Edwoods/openjpa/2.0.0/staging-site/ Distribution artifacts: http://people.apache.org/~dwoods/openjpa/2.0.0/staging-site/apache-openjpa/downloads/http://people.apache.org/%7Edwoods/openjpa/2.0.0/staging-site/apache-openjpa/downloads/ User's Guide: http://people.apache.org/~dwoods/openjpa/2.0.0/staging-site/apache-openjpa/docs/http://people.apache.org/%7Edwoods/openjpa/2.0.0/staging-site/apache-openjpa/docs/ API Docs: http://people.apache.org/~dwoods/openjpa/2.0.0/staging-site/apidocs/http://people.apache.org/%7Edwoods/openjpa/2.0.0/staging-site/apidocs/ The RAT and IANAL build checks passed. The openjpa and openjpa-all shaded jar content looks good. The test-base, test-sources and tests jars are in the staging repo. The vote will be open for 3 days. [ ] +1 [ ] 0 [ ] -1 (and reason why) Thanks, Donald
Re: Terms for catalog and schema
Hi Daniel, The various database vendors and JDBC drivers have different usage of catalogs, some not using them at all or treating them the same as a schema. While many JPA mapping constructs allow you to specify a catalog attribute, I've found that OpenJPA uses the default catalog. There is a JIRA[1] filed to enhance the catalog support at some point, but there hasn't been much/any call for it. If you have specific scenarios you'd like to see supported, please document them in the JIRA or post them and I'll get them added to the JIRA. That'll help ensure those scenarios get tested if/when the support is added. -Jeremy [1] https://issues.apache.org/jira/browse/OPENJPA-840 On Thu, Mar 25, 2010 at 7:52 PM, Daniel Toffetti dto...@yahoo.com.arwrote: Now that I think again, the catalog is the specific database I'm connecting to... I've been surprised before by the fact that I could get a list of catalogs even when I'm connecting to one specific database, but anyway with Schemacrawler and with plain JDBC I could get it. Perhaps this will be of interest later if I need to support multiple database products, but right now I can get the list of tables I'm interested in. Thanks in advance for any comments, Best, Daniel Daniel Toffetti wrote: Is there any other term for catalog in OpenJPA parlance ?? Am I missing something ?? -- View this message in context: http://n2.nabble.com/Terms-for-catalog-and-schema-tp4801224p4801363.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: [ANNOUNCE] Welcome Rick Curtis as the newest member of the OpenJPA PMC
Congrats, Rick! Well done! -Jeremy On Fri, Mar 26, 2010 at 10:08 AM, Michael Dick mik...@apache.org wrote: All, Please join us in congratulating Rick Curtis as the newest member of the OpenJPA *PMC*. It's been great to have Rick working with us as a committer on OpenJPA. Even better to have him join us in providing oversight of the OpenJPA project. Way to go Rick!!! The Apache OpenJPA *PMC* -mike
Re: [VOTE] OpenJPA 2.0.0-beta3 release candidate
+1 Looks good! -Jeremy On Tue, Mar 23, 2010 at 9:36 PM, Donald Woods dwo...@apache.org wrote: I've staged a release candidate for OpenJPA 2.0.0 Beta 3 based on r926797 of the code in the 2.0.x branch, which was tagged in svn to: https://svn.apache.org/repos/asf/openjpa/tags/2.0.0-beta3/ Release Notes: http://svn.apache.org/viewvc/openjpa/tags/2.0.0-beta3/openjpa-project/RELEASE-NOTES.html?view=co Maven staging repo: http://people.apache.org/~dwoods/openjpa/2.0.0-beta3/staging-repo/http://people.apache.org/%7Edwoods/openjpa/2.0.0-beta3/staging-repo/ Site staging: http://people.apache.org/~dwoods/openjpa/2.0.0-beta3/staging-site/http://people.apache.org/%7Edwoods/openjpa/2.0.0-beta3/staging-site/ Distribution artifacts: http://people.apache.org/~dwoods/openjpa/2.0.0-beta3/staging-site/apache-openjpa/downloads/http://people.apache.org/%7Edwoods/openjpa/2.0.0-beta3/staging-site/apache-openjpa/downloads/ User's Guide: http://people.apache.org/~dwoods/openjpa/2.0.0-beta3/staging-site/apache-openjpa/docs/http://people.apache.org/%7Edwoods/openjpa/2.0.0-beta3/staging-site/apache-openjpa/docs/ API Docs: http://people.apache.org/~dwoods/openjpa/2.0.0-beta3/staging-site/apidocs/http://people.apache.org/%7Edwoods/openjpa/2.0.0-beta3/staging-site/apidocs/ The eventual landing page for Beta 3 on the wiki (most of the links will not work until the vote passes and artifacts are published): http://cwiki.apache.org/confluence/display/openjpa/OpenJPA+2.0.0+Beta+3 The RAT and IANAL build checks passed. The openjpa and openjpa-all shaded jar content looks good. The test-base, test-sources and tests jars are in the staging repo. The build passed the JPA 2.0 TCK. The vote will be open for 72 hours or less. [ ] +1 [ ] 0 [ ] -1 (and reason why) Thanks, Donald
Re: Use external classes as entities
This may/may not work depending on your environment and the class definitions, but you could try defining the mappings and metadata for ForeignClass1 and ForeignClass2 in an orm.xml file. Another issue will be getting these classes enhanced and verifying they still behave properly after enhancement (ie. the business logic, if any, still works properly). If you are in a JSE environment, you could try using the agent enhancer. It will enhance the classes as they are loaded (no need to modify the jar). You'll likely need to specify the iCal4j jar in a jar-file element and define the foreign classes in class elements within your persistence.xml. -Jeremy On Wed, Mar 24, 2010 at 2:25 PM, Pinaki Poddar ppod...@apache.org wrote: Any ideas? Please see [1] [1] http://openjpa.apache.org/builds/latest/docs/manual/manual.html#type - Pinaki -- View this message in context: http://n2.nabble.com/Use-external-classes-as-entities-tp4787743p4793276.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Open jpa 2.0 and maven build
Including the schema location to the 2.0 persistence XSD should work and may be necessary using Spring, since, like JEE containers, it may parse the persistence.xml and expect the schemaLocation to be present for validation purposes. But, I haven't used Spring either so I can say for certain. persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd; version=2.0 ... /persistence -Jeremy On Thu, Mar 11, 2010 at 2:50 PM, Donald Woods dwo...@apache.org wrote: By the JPA schema version specified in the persistence.xml - persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; version=2.0 The above is used in out junits to test the Bean Validation supprt which is JPA 2.0 specific. Not sure if using the reference to the 2_0.xsd works. -Donald On 3/11/10 3:40 PM, Pmoran wrote: That has not helped. let me get back to an earlier question, how does OPENJPA determine a given project is version 1.0 versus 2.0? My project does the following: Set openjpa.specification=jpa 2.0 persistence.xml is version 2.0 no orm.xml only openJPA-2.0.0beta2.jar on path Eclipse (STS version) IDE, maven pom based build What am i missing?
Re: Open jpa 2.0 and maven build
Including the schema location to the 2.0 persistence XSD should work and may be necessary using Spring, since, like JEE containers, it may parse the persistence.xml and expect the schemaLocation to be present for validation purposes. But, I haven't used Spring either so I can say for certain. persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd; version=2.0 ... /persistence -Jeremy On Thu, Mar 11, 2010 at 2:50 PM, Donald Woods dwo...@apache.org wrote: By the JPA schema version specified in the persistence.xml - persistence xmlns=http://java.sun.com/xml/ns/persistence; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; version=2.0 The above is used in out junits to test the Bean Validation supprt which is JPA 2.0 specific. Not sure if using the reference to the 2_0.xsd works. -Donald On 3/11/10 3:40 PM, Pmoran wrote: That has not helped. let me get back to an earlier question, how does OPENJPA determine a given project is version 1.0 versus 2.0? My project does the following: Set openjpa.specification=jpa 2.0 persistence.xml is version 2.0 no orm.xml only openJPA-2.0.0beta2.jar on path Eclipse (STS version) IDE, maven pom based build What am i missing?
Re: Error trying to enhance at build time
Hi remmons, The PCEnhancer requires the path to the file instead of the package. For example: To compile: javac -cp openjpa-all-2.0.0-beta2.jar;. com\aurigen\openjpanys\Message.java then... To enhance: java -cp openjpa-all-2.0.0-beta2.jar;. org.apache.openjpa.enhance.PCEnhancer com\aurigen\openjpanys\Message[.java|.class] hth, -Jeremy On Thu, Mar 4, 2010 at 4:06 PM, Kevin Sutter kwsut...@gmail.com wrote: Hi remmons, Where are your application's java class files? The exception stack below says that it can't find your Message.java file. Is it in your classpath? [exec] Caused by: java.io.FileNotFoundException: com.aurigen.openjpanys.Message.java (The system cannot find the file specified) Kevin On Thu, Mar 4, 2010 at 1:24 PM, remmons remm...@aurigen.com wrote: I am trying to enhance a class at build time, but I get an error message. Here is my command line: [exec] C:\document\eclipse350\webJava\OpenJpaNysjava -cp src\java;build;lib\openjpa-2.0.0-beta2.jar;lib\openjpa-all-2.0.0-beta2.jar org.apache.openjpa.enhance.PCEnhancer com.aurigen.openjpanys.Message.java Here is the error I am getting: [exec] Exception in thread main org.apache.commons.lang.exception.NestableRuntimeException: Error extracting class information from com.aurigen.openjpanys.Message.java. [exec] at org.apache.openjpa.lib.meta.ClassArgParser.parseTypeNames(ClassArgParser.java:226) [exec] at org.apache.openjpa.lib.meta.ClassArgParser.parseTypes(ClassArgParser.java:161) [exec] at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4638) [exec] at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4601) [exec] at org.apache.openjpa.enhance.PCEnhancer$1.run(PCEnhancer.java:4571) [exec] at org.apache.openjpa.lib.conf.Configurations.launchRunnable(Configurations.java:725) [exec] at org.apache.openjpa.lib.conf.Configurations.runAgainstAllAnchors(Configurations.java:715) [exec] at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4566) [exec] at org.apache.openjpa.enhance.PCEnhancer.main(PCEnhancer.java:4557) [exec] Caused by: java.io.FileNotFoundException: com.aurigen.openjpanys.Message.java (The system cannot find the file specified) [exec] at java.io.FileInputStream.open(Native Method) [exec] at java.io.FileInputStream.init(Unknown Source) [exec] at java.io.FileReader.init(Unknown Source) [exec] at org.apache.openjpa.lib.meta.ClassArgParser.getFromJavaFile(ClassArgParser.java:339) [exec] at org.apache.openjpa.lib.meta.ClassArgParser.parseTypeNames(ClassArgParser.java:219) [exec] ... 8 more Can anyone tell me what is wrong? -- View this message in context: http://n2.nabble.com/Error-trying-to-enhance-at-build-time-tp4676588p4676588.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Struts 2x + OpenJPA 2.0 M3 + ( Tomcat or Glassfish )
Seth, Thanks for reporting this problem. I've opened JIRA OPENJPA-1410[1]. The code in PersistenceProviderImpl that sets up validation looks like it might be suspect to classloading issues. Which version of Tomcat are you using? -Jeremy [1] https://issues.apache.org/jira/browse/OPENJPA-1410 On Tue, Dec 1, 2009 at 5:56 AM, seth.jackson seth.jackson@dfas.milwrote: After further review, using Glassfish 2.1.1 I received this error message in the server log: Caused by: java.lang.LinkageError: loader constraint violation: when resolving method org.apache.openjpa.persistence.validation.ValidationUtils.setupValidation(Lorg/apache/openjpa/conf/OpenJPAConfiguration;)Z the class loader (instance of org/apache/catalina/loader/WebappClassLoader) of the current class, org/apache/openjpa/persistence/PersistenceProviderImpl, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for resolved class, org/apache/openjpa/persistence/validation/ValidationUtils, have different Class objects for the type org/apache/openjpa/conf/OpenJPAConfiguration used in the signature So it appears to be the WebappClassLoader and the AppClassLoader are both loading the OpenJPAConfiguration from the same JAR file, causing the error when the class is trying to be resolved in this particular method.. seth.jackson wrote: It appears something was modified in OpenJPA 2.0 M3 from M2 that causes a LinkageError. In my current environment, I've tested both Glassfish and Tomcat using M2 and M3. M2 runs without problems, but M3 throws a linkage error as follows: Caused by: java.lang.LinkageError: loader constraint violation: loader (instance of sun/misc/Launcher$AppClassLoader) previously initiated loading for a different type with name org/apache/openjpa/conf/OpenJPAConfiguration at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:621) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$000(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) at org.apache.openjpa.persistence.validation.ValidationUtils.setupValidation(ValidationUtils.java:53) at org.apache.openjpa.persistence.PersistenceProviderImpl.loadValidator(PersistenceProviderImpl.java:290) at org.apache.openjpa.persistence.PersistenceProviderImpl.createEntityManagerFactory(PersistenceProviderImpl.java:97) at org.apache.openjpa.persistence.OpenJPAPersistence.createEntityManagerFactory(OpenJPAPersistence.java:128) at org.apache.openjpa.persistence.OpenJPAPersistence.createEntityManagerFactory(OpenJPAPersistence.java:111) at test_test.user.UserAction.execute(UserAction.java:39) I've already confirmed that the OpenJPA classes in question do NOT exist in any other JARs in the path. ValidationUtils.setupValidation(ValidationUtils.java:53) calls the OpenJPAConfiguration.getConfigurationLog(). The object being referenced is JDBCConfigurationImpl, which in other classes retrieves the log reference perfectly fine, before it gets to the offending line. -- View this message in context: http://n2.nabble.com/Struts-2x-OpenJPA-2-0-M3-Tomcat-or-Glassfish-tp4087312p4093228.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: oracle 11g - operation not allowed: streams type cannot be used in batching
Nick, I ran into a batching related issue while doing some Oracle testing on trunk (2.0.0) a short while ago. The issue was fixed in the 11.2.0.1 version of the JDBC driver. It might be worth a shot to try the 11.2.0.1 driver before disabling statement batching. -Jeremy On Tue, Oct 13, 2009 at 9:39 AM, Michael Dick michael.d.d...@gmail.comwrote: Hi Nick, It sounds like turning off SQL statement batching will help here's a link to the section in the manual : http://openjpa.apache.org/builds/1.2.1/apache-openjpa-1.2.1/docs/manual/manual.html#ref_guide_dbsetup_stmtbatch -mike On Tue, Oct 13, 2009 at 8:26 AM, nick_j_m...@uk.ibm.com nick_j_m...@uk.ibm.com wrote: Just retested this in oracle 10g and appears to be the same issue Oracle 10g R2 using ojdbc14.jar - 10.1.0.2.0 Nick nick_j_m...@uk.ibm.com wrote: Hi there While testing my app against oracle 11 g i discover this new error. I'm using openjpa 1.2.1 I'm using the ojdbc5.jar - 11.1.0.6.0 org.apache.openjpa.persistence.PersistenceException: operation not allowed: streams type cannot be used in batching this occuers when trying to insert to a table associated with a pojo that has a Lob annotation this works on sqlserver and with oracle 10g -- View this message in context: http://n2.nabble.com/oracle-11g-operation-not-allowed-streams-type-cannot-be-used-in-batching-tp3816015p3816032.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: metadata api?
Hi Chris, OpenJPA provides APIs that allow you to interrogate class mappings. Using a direct approach (OpenJPA resolves class mapping and metadata as part of creating an emf/em), this code gives you access to the primary and foreign keys of an entity via the schema information stored in the mapping. import org.apache.openjpa.jdbc.meta.ClassMapping; import org.apache.openjpa.jdbc.schema.Column; import org.apache.openjpa.jdbc.schema.ForeignKey; import org.apache.openjpa.jdbc.schema.PrimaryKey; import org.apache.openjpa.persistence.JPAFacadeHelper; ... EntityManager em = emf.createEntityManager(); ClassMapping clsMapping = (ClassMapping)JPAFacadeHelper.getMetaData(em, SomeEntity.class); ForeignKey[] fks = clsMapping.getTable().getForeignKeys(); PrimaryKey pk = clsMapping.getTable().getPrimaryKey(); hth, -Jeremy On Wed, Sep 9, 2009 at 3:31 AM, Christopher Giblin c...@zurich.ibm.comwrote: Hi, I defined object-relational mappings in orm.xml. Works fine. Is an API available which allows querying of the orm definition for a given object? I am programming with reflection and would like to know, given an object, which of its attributes are primary or foreign keys. Thanks, chris
Re: ClassStrategy.
Hi Chris, As you dive into creating custom strategies, besides reading the OpenJPA docs, you may also want to check out this blog post[1] on the topic. -Jeremy [1] http://webspherepersistence.blogspot.com/2009/04/custom-orm-with-openjpa.html On Fri, Aug 7, 2009 at 2:43 AM, C N Davies c...@cndavies.com wrote: Looking at the docs there should be an interface named org.apache.openjpa.jdbc.meta.ClassStrategy which needs to be implemented in order to implement a strategy for a custom class. But I cannot find the class in any of the OpenJPA 1.2.1 jars. Is the document wrong or am I just stupid? Thanks J Chris
Re: How to get database information
Martin, The OpenJPAEntityManagerSPI interface provides a method to access the underlying JDBC connection used by the em. You can use that connection to get db metadata information. Depending on whether your application uses a container or application managed em, you may need to call em.getDelegate() to get the underlying OpenJPA entity manager implementation. Otherwise, you'll get a cast exception. Here's an example: OpenJPAEntityManagerSPI oem = (OpenJPAEntityManagerSPI)em.getDelegate(); java.sql.Connection conn = (java.sql.Connection) oem.getConnection(); java.sql.DatabaseMetaData dbmd = conn.getMetaData(); String dbProductName = dbmd.getDatabaseProductName(); String dbProductVersion = dbmd.getDatabaseProductVersion(); String dbURL = dbmd.getURL(); I ran this code in an app configured to use a data source and it returned the JDBC URL configured for the data source. You could potentially parse the URL for the host system, database name, etc. I don't recommend using this connection for other SQL operations since it could end up in state not suitable for use by OpenJPA. hth, -Jeremy On Thu, Jul 9, 2009 at 9:35 AM, mjdenham mjden...@gmail.com wrote: Hi, Is there an easy way to dynamically find the database name and schema name being used by an EntityManager at runtime? We are using OpenJpa 1.0.4 on Websphere and an Oracle datasource. We would like to make the information accessible on an application screen because we have so many environments - dev, test, uvt, uat, integration that it gets confusing to know which database a tester is using. Thanks Martin -- View this message in context: http://n2.nabble.com/How-to-get-database-information-tp3231794p3231794.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: [VOTE] OpenJPA Logo Contest
First - 14 Second - 7 Third - 9 -Jeremy On Thu, Jul 2, 2009 at 3:24 PM, Ravi Palacherla ravi.palache...@oracle.comwrote: First - 15 Second - 8 Third - 9 - Ravi. -Original Message- From: Donald Woods [mailto:dwo...@apache.org] Sent: Thursday, July 02, 2009 2:00 PM To: d...@openjpa.apache.org; users@openjpa.apache.org Cc: go...@oles.biz Subject: [VOTE] OpenJPA Logo Contest It's time to vote on your favorite logo! Anyone can vote for up to 3 logos and logo submitters can vote for their own logos. For example, First - #13 Second - #15 Third - #7 Please include all of your votes in a single email reply to this thread and use the index on the wiki page to denote which entry you are voting on (1 - 15.) -Donald Donald Woods wrote: Announcing the OpenJPA Logo Contest! Submissions: Accepted now through June 30, 2009 Rules and Guidelines: See the Logo Contest page [1] for more details. Voting: Will occur from July 1 through July 14. Winner: Will be announced on or after July 15. [1] http://cwiki.apache.org/openjpa/logo-contest.html -Donald
Re: Best practice to avoid duplicates on @Column(unique=true)
David Milosz, Based on the information provided, I do not think Bean Validation would provide a good solution for this problem. Used within the context of JPA, bean validation gets called when various lifecycle events occur; pre-persist, pre-remove, pre-update. In order to create a custom validation constraint, you'd likely need to invoke some database operations (likely some variant of the query Craig suggested). Regarding the use of em query operations inside lifecycle events JPA specification states: spec In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context.[38] A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked. /spec So using database operations, at least within the same persistence context, probably isn't a good idea. Regardless, I think the net result would be that, application-wise, you'd be back in the nearly same situation as present. The exception would still occur on the persist, the main difference would be that the exception would be coming from the validator instead of the failed database operation. -Jeremy On Sat, Jun 20, 2009 at 3:30 AM, Miłosz Tylenda mtyle...@o2.pl wrote: David, Apart from what Craig has suggested, what came to my mind is that there is an ongoing effort to implement JSR-303 Bean Validation in OpenJPA 2.0. Not sure however, whether it is sufficiently implemented yet and it can be used for your purpose. Might be worth checking though. Cheers, Milosz I realise that this is not strickly an OpenJPA problem, rather a more general JPA one, but there are experts here who might know the answer. I have a number of classes which represent tables which have not only an Id field, but also various other fields which are marked as unique. When I persist and then try to flush a new object which has a non-unique value in the object (the user entered bad data) it breaks the transaction and throws an error. All of which is quite understandable. The question is what is the best way to avoid it. Do I have to build the checking into the application, or is there a more generic way which I can use as a validation technique before I try to persist the object. David
Re: Best practice to avoid duplicates on @Column(unique=true)
Hi Milosz, Great observation questions. The sentence you refer to means that you can directly invoke a JSR-303 validator at any time from the application. ex: javax.validation.ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); javax.validation.Validator validator = factory.getValidator(); EntityA a = em.find(EntityA.class, IdOfA); SetConstraintViolationEntityA cvs = validator.validate(a); I've only briefly read over how one may create and tie a constraint validator implementation class to a custom constraint, but I don't see an immediate way that the constraint validator could get access (outside of some static helper method) to an em during the validation process. That said, I did not read anything in the specs (but, I could easily have missed something) that would prevent the constraint validator from accessing an em during application driven validation... so it could potentially be used during that process. Care would need to be taken not to cause unintended side-effects (locks, loading, tx commit/rollback, etc.). One more thing to keep in mind, application driven validation also requires a JPA traversable resolver to prevent from validating unloaded or related entities. OpenJPA does not provide a resolver, but the plan is to provide one in a future iteration of 2.0. Until that is available, validating of unloaded and related entities (if tagged with @Valid) will occur. BTW, This scenario will make a great set of test cases. :-) -Jeremy On Mon, Jun 22, 2009 at 12:59 PM, Miłosz Tylenda mtyle...@o2.pl wrote: Jeremy, Thanks for the explanation. Maybe you could also explain this sentence from the spec: Validation can also be achieved by the application calling the validate method of a validator instance upon an instance of a managed class, as described in the Bean Validation specification [8] Does it mean we can call validate at whatever time in the persistence context? Can we access entity manager then? Greetings, Milosz David Milosz, Based on the information provided, I do not think Bean Validation would provide a good solution for this problem. Used within the context of JPA, bean validation gets called when various lifecycle events occur; pre-persist, pre-remove, pre-update. In order to create a custom validation constraint, you'd likely need to invoke some database operations (likely some variant of the query Craig suggested). Regarding the use of em query operations inside lifecycle events JPA specification states: In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context.[38] A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked. So using database operations, at least within the same persistence context, probably isn't a good idea. Regardless, I think the net result would be that, application-wise, you'd be back in the nearly same situation as present. The exception would still occur on the persist, the main difference would be that the exception would be coming from the validator instead of the failed database operation. -Jeremy On Sat, Jun 20, 2009 at 3:30 AM, Miłosz Tylenda wrote: David, Apart from what Craig has suggested, what came to my mind is that there is an ongoing effort to implement JSR-303 Bean Validation in OpenJPA 2.0. Not sure however, whether it is sufficiently implemented yet and it can be used for your purpose. Might be worth checking though. Cheers, Milosz I realise that this is not strickly an OpenJPA problem, rather a more general JPA one, but there are experts here who might know the answer. I have a number of classes which represent tables which have not only an Id field, but also various other fields which are marked as unique. When I persist and then try to flush a new object which has a non-unique value in the object (the user entered bad data) it breaks the transaction and throws an error. All of which is quite understandable. The question is what is the best way to avoid it. Do I have to build the checking into the application, or is there a more generic way which I can use as a validation technique before I try to persist the object. David
Re: OpenJPA-2.0.0-snapshot Question with @ManyToMany
Open Gloves, Apologies. I did not verify that the insert into the collection actually took place. After re-running the test, paying close attention to the trace output, I found the source of the problem. During entity enhancement several warnings were logged of this form: 1656 sample WARN [main] openjpa.Enhance - Detected the following possible violations of the restrictions placed on property access persistent types: entities.Student uses property access, but its field teachers is accessed directly in method removeTeacher defined in entities.Student. In short, non-persistent methods in Teacher and Student are accessing fields directly instead of calling the persistent property methods. In order for OpenJPA to effectively track changes in the persistent properties they must be accessed instead of the fields. Modifying the addTeacher and removeTeacher methods as below corrected the problem. public void addTeacher(Teacher teacher) { if (getTeachers() == null) setTeachers(new HashSetTeacher()); getTeachers().add(teacher); } public void removeTeacher(Teacher teacher) { if (getTeachers().contains(teacher)) { getTeachers().remove(teacher); } } This looks to be another implementation difference between OpenJPA and Hibernate. -Jeremy On Tue, Jun 2, 2009 at 12:51 AM, opengloves openglo...@gmail.com wrote: Hi, Thanks for your response. I hardcoded is just for test @ManyToMany and see the effect. @GeneratedValue is not the point of this issue. I also do not think this is the bug of OpenJPA, and I had been modified the code like your advice before, and It didn't passed test either. because the test code is passed, but it didn't do the right thing because the data is not insert into the table STUDENT_TEACHER, this is strange, and I also test the hibernate without if block and it works, and I tested the method testPersistJoinTable() twice and the table is also contain one record. and this is good, this is the META-INF/persistence.xml about hibernate persistence-unit name=sample transaction-type=RESOURCE_LOCAL classorg.sample.demo.jpa.entity.manytomany.Student/class classorg.sample.demo.jpa.entity.manytomany.Teacher/class properties property name=hibernate.dialect value=org.hibernate.dialect.DerbyDialect/ property name=hibernate.connection.url value=jdbc:derby://localhost:1527/sample;create=true / property name=hibernate.connection.driver_class value=org.apache.derby.jdbc.ClientDriver / property name=hibernate.connection.username value=user / property name=hibernate.connection.password value=secret / property name=hibernate.hbm2ddl.auto value=update/ /properties /persistence-unit Jar Environment: antlr-2.7.6, commons-collections-3.1, dom4j-1.6.1, ejb3-persistence, hibernate3, hibernate-annotations, hibernate-cglib-repack-2.1_3, hibernate-commons-annotations, hibernate-entitymanager, javassist-3.4.GA, jta-1.1, log4j-1.2.15, slf4j-api-1.5.2, slf4j-log4j12-1.5.0. Other environment and codes are the same.(Student.java, Teacher.java, ManyToManyTest.java are the same) After modified the code, I think this is strange: the test is passed and the data is not insert into the table. And I come here, find help. Or maybe this is a bug? I think add this if block is the provider dependence, maybe. -- Thanks Open Gloves Jeremy Bauer wrote: Hi, Interesting that this works on Hibernate. The first potential issue I found in the test is that it uses a hardcoded id and your entities are annotated with @GeneratedValue. Depending on how the value is generated, the values could be different between test runs and providers. Storing away the id of the persisted entities (in static fields, for example) is a safer and more consistent way to make sure the test accesses the same entities in future test variations. The NPE is the result of the student.teachers collection being null. While the class contains code to set it to new HashSet upon construction, OpenJPA sets it to null after the find operation - since the set did not contain any elements when Student was persisted. Modifying the addTeacher method as below corrected the NPE and the test passed. public void addTeacher(Teacher teacher) { if (teachers == null) teachers = new HashSetTeacher(); this.teachers.add(teacher); } Based on the behavior I've seen, I do not think this is a bug in OpenJPA. While I haven't tested with Hibernate, I suspect it is just a difference in how empty/null collections are stored and initialized by each provider. hth, -Jeremy -- View this message in context: http://n2
Re: OpenJPA-2.0.0-snapshot Question with @ManyToMany
Hi, Interesting that this works on Hibernate. The first potential issue I found in the test is that it uses a hardcoded id and your entities are annotated with @GeneratedValue. Depending on how the value is generated, the values could be different between test runs and providers. Storing away the id of the persisted entities (in static fields, for example) is a safer and more consistent way to make sure the test accesses the same entities in future test variations. The NPE is the result of the student.teachers collection being null. While the class contains code to set it to new HashSet upon construction, OpenJPA sets it to null after the find operation - since the set did not contain any elements when Student was persisted. Modifying the addTeacher method as below corrected the NPE and the test passed. public void addTeacher(Teacher teacher) { if (teachers == null) teachers = new HashSetTeacher(); this.teachers.add(teacher); } Based on the behavior I've seen, I do not think this is a bug in OpenJPA. While I haven't tested with Hibernate, I suspect it is just a difference in how empty/null collections are stored and initialized by each provider. hth, -Jeremy On Mon, Jun 1, 2009 at 9:03 AM, opengloves openglo...@gmail.com wrote: IDE Environment: Eclipse-3.4 DB Environment: Apache-Derby-10.5.1.1 JDK Environment: Sun JDK-1.6.0_07 Jar Environment: from http://openjpa.apache.org/builds/latest/downloads/apache-openjpa-2.0.0-SNAPSHOT-binary.zip Eclipse PlugIn Environment:Apache-Derby, JUnit4 I want to test the @ManyToMany(the example is Teacher and Student, many to many) The code is this: Student.java @Entity public class Student { private int id; private String name; private SetTeacher teachers = new HashSetTeacher(); @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(length = 10, nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToMany(cascade = { CascadeType.REFRESH }) @JoinTable( name = STUDENT_TEACHER, inverseJoinColumns = @JoinColumn(name = TEACHER_ID), joinColumns = @JoinColumn(name = STUDENT_ID) ) public SetTeacher getTeachers() { return teachers; } public void setTeachers(SetTeacher teachers) { this.teachers = teachers; } public void addTeacher(Teacher teacher) { this.teachers.add(teacher); } public void removeTeacher(Teacher teacher) { if (this.teachers.contains(teacher)) { this.teachers.remove(teacher); } } } Teacher.java @Entity public class Teacher { private int id; private String name; private SetStudent students = new HashSetStudent(); @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(length=10, nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToMany(cascade={CascadeType.REFRESH}, mappedBy=teachers ) public SetStudent getStudents() { return students; } public void setStudents(SetStudent students) { this.students = students; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Teacher other = (Teacher) obj; if (id != other.id) return false; return true; } } ManyToManyTest.java public class ManyToManyTest { @Test public void testPersist(){ EntityManagerFactory emf = Persistence.createEntityManagerFactory(sample); EntityManager em = emf.createEntityManager(); EntityTransaction et = em.getTransaction(); et.begin(); Student student = new Student(); student.setName(student1); Teacher teacher = new Teacher(); teacher.setName(teacher1);
Re: correct way to load persistent metadata at startup
Heather, Have you looked into creating a custom sequence generator[1]? Within the generator, the persistent class and/or fields could be interrogated for annotations and you could generate a value based on them. This is more of a runtime vs. init-time solution, though. Here's an example: package generator; import java.lang.reflect.AccessibleObject; import org.apache.openjpa.jdbc.conf.JDBCConfiguration; import org.apache.openjpa.jdbc.kernel.JDBCStore; import org.apache.openjpa.jdbc.meta.ClassMapping; import org.apache.openjpa.meta.FieldMetaData; public class MyGenerator extends org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq { @Override public JDBCConfiguration getConfiguration() { return null; } @Override protected Object nextInternal(JDBCStore arg0, ClassMapping arg1) throws Exception { FieldMetaData fmd = arg1.getFieldMapping(someField); AccessibleObject fld = (AccessibleObject)fmd.getBackingMember(); MyAnnotation anno = (MyAnnotation)fld.getAnnotation(MyAnnotation.class); // Return the value of the annotation. This will get persisted in the DB column. return anno.value(); } } @Entity @SequenceGenerator(name=myGenerator, sequenceName=generator.MyGenerator()) public class GenValue { @MyAnnotation(FieldValue) @GeneratedValue(generator=myGenerator, strategy=GenerationType.SEQUENCE) public String someField; ... } [1] http://openjpa.apache.org/builds/latest/docs/manual/ref_guide_sequence.html -Jeremy On Fri, May 15, 2009 at 2:06 PM, Kevin Sutter kwsut...@gmail.com wrote: Hi Heather, Interesting use of the OpenJPA metadata processing. Just from your brief description, I would be careful on depending on an implementation versus defined interfaces. Even if we could get this initialization done earlier for you, unless there was some defined mechanism to force this (ie. the openjpa.InitializeEagerly property), I wouldn't count on it. In this particular case, the metadata repository is meant for OpenJPA processing. I know with OpenJPA the lines may not be crystal clear between public API's, provider SPI's, or internal classes. Of course, since this is an open-source project, you are welcome to peruse the complete contents of the code base and see if a solution is doable or not. I would just be careful on being too dependent on a specific implementation. Kevin On Fri, May 15, 2009 at 9:30 AM, Heather Sterling hst...@us.ibm.com wrote: Thanks Kevin. Our scenario is that we have added product-specific annotations to the persistent classes. In particular, we have some annotations that we need in our perPersist entity listener to generate unique identifiers before the object is persisted. We're currently initializing all of the metadata at the beginning. We essentially iterate through the persistent classes and create maps that hold this extra information. I guess it's possible for us to lazily load this data in the entity listener if it hasn't been loaded for a particular class. I also looked to see if there was another hook we could potentially use, but didn't see any that seemed to fit the problem. Heather Sterling Systems Management Development Phone: 919-254-7163 T/L: 444-7163 Cell: 919-423-3143 Email: hst...@us.ibm.com [image: Inactive hide details for Kevin Sutter ---05/12/2009 12:53:30 PM---Heather,] Kevin Sutter ---05/12/2009 12:53:30 PM---Heather, *Kevin Sutter kwsut...@gmail.com* 05/12/2009 12:48 PM Please respond to users To: users@openjpa.apache.org cc: Subject: Re: correct way to load persistent metadata at startup Heather, Good question... :-) This topic has come up recently due to some potential locking issues (serialized access) when reading the metadata repository in a multi-threaded environment. At this point, there is not a clear cut answer for forcing the initialization of the metadata repository. The code for the new openjpa.InitializeEagerly property was committed to trunk last August (after the 1.2.0 release was created), but we've since determined that it may not be complete for all cases. You are welcome to try it out from either the 1.3.x or trunk branches and see if it helps in your particular situation. Let us know what you find out. Also, can you explain your need for getting this data eagerly vs letting the lazy loading process play out? Thanks! Kevin On Mon, May 11, 2009 at 2:40 PM, Heather Sterling hst...@us.ibm.com wrote: I am attempting to load all the persistent class metadata eagerly. I realize this isn't great performance-wise, but I need to do it for the time-being. I had wanted to call: ClassMetaData[] classMetaDatas = conf.getMetaDataRepositoryInstance().getMetaDatas(); but realized the data was loaded lazily when nothing came back. I
Re: Can't query against a MappedSuperclass
Hi Jim, It looks like there are inconsistencies in the manual and provider. I was able use the em.find() operation with a mapped superclass, but could not run a JPQL query which used one. To perform the find operation, OpenJPA queried known entity subclasses of the mapped superclass until it found one that matched the specified ID. I tried using mapped superclasses with the base 1.0 release to make sure this capability hadn't regressed and 1.0 behaved the same. So, it doesn't look like this ever worked with JPQL. Have you taken a look at using entity enheritance and the various entity inheritance strategies? The TABLE_PER_CLASS strategy may map fairly well to a domain model that currently uses mapped superclass over multiple disparate entities. It provides query capabilities over the superclass entity type. I've opened JIRA OPENJPA-1043[1] for this issue. Minimally, the docs should be updated to reflect that mapped superclasses are only supported on a find until such a time they can be supported in a query. -Jeremy [1] https://issues.apache.org/jira/browse/OPENJPA-1043 On Mon, Apr 20, 2009 at 4:33 PM, Fay Wang fyw...@yahoo.com wrote: Hi, According to openjpa manual: Unlike true entities, you cannot query a mapped superclass http://openjpa.apache.org/builds/latest/docs/manual/manual.html#jpa_overview_meta_embeddablesuper --- On Mon, 4/20/09, jim weaver jewea...@us.ibm.com wrote: From: jim weaver jewea...@us.ibm.com Subject: Can't query against a MappedSuperclass To: users@openjpa.apache.org Date: Monday, April 20, 2009, 12:38 PM I have the following: @MappedSuperclass class A { } @Entity class B extends A { } @Entity class C extends A { } and I try to do this type of query: SELECT a FROM A a I receive error message An error occurred while parsing the query filter SELECT a FROM A a. Error message: The name A is not a recognized entity or identifier. Perhaps you meant B, which is a close match. Known entity names: [B, C] A is defined in my persistence.xml and my tables do have the inherited fields from it so I'm pretty sure jpa is recognizing it. The OpenJPA doc says that the query is supported.this is from the 1.2.0 doc: Note OpenJPA allows you to query on mapped superclasses. A query on a mapped superclass will return all matching subclass instances. -- View this message in context: http://n2.nabble.com/Can%27t-query-against-a-MappedSuperclass-tp2665700p2665700.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Can't query against a MappedSuperclass
Hi Fay, The JPA 1.0 and 2.0 draft spec clearly state that this isn't a requirement of JPA, but a note in the OpenJPA documentation (section 1.3) seems to indicate that OpenJPA does support it as an OpenJPA extension. openjpa doc Unlike true entities, you cannot query a mapped superclass, pass a mapped superclass instance to any EntityManager or Query methods, or declare a persistent relation with a mapped superclass target. ...then Note OpenJPA allows you to query on mapped superclasses. A query on a mapped superclass will return all matching subclass instances. OpenJPA also allows you to declare relations to mapped superclass types; however, you cannot query across these relations. /openjpa doc Using a mapped superclass with the em.find() operation over very simple entity subclasses seemed to work fine, but JPQL queries do not. -Jeremy On Tue, Apr 21, 2009 at 11:32 AM, Fay Wang fyw...@yahoo.com wrote: Just found that in JPA 2.0 Proposed Final Draft (March 13, 2009): Spec 2.11.2: A mapped superclass, unlike an entity, is not queryable and cannot be passed as an argument to EntityManager or Query operations. --- On Tue, 4/21/09, Jeremy Bauer techhu...@gmail.com wrote: From: Jeremy Bauer techhu...@gmail.com Subject: Re: Can't query against a MappedSuperclass To: users@openjpa.apache.org Date: Tuesday, April 21, 2009, 8:52 AM Hi Jim, It looks like there are inconsistencies in the manual and provider. I was able use the em.find() operation with a mapped superclass, but could not run a JPQL query which used one. To perform the find operation, OpenJPA queried known entity subclasses of the mapped superclass until it found one that matched the specified ID. I tried using mapped superclasses with the base 1.0 release to make sure this capability hadn't regressed and 1.0 behaved the same. So, it doesn't look like this ever worked with JPQL. Have you taken a look at using entity enheritance and the various entity inheritance strategies? The TABLE_PER_CLASS strategy may map fairly well to a domain model that currently uses mapped superclass over multiple disparate entities. It provides query capabilities over the superclass entity type. I've opened JIRA OPENJPA-1043[1] for this issue. Minimally, the docs should be updated to reflect that mapped superclasses are only supported on a find until such a time they can be supported in a query. -Jeremy [1] https://issues.apache.org/jira/browse/OPENJPA-1043 On Mon, Apr 20, 2009 at 4:33 PM, Fay Wang fyw...@yahoo.com wrote: Hi, According to openjpa manual: Unlike true entities, you cannot query a mapped superclass http://openjpa.apache.org/builds/latest/docs/manual/manual.html#jpa_overview_meta_embeddablesuper --- On Mon, 4/20/09, jim weaver jewea...@us.ibm.com wrote: From: jim weaver jewea...@us.ibm.com Subject: Can't query against a MappedSuperclass To: users@openjpa.apache.org Date: Monday, April 20, 2009, 12:38 PM I have the following: @MappedSuperclass class A { } @Entity class B extends A { } @Entity class C extends A { } and I try to do this type of query: SELECT a FROM A a I receive error message An error occurred while parsing the query filter SELECT a FROM A a. Error message: The name A is not a recognized entity or identifier. Perhaps you meant B, which is a close match. Known entity names: [B, C] A is defined in my persistence.xml and my tables do have the inherited fields from it so I'm pretty sure jpa is recognizing it. The OpenJPA doc says that the query is supported.this is from the 1.2.0 doc: Note OpenJPA allows you to query on mapped superclasses. A query on a mapped superclass will return all matching subclass instances. -- View this message in context: http://n2.nabble.com/Can%27t-query-against-a-MappedSuperclass-tp2665700p2665700.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: how to store collection of enums as strings
Craig, The latest public draft (3/13/2009) of the JPA 2.0 specification defines the ability to apply the Enumeration (also Temporal and Lob) annotation to element collection. Support within OpenJPA trunk will follow in the weeks to come. -Jeremy On Tue, Mar 31, 2009 at 12:04 PM, Craig L Russell craig.russ...@sun.comwrote: I'd like to see a simple way to persist an EnumSet (which if I understand this use case is really what is desired): @Enumerated(STRING) @ElementCollection private EnumSetMyEnum myEnums = new EnumSetMyEnum(); If no volunteers to implement this one (too bad it's not in the specification) then this would be my second choice: @Enumerated(STRING) @ElementCollection private SetMyEnum myEnums = new HashSetMyEnum(); The @Enumerated tells us that you want the String value of the enum to be persisted (not the int value); the @ElementCollection tells us to persist the values individually and not as a serialized blob. Craig On Mar 31, 2009, at 8:46 AM, Jody Grassel wrote: It sounds like you're trying to persist a collection of enumerations as a set of data and not as a reference to other entities, is that correct? If so, wouldn't a combination of @PersistentCollection and Externalization (section 6.6 in the manual) provide the function you are looking for? On Wed, Mar 25, 2009 at 11:48 AM, Tedman Leung ted...@sfu.ca wrote: Anyone know how to store a collection of enums as Strings instead of their ordinal values? (preferably with annotations...) i.e. @ManyToMany private SetMyEnum myEnums=new HashSetMyEnum(); -- Ted Leung ted...@sfu.ca It's time for a new bike when the bulb in your shift light burns out. Craig L Russell Architect, Sun Java Enterprise System http://db.apache.org/jdo 408 276-5638 mailto:craig.russ...@sun.com P.S. A good JDO? O, Gasp!
Re: Is JPA 2 going to have something like JAXBs @XmlJavaTypeAdapter ?
Ryan, I agree, this would be a useful feature to have standardized by the JPA specification. My guess is that it would be too late to try to get something into JPA 2.0, but one could recommend this feature for inclusion in a future version of the spec. Pinaki and Kevin (cc'd) participate in the expert group so they may have recommendations for submitting feature requests. Currently, you can do the conversion yourself within your business logic (or create separate entities or embeddables for the mappings), which can result in an indirect and sometimes quirky OR mapping.. or you can use OpenJPA's @Strategy extension to specify a custom value mapping handler. Here is an example handler for UUID: package strat; import java.util.UUID; import org.apache.openjpa.jdbc.kernel.JDBCStore; import org.apache.openjpa.jdbc.meta.ValueMapping; import org.apache.openjpa.jdbc.meta.strats.AbstractValueHandler; import org.apache.openjpa.jdbc.schema.Column; import org.apache.openjpa.jdbc.schema.ColumnIO; import org.apache.openjpa.meta.JavaTypes; public class UUIDValueHandler extends AbstractValueHandler { public Column[] map(ValueMapping vm, String name, ColumnIO io, boolean adapt) { Column col = new Column(); col.setName(name); col.setJavaType(JavaTypes.STRING); return new Column[]{ col }; } public boolean isVersionable() { return true; } /** * Convert the object value to its datastore equivalent. */ public Object toDataStoreValue(ValueMapping vm, Object val, JDBCStore store) { if (val == null) return null; UUID uuid = (UUID) val; return uuid.toString(); } /** * Convert the datastore value to its object equivalent. */ public Object toObjectValue(ValueMapping vm, Object val) { if (val == null) return null; String uuidStr = (String)val; return UUID.fromString(uuidStr); } } @Entity public class EntityA { ... @Strategy(strat.UUIDValueHandler) private UUID uuid; ... } Using this custom value handler, UUID will be mapped internally to/from a string type. In addition, the schema factory (if used) will create the appropriate database column type(s). The OpenJPA unit test suite has an additional example usage of @Strategy which maps an object to/from multiple database columns. Search for @Strategy in org.apache.openjpa.persistence.jdbc.annotations.NonstandardMappingEntity. hth, -Jeremy On Mon, Mar 30, 2009 at 9:28 AM, Ryan Fogarty rfoga...@adaptivemethods.comwrote: I use @XmlJavaTypeAdapter a lot to manipulate our data model for classes that just don't naturally fit into an XML model (like custom containers and the sort). Seems to be one of the most intuitive and powerful tools in JAXBs toolbox but I can't find anything like it in JPA 1 or 2. For instance, I can't seem to do the simplest thing with JPA such as take a java.util.UUID and have OpenJPA map it into a STRING. It looks like there is no chance of getting this into JPA 2 since they are in final draft. I just can't imagine such a useful tool *not* existing in a powerful API like JPA, so what gives? Have I missed something fundamental? Thank you, Ryan
Re: Questions about classpath for OpenJPA
Hi Paul, For Tomcat related information, you may be able to derive some information from this thread [1]. It began as a data source related issue but got into some configuration issues as well. I've only used Tomcat 5.5 with OpenJPA. I'm not sure about Tomcat 6, but 5.5 did not come with geronimo spec api jars (or equivalents). Here are the OpenJPA bundled jars that I needed to copy into the tomcat/common/lib directory: - openjpa-1.2.0.jar - serp-1.13.1.jar - geronimo-jta_1.1_spec-1.1.jar - geronimo-jpa_3.0_spec-1.0.jar - commons-collections-3.2.jar - commons-lang-2.1.jar You'll also need to make your JDBC driver jar(s) available to your app(s). I added them to common/lib. You may also be able to bundle all these jars in your WAR, but I found it cleaner to make them common libs. You may choose to use JNDI data sources with Tomcat vs. direct configuration. Here is a an article for configuring pooled data sources with Tomcat.[2] Until you make the jump to Tomcat, here is a link for configuring pooled datasources with OpenJPA in a JSE environment using dbcp.[3] JRE 1.5.0_05 is fairly old. I'd try updating to a newer JRE. I'm currently using 1.5.0_15. Just a guess, but something may be relying on parser related updates in newer versions of the JRE. [1] http://n2.nabble.com/Using-datasource-from-tomcat-with-openjpa-tt1449575.html#a1449832 [2] http://www.onjava.com/pub/a/onjava/2006/04/19/database-connection-pooling-with-tomcat.html [3] http://webspherepersistence.blogspot.com/2009/01/jpa-connection-pooling.html hth, -Jeremy On Thu, Mar 19, 2009 at 2:33 PM, Paul Copeland t...@jotobjects.com wrote: I am just getting started and created a simple standalone (not in an app server container) JPA application working with both TopLink and OpenJPA 1.2 and tested with both MySQL and Postgres. This is with Java SE 1.5.0_05 building with Ant (not in in an IDE). By trial and error I found I needed the jar files downloaded in the apache-openjpa-1.2.0 lib directory. I also needed xercesImpl.jar. I did not find these dependencies documented in the release notes, or in the manual, or on the Quickstart page (http://openjpa.apache.org/quick-start.html). These were the necessary jars at either compile time or runtime - commons-collections-3.2.jar commons-lang-2.1.jar geronimo-jpa_3.0_spec-1.0.jar geronimo-jta_1.1_spec-1.1.jar openjpa-1.2.0.jar serp-1.13.1.jar xercesImpl.jar Probably I will also need commons-pool-1.3.jar or something similar for Connection pooling. Presumably the geronimo jars are not needed in a Java 5 EE container. I'm not sure why xerces is required since Java SE 1.5 has a SAX parser. I guess all the other jars need to be deployed in the classpath in most other contexts. This kind of dependency information might be usefully documented somewhere. Every new user has to figure this stuff out. BTW - My target runtime environment will be Tomcat 6 + Java SE 1.6 + OpenJPA 1.2 + Postgres 8.2.x Any experience or advice about what jars are required or is this already documented somewhere? Thanks - Paul
Re: Slow performance with OpenJPA when selecting from a ManyToMany relation.
Hi Shubbis, Does your measurement include the time it takes to create the entity manager factory and/or entity manager or are they created before you execute the find operations? I'm guessing you create the em ahead of time, since the ManyToMany result is atypical. But if so, could you try creating the em before taking measurement? That would factor out any em initialization related issues. Also, which db platform are you using for the tests? -Jeremy On Thu, Mar 12, 2009 at 8:48 AM, Shubbis marius.jo...@broadpark.no wrote: Hi Kevin, Thanks for the reply! We are enhancing the files. I have an Ant script enhancing the files before every run of OpenJPA, so that is not the problem. Although it did give me strange results the first time I tried openjpa and did not enhance ;) -Shubbis Kevin Sutter wrote: Hi Shubbis, Thanks for asking before posting any results... :-) Much appreciated. The first thing that comes to mind is whether you are enhancing your Entities that are used with OpenJPA. For optimal performance, OpenJPA uses a byte-code weaving technique to enhance the Entity objects. This enhancement allows for more efficient interaction between the Entity objects and the OpenJPA runtime. This blog entry explains the various enhancement mechanisms available for an OpenJPA environment (build vs runtime): http://webspherepersistence.blogspot.com/2009/02/openjpa-enhancement.html FYI, if you do not perform the byte-code enhancement either statically at build time or dynamically at runtime, then OpenJPA falls back to a simpler subclassing approach. This subclassing approach is meant for simple out-of-the-box examples, and not for production or performance comparisons. This performance concern becomes especially noticeable with Eager type relationship fetching like it looks your example is doing. Let's start with this enhancement processing. If you are doing enhancement and you are still hitting this performance concern, then we need to dig further because we definitely do not see this type of performance concern when we do our comparisons... :-) Thanks, Kevin On Thu, Mar 12, 2009 at 7:22 AM, Shubbis marius.jo...@broadpark.no wrote: First post so bare with me, and I've search for quite a while and not found any answers. I'm working on a school project where we are testing performance with different ORM's compared to JDBC and I'm having a big issue with OpenJPA when using a ManyToMany relation. We're trying to do a simple select case where we run a for loop with 500 iterations while calling a findById method that returns the instance. Wearhouse instance = getOJPAEntityManager().find(Wearhouse.class, id); This takes roughly 1~ sec on JDBC and 1.2~ EclipseLink while it takes 10+ sec on OpenJPA. This only happens with ManyToMany! We have plenty of insert tests, select tests etc and all of them are much more similar, with openjpa winning and losing a few. Now, I'll gladly admit we dont have to much experience with this, but this strikes me as very odd. So, if anyone has any tips, comments or info I'll be glad to try it out. Thanks in advance! Marius Here are the two entities in question: package project.common.model; import java.util.*; import javax.persistence.*; @Entity public class Wearhouse { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer wearhouseNr; private String wearhouseName; @ManyToMany(cascade={CascadeType.PERSIST}, fetch = FetchType.EAGER) @JoinTable( name=wearhouse_storagecategory, joincolum...@joincolumn(name=wearhouseNr), inversejoincolum...@joincolumn(name=storagecategoryNr) ) private ListStoragecategory storageCategories; public Wearhouse() { } public Wearhouse(String wearhouseName) { this.wearhouseName = wearhouseName; storageCategories = new ArrayListStoragecategory(); } public Integer getWearhouseNr() { return this.wearhouseNr; } public void setWearhouseNr(Integer wearhouseNr) { this.wearhouseNr = wearhouseNr; } public String getWearhouseName() { return this.wearhouseName; } public void setWearhouseName(String wearhouseName) { this.wearhouseName = wearhouseName; } public void setStorageCategories(ListStoragecategory storageCategory){ this.storageCategories = storageCategory; } public ListStoragecategory getStorageCategories(){ return storageCategories; } public void addStorageCategories(Storagecategory storagecategory) {
Re: Slow performance with OpenJPA when selecting from a ManyToMany relation.
Shubbis, Thanks for your reply and for your willingness to give my suggestion a try. My question was mainly to (indirectly) point out that emf em creation is costly (especially emf) and that it could skew results. Since your measurement procedure tosses out high low values, even if you create the em during the first exec in your test cycle the measurement procedure would likely toss out that result. That being the case, creating the em ahead of time should not show any better results. Unless your test suite executes the ManyToMany tests first and reuses that em for all following tests, which, from your description is not the case, other tests should have been similarly affected. But, it may still be worth verifying. What issue did you have with the 1.2.x nightly build? A vote is currently underway to publish a new 1.2.x release soon so please post if you've found a problem. -Jeremy On Thu, Mar 12, 2009 at 2:26 PM, Shubbis marius.jo...@broadpark.no wrote: Hi Jeremy! Our tests get (or create) the em when we begin the measurement. This is done on all the frameworks and all the tests (selects, inserts, updates, deletes, etc.). We then remove the highest and lowest numbers from all the results and gather an average. Should this really be affected? I mean, wouldn't that be a problem on all the selects and not only the ManyToMany if that was the case? Don't get me wrong, I'm going to give it a go, but I just want to make sure our scenario is understood. Also we are using MySQL 5.1. I've also tried to run the test on my local mysql installation and the results are similar, actually a bit slower.. Jeremy Bauer wrote: Hi Shubbis, Does your measurement include the time it takes to create the entity manager factory and/or entity manager or are they created before you execute the find operations? I'm guessing you create the em ahead of time, since the ManyToMany result is atypical. But if so, could you try creating the em before taking measurement? That would factor out any em initialization related issues. Also, which db platform are you using for the tests? -Jeremy On Thu, Mar 12, 2009 at 8:48 AM, Shubbis marius.jo...@broadpark.no wrote: Hi Kevin, Thanks for the reply! We are enhancing the files. I have an Ant script enhancing the files before every run of OpenJPA, so that is not the problem. Although it did give me strange results the first time I tried openjpa and did not enhance ;) -Shubbis Kevin Sutter wrote: Hi Shubbis, Thanks for asking before posting any results... :-) Much appreciated. The first thing that comes to mind is whether you are enhancing your Entities that are used with OpenJPA. For optimal performance, OpenJPA uses a byte-code weaving technique to enhance the Entity objects. This enhancement allows for more efficient interaction between the Entity objects and the OpenJPA runtime. This blog entry explains the various enhancement mechanisms available for an OpenJPA environment (build vs runtime): http://webspherepersistence.blogspot.com/2009/02/openjpa-enhancement.html FYI, if you do not perform the byte-code enhancement either statically at build time or dynamically at runtime, then OpenJPA falls back to a simpler subclassing approach. This subclassing approach is meant for simple out-of-the-box examples, and not for production or performance comparisons. This performance concern becomes especially noticeable with Eager type relationship fetching like it looks your example is doing. Let's start with this enhancement processing. If you are doing enhancement and you are still hitting this performance concern, then we need to dig further because we definitely do not see this type of performance concern when we do our comparisons... :-) Thanks, Kevin On Thu, Mar 12, 2009 at 7:22 AM, Shubbis marius.jo...@broadpark.no wrote: First post so bare with me, and I've search for quite a while and not found any answers. I'm working on a school project where we are testing performance with different ORM's compared to JDBC and I'm having a big issue with OpenJPA when using a ManyToMany relation. We're trying to do a simple select case where we run a for loop with 500 iterations while calling a findById method that returns the instance. Wearhouse instance = getOJPAEntityManager().find(Wearhouse.class, id); This takes roughly 1~ sec on JDBC and 1.2~ EclipseLink while it takes 10+ sec on OpenJPA. This only happens with ManyToMany! We have plenty of insert tests, select tests etc and all of them are much more similar, with openjpa winning and losing a few. Now, I'll gladly admit we dont have to much experience with this, but this strikes me as very odd. So, if anyone has any tips, comments or info I'll
Re: out of memory issues
Adam, Are you using compile time enhancement or does the web container do enhancement? If not, runtime enhancement will be used and I've seen cases where non-agent runtime enhancement can significantly increase memory usage. If you aren't certain, an easy way to check is to disable runtime enhancement via: property name=openjpa.RuntimeUnenhancedClasses value=unsupported/ If your classes are not enhanced, the app will fail with an exception to that effect. -Jeremy On Wed, Jan 28, 2009 at 4:39 AM, Adam Hardy adam@cyberspaceroad.comwrote: Hi Mike, thanks for the input. The child objects are mapped entities and they total around 25 * 300, so 7500. This is their structure: private Long id; private BigDecimal total; private DollarReturn dollarReturn; private TestAnalysis testAnalysis; where DollarReturn and TestAnalysis are also mapped entities. TestAnalysis will have 7500 of these in its child list. They extend a superclass: private Long version; private Long ownerId; private Date created; private Date modified; For what it's worth, they also have several transient properties. I didn't get a heap dump before. Now I have changed the architecture a bit to try to streamline the process, and the process doesn't crash now, it just takes a very long time. Regards Adam Michael Dick on 27/01/09 16:31, wrote: Hi Adam, just some quick thoughts, How many child objects are we talking about, and are they entities or just objects which are persisted to the database? If you have heap dumps it might be interesting to see which object(s) are taking up the most memory. It sounds like the likely culprit is the number of child objects and any OpenJPA objects associated with them. -mike On Mon, Jan 26, 2009 at 11:46 AM, Adam Hardy adam@cyberspaceroad.com wrote: The webapp I am working on uses OpenJPA (or Hibernate depending on bugs blocking progress) and I have just hit a problem that currently looks like it will only be solved by violating the current architecture. I'm hoping I'm wrong and thought I'd ask first. The scenario is that the user can choose a whole range of financial instruments to put in a portfolio, and the webapp grabs them all on submission of the request and builds the object graph. The Manager class which is also the transactional interface then creates an Analysis entity to hold performance stats, and which may create for itself a large number of small child objects representing past performance. When the Analysis is done, the Manager call finishes and the transaction commits (or I commit the transaction in my unit test), and I get an out-of-memory exception. Presumably it's all the child object inserts causing the problem. Obviously I would like to do a flush before I run out of memory, but the Analysis entity object has no access to the entity manager. Or at least it shouldn't have. The other problem is that the Analysis entity can't really be saved until the child objects are all created, so I would have to think of a dirty work-around to allow me to save it first, to allow me to flush the child objects.
Re: out of memory issues
Adam, I've found that if you want to run enhancement on a specific pu you can target it by using the -p parameter with the path to your persistence file suffixed by an anchor followed by the specific pu name. example: java -cp %ENHANCER_PATH% org.apache.openjpa.enhance.PCEnhancer -p META-INF\persistence.xml#OpenJPAPU If you are using the ant variation you should be able to do something similar. -Jeremy On Wed, Jan 28, 2009 at 11:44 AM, Adam Hardy adam@cyberspaceroad.comwrote: I'm now trying the build-time enhancement. My set-up is not playing well with the PCEnhancer. I get this: 158 OpenJPA INFO [main] openjpa.Tool - No targets were given. Running on all classes in your persistent classes list, or all metadata files in classpath directories if you have not listed your persistent classes. Use -help to display tool usage information. Exception in thread main java.util.MissingResourceException: org.apache.openjpa.persistence.PersistenceProductDerivation:java.util.MissingResourceException: Persistence provider org.hibernate.ejb.HibernatePersistence specified in persistence unit Hibernate in META-INF/persistence.xml is not a recognized provider. at org.apache.openjpa.lib.conf.ProductDerivations.reportErrors(ProductDerivations.java:365) at org.apache.openjpa.lib.conf.ProductDerivations.load(ProductDerivations.java:270) at org.apache.openjpa.lib.conf.Configurations.populateConfiguration(Configurations.java:344) at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4438) Is there by some remote chance an undocumented config param to set the persistence unit I want it to look at in my persistence.xml? This is a framework I'm working on which is theoretically JPA-implementation neutral. Adam Hardy on 28/01/09 17:04, wrote: Sorry, didn't mean compile-time enhancement, I was just mindlessly parroting the words I was reading :$ I started off using nothing, making no changes. No javaagent, nada. Now I've upgraded to Java 1.6 and I'm trying to get that working but today's not being very productive. However Java 6 class retransformation certainly sounds hopeful. I do see on my workstation that I still get the warning in my test run that This means that your application will be less efficient than it would if you ran the OpenJPA enhancer. (openjpa) although at least it doesn't tell me what it did with Java 1.5: Additionally, lazy loading will not be available for one-to-one and many-to-one persistent attributes in types using field access; they will be loaded eagerly instead. Jeremy Bauer on 28/01/09 16:35, wrote: Adam, Did you mean runtime enhancement is being used? (Want to make sure I didn't steer you down the wrong path - I don't think so, based on your statement about adding enhancement to the maven build). I'm not sure if 1.6 will help, but it may be worth a shot. (Anyone?) Besides using compile-time enhancement you could also try to configure your web app server to use the agent enhancer. -Jeremy On Wed, Jan 28, 2009 at 9:51 AM, Adam Hardy adam@cyberspaceroad.com wrote: Hi Jeremy, compile-time enhancement is being used. I figured it would have to be something like that. I just upgraded to JDK 1.6 to see if the enhancement provided that way is better, so fingers crossed. Otherwise I'll have to build in the enhancement stage into the maven build and from what it looks like, the current way of doing that hasn't been changed since OpenJPA v0.9.6. regards Adam Jeremy Bauer on 28/01/09 14:35, wrote: Adam, Are you using compile time enhancement or does the web container do enhancement? If not, runtime enhancement will be used and I've seen cases where non-agent runtime enhancement can significantly increase memory usage. If you aren't certain, an easy way to check is to disable runtime enhancement via: property name=openjpa.RuntimeUnenhancedClasses value=unsupported/ If your classes are not enhanced, the app will fail with an exception to that effect. -Jeremy On Wed, Jan 28, 2009 at 4:39 AM, Adam Hardy adam@cyberspaceroad.com wrote: Hi Mike, thanks for the input. The child objects are mapped entities and they total around 25 * 300, so 7500. This is their structure: private Long id; private BigDecimal total; private DollarReturn dollarReturn; private TestAnalysis testAnalysis; where DollarReturn and TestAnalysis are also mapped entities. TestAnalysis will have 7500 of these in its child list. They extend a superclass: private Long version; private Long ownerId; private Date created; private Date modified; For what it's worth, they also have several transient properties. I didn't get a heap dump before. Now I have changed the architecture a bit to try to streamline the process, and the process doesn't crash now, it just takes a very long time. Regards Adam Michael Dick on 27/01/09 16
Re: Entitymanager lookup using JNDI on webshpere
Devu, Apologies. I should have clarified. You can do the lookup from your POJO as long as the POJO method is called from a method of your EJB. example: MYEjb { public void mymethodwhichneedsacachevalue() { CachePOJO.getValue(key); } } CachePOJO { private void initialize() { InitialContext ctx = new InitialContext(); Entitymanger mgr = ctx.lookup(java:comp/env/MyPCJndi); //use mgr to load values from DB. } public String getValue(String key) { // initialize is called if not initialized? ... } } Question - does your cache store a static reference to the entity manager or does it only get used once during initialization? If it is a one time usage, this pattern should work fine. If you need to store the entity manager, this pattern likely will not work. (There are various transaction and thread safety issues to consider.) Alternately, you'll could look up the entity manager upon each usage or switch to an application managed design. -Jeremy On Tue, Jan 13, 2009 at 2:37 AM, devu213 devusm...@gmail.com wrote: Hi Kevin /Jeremy, Thanks for your replies. In the code that you mention, I would have to follow a pattern like this... MYEjb { EntityManager em = null; InitialContext ctx = new InitialContext(); em = (EntityManager)ctx.lookup(java:comp/env/MyPCJndi); public void mymethodwhichneedsacachevalue() { Cache.getValue(key, manager); // the manager is passed to the cache. Don't want this } } CachePOJO { public String getValue(String key, EntityManager manager) { //singleton...uses manager to initialize from database for the first time } } What I really want is CachePOJO { private void initialize() { InitialContext ctx = new InitialContext(); Entitymanger mgr = ctx.lookup(jndinameofmgr); //use mgr to load values from DB. } } Yes, the cache is accessed from an EJB, but I don't want to be passing the manager around. In fact, I have this pattern problem repeatedly because we have DAO classes that always now need to get initialized with the manager which is passed from the EJB class (session facade). I end up having to pass my entitymanager around. In a previous project with hibernate, I remember being able to get the sessions directly from the container using JNDI and they would be bound to a transaction if there was one existing. I want to be able to work with a similar pattern but stumble since the only place I am able to get a manager from right now is inside an EJB which I then have to pass around to lower layers. Thanks in advance. Devu. Jeremy, I don't have an option to go to WAS 7 right now, I will have to live with the fix packs. Will try out the method in Kevin's link. Kevin Sutter wrote: Devu213, Besides Jeremy's references below, I want to be aware of WebSphere's support of OpenJPA. I started to cover this the WebSphere and Java Persistence blog [1], but to cover your specific situation... You are correct that the version shipped with the WebSphere EJB3 Feature Pack was OpenJPA 1.0. But, we have created a service stream for this release in OpenJPA (1.0.x). If any problems are discovered in the 1.0 release, then we can fix them in OpenJPA 1.0.x. This updated version of OpenJPA will then get picked up for WebSphere iFixes and FixPacks. So, you are not stuck with OpenJPA 1.0. It will get updated just like the rest of your WebSphere offering as additional FixPacks are applied. WebSphere v7 shipped a version of 1.2 OpenJPA. This version will get supported via the 1.2.x branch of OpenJPA. You could follow Jeremy's references below to use this newer version of OpenJPA with the EJB3 Feature Pack, but then you no longer have access to the WebSphere extensions that sit on top of the OpenJPA binaries. It is an option though. Good luck, Kevin [1] http://webspherepersistence.blogspot.com/2008/09/support-for-openjpa.html On Mon, Jan 12, 2009 at 10:42 AM, Jeremy Bauer techhu...@gmail.com wrote: Hi devu213, To use JNDI to lookup an EM or EMF in WebSphere app server you can define a class level annotation (or via XML in your ejb module deployment descriptor) on your session bean or servlet and use the name attribute to specify the JNDI name. For example: @Stateless @PersistenceContext(unitName=MyPC, name=MyPCJndi) public class JPABean implements JPALocal, JPARemote { ... @Resource SessionContext sessionCtx; public void beanMethod() { // 1) Lookup via comp/env namespace of the initial/current context EntityManager em = null; InitialContext ctx = new InitialContext(); em = (EntityManager)ctx.lookup(java:comp/env/MyPCJndi); // or 2) Use direct lookup from
Re: Entitymanager lookup using JNDI on webshpere
Hi devu213, To use JNDI to lookup an EM or EMF in WebSphere app server you can define a class level annotation (or via XML in your ejb module deployment descriptor) on your session bean or servlet and use the name attribute to specify the JNDI name. For example: @Stateless @PersistenceContext(unitName=MyPC, name=MyPCJndi) public class JPABean implements JPALocal, JPARemote { ... @Resource SessionContext sessionCtx; public void beanMethod() { // 1) Lookup via comp/env namespace of the initial/current context EntityManager em = null; InitialContext ctx = new InitialContext(); em = (EntityManager)ctx.lookup(java:comp/env/MyPCJndi); // or 2) Use direct lookup from the injected session ctx of the session bean em = (EntityManager)sessionCtx.lookup(MyPCJndi); } Looking up an EntityManagerFactory via @PersistenceUnit works similarly. Notice though, that lookup is via the ENC of the EJB. I don't know how/if global JNDI can be used to get a factory. (Anyone?) So, if you initialize your POJO cache within the context of the EJB, the lookup will work. If you need to initialize the cache outside of a container, Persistence.createEntityManagerFactory should work for you. I'd verify that all of your jars specified in your jar-file entry are available on the classpath of your application. You may need to add the jars to the class path entry in the manifest of your module. Here's an IBM infocenter document that explains how to configure an alternate persistence provider[1]. The key items when using an alternate version of OpenJPA is to make sure you've included all the necessary OpenJPA jars in your application or via shared library and the application classloader is configured to load PARENT_LAST. This allows the OpenJPA jars provided by the application (or shared lib) to be loaded before those provided by the app server. [1] http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.ejbfep.multiplatform.doc/info/ae/ae/tejb_jpa3rdparty.html Hope this helps, -Jeremy On Sat, Jan 10, 2009 at 4:25 AM, devu213 devusm...@gmail.com wrote: Hi Kevin, Thanks for taking interest despite this being a Websphere question. Here is the information that might help: 1. Yes am using the EJB3 featurepack. My server is at version 6.1.0.17 with EJB and Webservices FP installed. 2. The code snippet Persistence.createEntityManager() works on stand-alone even with the jar tags(but fails in the container). 3. I am using the openJPA shipped with Websphere. Having given you the above it looks from your answer that I have erred by not stating my question properly. The issue is, I don't know what name is used to bind the factory and the manager. So the issue is not that I'm not able to lookup but that I don't know the JNDI name to look up and so haven't even tried it. Somehow, I did not find any documentation on the Websphere sites or google. Also on similar lines, I would like to see some documentation on how to override the default openJPA shipped with WAS because I want to be able to use the latest version but the one being picked up by the classloader is always the 1.0 version. Thanks in advance. Kevin Sutter wrote: Hi devu213, Just to clarify... Are you using the EJB3 Feature Pack on top of WebSphere v6.1. Are you using the version of OpenJPA that ships with the Feature Pack, or something newer? It sounds like you are using container-managed persistence (ie. the injection support), so it sounds like you are using the EJB3 Feature Pack. But, I just want to make sure. With the EJB3 Feature Pack, the JNDI lookup of an EntityManager should work as well as the injection support. You mention that you are getting a SAX parser error with your persistence.xml file. Do you get any parsing errors when running OpenJPA standalone? Or, is all of your testing within a container? Can you provide more details on the specific parsing errors you are getting? You should also be able to use application-managed persistence within the Container. Off the top of my head, I'm not aware of any problems with what you are attempting. Unfortunately, I can't highlight anything you're doing incorrectly. If you can provide some additional details, maybe we can help get you running. FYI... Just a reminder. This forum is for questions and issues specific to OpenJPA. Since some of us are intimate with WebSphere, we attempt to help with related WebSphere questions. In this particular case, it sounds like you might be hitting a problem with the EJB Container within WebSphere. We can help with the triage of this case, but we won't be able to resolve the problem with OpenJPA (if it turns out to be a problem with the Container). Thanks, Kevin On Wed, Jan 7, 2009 at 2:40 AM, devu213 devusm...@gmail.com wrote: Hi, I need to lookup an entitymanager using JNDI on
Re: How to configure openjpa logs from inside tomcat (6.0)?
Andrei, If you haven't solved this issue, the simplest way I've found to enable OpenJPA logging within Tomcat is to: 1) add this property to your persistence.xml property name=openjpa.Log value=commons/ 2) create a logging.properties file with the following content and add it to the WEB-INF/classes directory of your war. handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler org.apache.juli.FileHandler.level = ALL org.apache.juli.FileHandler.directory = ${catalina.base}/logs org.apache.juli.FileHandler.prefix = openjpa. java.util.logging.ConsoleHandler.level = ALL java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter # enable SQL logging openjpa.jdbc.SQL.level=ALL OpenJPA should log to a file with a name prefixed with openjpa in the tomcat logs directory. The *.ConsoleHandler.* properties enable logging to the console so you may/may not want to include those. hth, -Jeremy On Tue, Dec 30, 2008 at 9:50 PM, Andrei Tchijov and...@tchijov.com wrote: Sorry if this topic was discussed before (and will be very glad just to get pointer to previous discussion). I am having difficulties with controlling opnejpa logging when it is running inside tomcat (6.0). So far I have tried following: - specifying openjpa.Log property in persistence.xml file, - passing openjpa.Log property(among others) to createEntityManagerFactory(), - adding openjpa. ... .level=... lines to conf/logging.properties file What I want is to be able to see SQL statements (and I can see them when I run my code outside of tomcat), what I got is two messages: ... openjpa.Runtime - Starting OpenJPA 1.2.0 ... openjpa.jdbc.JDBC - Using dictionary class org.apache.openjpa.jdbc.sql.MySQLDictionary. Your advice will be highly appreciated, Andrei Tchijov -- View this message in context: http://n2.nabble.com/How-to-configure-openjpa-logs-from-%22inside%22-tomcat-%286.0%29--tp2094916p2094916.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Help - Single table inheritance not working with one-to-many collection
Hi, I think the problem may be related to the use of MappedSuperclass on the base class. Is your intent to create an entity inheritance hierarchy? (This appears to be the case since you've specified an inheritance type and discriminator.) If so the intent of mapped superclass is to map the superclass persistent information into the subclass entity table. If you want a true inheritance hierarchy you should tag your Test class with @Entity instead of @MappedSuperclass. I haven't verified, but OpenJPA may be getting confused by the @Table annotation on the mapped superclass and is storing both types of entities in a single table. Normally, each entity would map to its own table and that table would contain its persistent information and the persistent information stored in the mapped superclass. Hope this helps, -Jeremy On Fri, Dec 5, 2008 at 7:37 PM, nibbler [EMAIL PROTECTED] wrote: Hi, I'm having trouble with single table inheritance and a one-to-many relationship. Specifically, I have two Entities that subclass from a superclass using single table inheritance. I have another Entity that has a one-to-many relationship with one of the subclasses. Using a simple Query, they behave properly, I get one subclass or the other. But when accessing one of them through the container's one-to-many relationship, I get a collection containing objects of both classes. My classes basically look like this: // This is the superclass. @MappedSuperclass @Table(name=test_table) @Inheritance(strategy=InheritanceType.SINGLE_TABLE @DiscriminatorColumn(name=discriminator) public class Test { @Id @Column name=id_column protected long idColumn; @Basic @Column(name=column_a) protected String columnA; @Basic @Column (name=site_id) protected long siteId; // Here's the link to the containing Entity. @ManyToOne (fetch=FetchType.LAZY) @JoinColumn (name=containing_obj_id) private ContainingObject co; ... } // This is the first child. @Entity @DiscriminatorValue(S) public class TestChild1 extends Test { @Basic @Column (name=column_b) private String columnB; ... } // Second child. @Entity @DiscriminatorValue(D) public class TestChild2 extends Test { // This class doesn't have any unique properties. } // This class contains the one-to-many. public class ContainingObject { ... // This is supposed to map a collection of TestChild1 objects. @OneToMany (mappedBy=co) private SetTestChild1 testChildren = new HashSetTestChild1(); ... } Okay, so let's say I have 3 TestChild1 and 2 TestChild2 rows in test_table for a given ContainingObject. this works: Query q = em.createQuery(select test1 from TestChild1 test1 where containing_obj_id = 100); ListTestChild1 list = (ListTestChild1)q.getResultList(); System.out.println(There are + list.size() + testChild1 objs); // THIS WILL SHOW THERE ARE 3. But this doesn't work: // I've retrieved a ContainingObject 'co' with containing_obj_id of 100. SetTestChild1 children = co.getTestChildren(); System.out.println(There are + children.size() + testChild1 objs); // THIS WILL SHOW all 5. I have tried to put the many to one relationship in the TestChild1 class (just to test) and that didn't work either. What am I missing? Thanks in advance! -- View this message in context: http://n2.nabble.com/Help---Single-table-inheritance-not-working-with-one-to-many-collection-tp1620948p1620948.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: NullPointerException when calling createEntityManager on EntityManagerFactory
Martin, The Animal class is listed as an entity class in the persistence.xml, but it is not annotated (or defined in orm.xml) as an entity. Annotating the entity should correct the problem. I'll open a JIRA to address the NPE, since OpenJPA should be able to handle this condition more appropriately. Also, after I annotated the entity, I needed to use the maven compiler plugin to set the compile source and target to 1.5. You can do that by adding this to your pom, after dependencies: build plugins plugin groupIdorg.apache.maven.plugins/groupId artifactIdmaven-compiler-plugin/artifactId configuration source1.5/source target1.5/target /configuration /plugin /plugins /build -Jeremy On Sat, Dec 6, 2008 at 5:11 AM, Martin Olsen [EMAIL PROTECTED] wrote: Hi. I am receiving a NullPointerException when I try to get an EntityManager in a jUnit test. What am I missing? The attached files is organised like this: pom.xml src/main/java/domain/Animal.java src/test/java/domain/OpenJPATest.java src/test/resources/META-INF/persistence.xml The test is run with `mvn test`. The stacktrace is in the attached file domain.OpenJPATest.txt -- Martin Olsen [EMAIL PROTECTED]
Re: Help - Single table inheritance not working with one-to-many collection
Mike, I think I understand the issue, but I apologize in advance if I've missed your point (again). :-) Tagging a superclass with @Entity and @MappedSuperclass is not typical. MappedSuperclass does not define an entity inheritance hierarchy - it is an strategy to map a table to a class inheritance hierarchy. MappedSuperclass, by definition, will use separate tables for each entity subclass, which is contradictory to the single table inheritance strategy you've defined. Try removing @MappedSuperclass from 'Test'. OpenJPA should determine that Test is an entity superclass of TestChild1 and TestChild2 and that you want single table inheritance (entity state of TestChild1 and TestChild2 stored in the test_table). Discriminator values will be used appropriately. I haven't verified, but if you've tagged Test with @Entity and @MappedSuperclass you may be getting some sort of hybrid behavior. Some things may appear to work, some may not. If you remove @MappedSuperclass (and have Test tagged with @Entity) and it still doesn't work, it sounds like a bug... -Jeremy On Mon, Dec 8, 2008 at 1:51 PM, nibbler [EMAIL PROTECTED] wrote: Hi Jeremy, Thanks for the reply. Ouch, I made a mistake in the code above; the Test class does have the @Entity annotation. The Test superclass should be abstract (didn't fix the problem). Also, I'm not sure I was totally clear in my description, so please allow me to restate. So the problem again is that openjpa is ignoring the single-table inheritance strategy when mapping a one-to-many collection (where the many is using the inheritance). I have an abstract Test superclass and two child classes, TestChild1 and TestChild2. The Test classes share fields 'id' and 'columnA'. They can also map many-to-one with a ContainingObject (yikes another mistake, the 'siteId' field should actually be the containingObjId/containing_obj_id that provides the mapping. Doesn't change the general gist, though). TestChild1 adds a 'columnB' field. I want to use single table inheritance so I have one table in the database. I need a discriminator column, so I add one, 'discriminator': test_table( id long, containing_obj_id long, column_a varchar2(30), column_b varchar2(30), discriminator varchar2(1) ); TestChild1 will use 'S' as it's discriminator value, and TestChild2 will use 'D' (my real classes were using an id column that is null in the case of one class and not null in the other, but openjpa can't use null as a discriminator value so I need to add the column. But that's another matter). Anyway, my understanding of the docs is that I create the Test entity, and then subclass it with the Testchild1 and TestChild2. The Test entity is a MappedSuperclass and controls the inheritance type (single table) and discriminator column. Then I add the discrimator value annotations to the child classes and I should be good. It works fine with Queries, but not with the one-to-many relationship in ContainingObject: I get all of the Test objects in the table for that CO. It seems that openjpa, when getting the TankSource collection from the ContainingObject, is ignoring the inheritance strategy. Thanks again for your reply, -Mike Jeremy Bauer wrote: Hi, I think the problem may be related to the use of MappedSuperclass on the base class. Is your intent to create an entity inheritance hierarchy? (This appears to be the case since you've specified an inheritance type and discriminator.) If so the intent of mapped superclass is to map the superclass persistent information into the subclass entity table. If you want a true inheritance hierarchy you should tag your Test class with @Entity instead of @MappedSuperclass. I haven't verified, but OpenJPA may be getting confused by the @Table annotation on the mapped superclass and is storing both types of entities in a single table. Normally, each entity would map to its own table and that table would contain its persistent information and the persistent information stored in the mapped superclass. Hope this helps, -Jeremy On Fri, Dec 5, 2008 at 7:37 PM, nibbler [EMAIL PROTECTED] wrote: Hi, I'm having trouble with single table inheritance and a one-to-many relationship. Specifically, I have two Entities that subclass from a superclass using single table inheritance. I have another Entity that has a one-to-many relationship with one of the subclasses. Using a simple Query, they behave properly, I get one subclass or the other. But when accessing one of them through the container's one-to-many relationship, I get a collection containing objects of both classes. My classes basically look like this: // This is the superclass. @MappedSuperclass @Table(name=test_table) @Inheritance(strategy=InheritanceType.SINGLE_TABLE @DiscriminatorColumn(name=discriminator) public class Test { @Id @Column name
Geronimo spec API update in progress, may affect trunk build
The Geronimo JPA 2.0 spec API is currently being updated with the JPA 2.0 API updates defined in the latest JSR-317 draft. OpenJPA uses the Geronimo JPA 2.0 API to build OpenJPA 2.0 snapshot/trunk. Corresponding OpenJPA updates need to be made following the Geronimo update, so there will be a period when OpenJPA 2.0 snapshot/trunk builds may fail. I'll post when the update is complete. The 1.x release builds will not be affected. -Jeremy
Geronimo spec API update complete
The Geronimo JPA 2.0 spec API and corresponding OpenJPA updates are complete in trunk. If you have a local trunk build you'll need to use the -U option with maven (ex. mvn -U clean install) to pick up the new snapshot of the Geronimo JPA spec jar, otherwise your build may fail. The JPA 2.0 spec API contains many additions to the standard JPA interfaces; EntityManager, EntityManagerFactory, Query, etc. These new methods are available in OpenJPA trunk, but not yet implemented. Until they are implemented, calling them will result in an UnsupportedOperationException. Please let me know if you run into problems or have questions regarding the update. Back to our regularly scheduled builds... :-) -Jeremy -- Forwarded message -- From: Jeremy Bauer [EMAIL PROTECTED] Date: Wed, Nov 26, 2008 at 6:37 PM Subject: Geronimo spec API update in progress, may affect trunk build To: [EMAIL PROTECTED], users@openjpa.apache.org The Geronimo JPA 2.0 spec API is currently being updated with the JPA 2.0 API updates defined in the latest JSR-317 draft. OpenJPA uses the Geronimo JPA 2.0 API to build OpenJPA 2.0 snapshot/trunk. Corresponding OpenJPA updates need to be made following the Geronimo update, so there will be a period when OpenJPA 2.0 snapshot/trunk builds may fail. I'll post when the update is complete. The 1.x release builds will not be affected. -Jeremy
Re: ArgumentException (Incomplete initialisation of EntityManager)
Hi Yann, Does your test use the same entity manager concurrently on multiple threads? Entity managers are not thread safe by definition. If that is the case, you could try setting openjpa.Multithreaded property to true, but you'll likely run into other state or transaction related issues. It's best to use a unique entity manager on each thread.If you are using separate entity managers, could you post a failing test case and information about your system - specifically OS and the number of CPU cores. -Jeremy On Tue, Nov 25, 2008 at 9:15 AM, Yann Andenmatten [EMAIL PROTECTED] wrote: Hi, We are in the process of testing OpenJPA's performance on large volume. To measure it, we uses junitperf which execute simultaneously the same unit test in separate threads. Some time the test succeeded, some time I get this error (which excludes a configuration problem): 1) testPortfolioType(MultithreadedQueriesTest)openjpa-1.2.0-r422266:683325 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter SELECT e FROM SomeEntity29 e. Error message: The name SomeEntity29 is not a recognized entity or identifier. Perhaps you meant SomeEntity29, which is a close match. Known entity names: [SomeEntity18, SomeEntity19, SomeEntity16, SomeEntity17, SomeEntity14, SomeEntity15, SomeEntity12, SomeEntity13, SomeEntity10, SomeEntity6, SomeEntity11, SomeEntity5, SomeEntity4, SomeEntity3, SomeEntity2, SomeEntity1, Client, SomeEntity20, SomeEntity22, SomeEntity21, SomeEntity24, SomeEntity9, SomeEntity23, SomeEntity26, SomeEntity8, SomeEntity7, SomeEntity25, SomeEntity28, SomeEntity27, SomeEntity29] at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException( AbstractExpressionBuilder.java:118) at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JP QLExpressionBuilder.java:177) [...] As you can see in this particular execution is that SomeEntity29 is not recognized as an entity, but it appears on the known entity names. This lets me think the initialization continued after the error occurs and before the error message is printed. I tried to create and close a dummy EntityManager as proposed in some thread on this mailing list: emf = Persistence.createEntityManagerFactory(myUnit, p); EntityManager em = emf.createEntityManager(); em.close(); Thread.sleep(5000); No success. I also tried to force the initialization of the entities by loading the classes: for (int i=1; i=29; i++) { Class.forName(my.company.SomeEntity+i); } No success too. Any idea how to unsure the proper initialization of the EntityManager before the first query? Yann (Occurred with openJPA 1.2.0 Sybase and Derby databases, sun jdk1.6) • This email and any files transmitted with it are CONFIDENTIAL and intended solely for the use of the individual or entity to which they are addressed. • Any unauthorized copying, disclosure, or distribution of the material within this email is strictly forbidden. • Any views or opinions presented within this e-mail are solely those of the author and do not necessarily represent those of Odyssey Financial Technologies SA unless otherwise specifically stated. • An electronic message is not binding on its sender. Any message referring to a binding engagement must be confirmed in writing and duly signed. • If you have received this email in error, please notify the sender immediately and delete the original.
Re: Using datasource from tomcat with openjpa
Hi Håkon, Try defining a non-jta data source in your persistence.xml. That should correct the problem. You can even use the same data source as you've defined for your jta-data-source name. ex: non-jta-data-sourcejava:comp/env/jdbc/workflowdb/non-jta-data-source -Jeremy On Wed, Nov 5, 2008 at 7:08 AM, Håkon Sagehaug [EMAIL PROTECTED]wrote: Hi I tried to get it to just work on a servlet and have more success here, but have now this problem, when I want to get the transaction in my servlet like this I em.getTransaction().begin(); and error is thrown Caused by: java.sql.SQLException: Unable to obtain a TransactionManager using null. at org.apache.openjpa.jdbc.kernel.TableJDBCSeq.allocateSequence(TableJDBCSeq.java:419) at org.apache.openjpa.jdbc.kernel.TableJDBCSeq.nextInternal(TableJDBCSeq.java:290) at org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:60) ... 33 more Caused by: javax.transaction.NotSupportedException: Unable to obtain a TransactionManager using null. at org.apache.openjpa.ee.AutomaticManagedRuntime.doNonTransactionalWork(AutomaticManagedRuntime.java:306) at org.apache.openjpa.jdbc.kernel.TableJDBCSeq.allocateSequence(TableJDBCSeq.java:415) ... 35 more Caused by: openjpa-1.2.0-r422266:683325 fatal user error org.apache.openjpa.util.InvalidStateException: Could not perform automatic lookup of EJB container's javax.transaction.TransactionManager implementation. Please ensure that you are running the application from within an EJB 1.1 compliant EJB container, and then set the org.apache.openjpa.ManagedRuntime property to at org.apache.openjpa.ee.AutomaticManagedRuntime.getTransactionManager(AutomaticManagedRuntime.java:250) at org.apache.openjpa.ee.AutomaticManagedRuntime.doNonTransactionalWork(AutomaticManagedRuntime.java:304) ... 36 more Caused by: javax.naming.NameNotFoundException: Name TransactionSynchronizationRegistry is not bound in this Context at org.apache.naming.NamingContext.lookup(NamingContext.java:770) at org.apache.naming.NamingContext.lookup(NamingContext.java:140) at org.apache.naming.NamingContext.lookup(NamingContext.java:781) at org.apache.naming.NamingContext.lookup(NamingContext.java:153) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:137) at javax.naming.InitialContext.lookup(InitialContext.java:392) at org.apache.openjpa.ee.RegistryManagedRuntime.getTransactionManager(RegistryManagedRuntime.java:61) at org.apache.openjpa.ee.AutomaticManagedRuntime.getTransactionManager(AutomaticManagedRuntime.java:168) ... 37 more It works fine when I just want to do a db lookup and not involve the transaction manager. Do I need to specify a transaction manager in tomcat as I did with the datasource? cheers, håkon 2008/11/5 Håkon Sagehaug [EMAIL PROTECTED] Hi all, I don't know exactly my problems lies, but think it may be in axis or I'm not sure. Because i got hold of the context in a normail servlet with this code Context initCtx = null; Context envCtx; DataSource ds = null; try { initCtx = new InitialContext(); envCtx = (Context) initCtx.lookup(java:comp/env); ds = (DataSource) envCtx.lookup(jdbc/workflowdb); but when I try the same inside a web service I get this javax.naming.NameNotFoundException: Name java:comp is not bound in this Context So i guess it's something about classloading etc, but the usual solution about same jar files in TOMCTA_HOME/lib and weppAPP/WEB-INF/lib can't be used here since there are noe similar jar files. My enironment is a tomcat 6 and axis2 1.3. cheers, Håkon 2008/11/5 Mani [EMAIL PROTECTED] Hi I am not sure whether you are still facing the issue. if yes i think you can try like this: properties property name=openjpa.ConnectionFactoryName value=jdbc/AMPPARTS / property name=openjpa.Log value=DefaultLevel=INFO,Tool=INFO / property name=openjpa.Sequence value=table(Table=OPENJPA_SEQUENCE_TABLE, Increment=1)/ property name=openjpa.jdbc.Schema value=Administrator/ /properties It worked for me. Try again. All the best. -Mani Håkon Sagehaug wrote: Hi I think you may have to send me all ;). I tried from the beginning with a clean tomcat and axis 2 install, and configured like you said, but still the same problem, so if you could send me what you think I need for getting it to work I would appreciate it cheers, Håkon 2008/11/3 Jeremy Bauer [EMAIL PROTECTED] Are you running a packaged service within the Axis2 app (an .aar archive) or is your service deployed as part of a separate web application? I was able to get an OpenJPA-based Axis2 service to work deployed within a standalone web application. I used Tomcat 5.5, Axis
Re: Using datasource from tomcat with openjpa
You may also need to define a resource reference in your web.xml. This link contains a good example on how to configure and use a data source: http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html. The configuration part is what is important for OpenJPA, since it just looks up the data source via the JNDI name provided in the jta-data-source element (as Mike pointed out). -Jeremy On Mon, Nov 3, 2008 at 9:22 AM, Michael Dick [EMAIL PROTECTED] wrote: Have you tried jta-data-sourcejava:comp/env/jdbc/workflowdb/jta-data-source instead of the property for openjpa.ConnectionFactoryName? -mike On Mon, Nov 3, 2008 at 8:22 AM, Håkon Sagehaug [EMAIL PROTECTED]wrote: Hi all, I've got a axis2 web service that is deployed in tomcat and talk to a database using openjpa. This works fine when I just use the persistent xml to configure my db connection, but now I want to use tomcat to configure the datasource. Here is my set-up persistent.xml persistence-unit name=MyOpenJPa transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider classdemo.hibernate.MyPerson/class properties property name=openjpa.ConnectionFactoryName value=java:comp/env/jdbc/workflowdb / property name=openjpa.Log value=DefaultLevel=INFO, Tool=INFO / property name=openjpa.Sequence value=table(Table=OPENJPA_SEQUENCE_TABLE, Increment=1)/ /properties /persistence-unit In tomcat's service xml I've got this Resource name=jdbc/workflowdb auth=Container type=javax.sql.DataSource maxActive=5 maxIdle=5 maxWait=1 username=name password=password driverClassName=org.postgresql.Driver url=jdbc:postgresql://hostname/Workflows/ I tried to put it into the GlobalNamingResources tag and inside a Context tag using the axis2 as path, but I always get this error back A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property. Does anyone have a good tip on how to get this to work?? cheers, Håkon -- Håkon Sagehaug, Software Developer Parallab, Bergen Center for Computational Science (BCCS) UNIFOB AS (University of Bergen Research Company)
Re: Using datasource from tomcat with openjpa
Are you running a packaged service within the Axis2 app (an .aar archive) or is your service deployed as part of a separate web application? I was able to get an OpenJPA-based Axis2 service to work deployed within a standalone web application. I used Tomcat 5.5, Axis 2-1.4.1 and OpenJPA 1.2.0. I simply added this entry to my tomcat_home/conf/context.xml: Resource name=jdbc/TestDB auth=Container type=javax.sql.DataSource maxActive=20 maxIdle=10 maxWait=1 username=yourusername password=yourpassword driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/testdb?autoReconnect=true/ And referenced the data source in my persistence.xml: persistence-unit name=Tomcat jta-data-sourcejava:comp/env/jdbc/TestDB/jta-data-source classentities.TestData/class /persistence-unit I also added the OpenJPA jar and necessary supporting jars to tomcat_home/common/lib. If you'd like a copy of my .war with source please let me know. The .war contains Axis2 binaries, which are quite large, so I won't post it to the forum. I'd guess using a .aar should work as well (if you happen to be doing that), but the configuration may be different. -Jeremy On Mon, Nov 3, 2008 at 12:20 PM, Jeremy Bauer [EMAIL PROTECTED] wrote: I found this: http://www.experts-exchange.com/Software/Server_Software/Application_Servers/Java/Apache_Tomcat/Q_23207819.html which indicated that you need to create a resource link between the data source you defined in the service.xml and resource ref in the web.xml, by defining this in the context.xml: ResourceLink global=jdbc/workflowdb name=jdbc/workflowdb auth=Container type=javax.sql.DataSource/ -Jeremy On Mon, Nov 3, 2008 at 11:37 AM, Håkon Sagehaug [EMAIL PROTECTED] wrote: Hi when I try to do this programmatically like this Context initCtx = null; Context envCtx; DataSource ds = null; try { initCtx = new InitialContext(); // envCtx = (Context) initCtx.lookup(java:/comp/env); ds = (DataSource) initCtx.lookup(java:comp/env/jdbc/workflowdb); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } propMap.put(openjpa.ConnectionFactory, ds); propMap.put(openjpa.ConnectionFactoryMode, managed); propMap.put(openjpa.FlushBeforeQueries, false); EntityManagerFactory emf = Persistence.createEntityManagerFactory( MyOpenJPa, propMap); I always get javax.naming.NameNotFoundException: Name java:comp is not bound in this Context So I guess this is related, but followed the tomcat doc so I can't understand why this does not work. 2008/11/3 Håkon Sagehaug [EMAIL PROTECTED] Hi I added resource configuration to the web.xml of axis2, and tried also to make a web.xml for the web service but neither of this worked. Any onther tips, it world be realy nice to get this to work for me cheers, Håkon 2008/11/3 Jeremy Bauer [EMAIL PROTECTED] You may also need to define a resource reference in your web.xml. This link contains a good example on how to configure and use a data source: http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html . The configuration part is what is important for OpenJPA, since it just looks up the data source via the JNDI name provided in the jta-data-source element (as Mike pointed out). -Jeremy On Mon, Nov 3, 2008 at 9:22 AM, Michael Dick [EMAIL PROTECTED] wrote: Have you tried jta-data-sourcejava:comp/env/jdbc/workflowdb/jta-data-source instead of the property for openjpa.ConnectionFactoryName? -mike On Mon, Nov 3, 2008 at 8:22 AM, Håkon Sagehaug [EMAIL PROTECTED]wrote: Hi all, I've got a axis2 web service that is deployed in tomcat and talk to a database using openjpa. This works fine when I just use the persistent xml to configure my db connection, but now I want to use tomcat to configure the datasource. Here is my set-up persistent.xml persistence-unit name=MyOpenJPa transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider classdemo.hibernate.MyPerson/class properties property name=openjpa.ConnectionFactoryName value=java:comp/env/jdbc/workflowdb / property name=openjpa.Log value=DefaultLevel=INFO, Tool=INFO / property name=openjpa.Sequence value=table(Table=OPENJPA_SEQUENCE_TABLE, Increment=1)/ /properties /persistence-unit In tomcat's service xml I've got this Resource name=jdbc/workflowdb auth=Container type=javax.sql.DataSource maxActive=5 maxIdle=5 maxWait=1 username=name password=password driverClassName=org.postgresql.Driver url=jdbc:postgresql://hostname/Workflows
Re: JPA 2.0 development plans...
Hi Adam, There is no list that I know of, yet. OpenJPA trunk is primed for 2.0 development and 2.0 planning will begin shortly, including a call for participation. I agree, part of the planning process needs to include mapping existing OpenJPA functionality to the corresponding function in JPA 2.0. There is a public draft of JSR-317 available for review at http://jcp.org/aboutJava/communityprocess/edr/jsr317/. If you (and others) would like to contribute to this effort, that would be fantastic. I've opened a JIRA task https://issues.apache.org/jira/browse/OPENJPA-757 for this piece of work, for now. As JPA 2.0 development gets underway lets take advantage of the wiki and other tools to better manage, document, and organize the effort. -Jeremy On Fri, Oct 31, 2008 at 4:57 AM, Adam Hardy [EMAIL PROTECTED] wrote: Is there a list of new JPA 2.0 spec features which are already covered by existing OpenJPA features? Such as @Dependent or @OrderColumn ? On Sep 30, 2008, at 9:10 AM, Kevin Sutter wrote: Due to the upcoming JPA 2.0 development activities, the OpenJPA svn repository needs to make a few changes. Since the JPA 2.0 changes could be disruptive to current JPA 1.0 processing (at least during initial development), I would like to create a 1.3.x service branch. This 1.3.x branch would indicate the end of new development based on the JPA 1.0 specification. This 1.3.x branch could be used for any necessary support activities (or even a potential release, if necessary), but the mainline trunk would now become the basis for JPA 2.0 development (2.0.0-SNAPSHOT). All new development activity would continue in trunk, just like the past. But, we would also have the ability to start experimenting with some of the new features that have been identified in the early drafts of the JPA 2.0 specification. Granted, we only have the single Early Draft Review version of the JPA 2.0 spec, but it's at least a start. Even if we have to modify a few things along the way, at least we're getting experience with the new specification. And, we can initiate a roadmap for the new features and hopefully encourage new participation by the diverse OpenJPA community. We need to determine the best date for this cutover. Since I'm not sure on the current development activities of the OpenJPA developers, let's use this thread for the discussion. Since the end of Sept is fast approaching, let's shoot for Friday, Oct 31 as the cutover date. Comments or suggestions are welcome!
Re: OpenJPA on WebSphere
Hi Robert, Thanks for posting your ear file and the word doc. I was able to use it to reproduce the problem with DB2 and Derby and as you've seen, strangely, the application works fine with Oracle. The culprit is the use of TransactionAttribute.REQUIRES_NEW on BankAccountsBean.UpdateCheckingBalance(). If you comment out @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) on that method the EJB operations will complete successfully. This gets around the issue, but may not provide the transactional behavior you intend. I haven't yet determined how the application, server, and DB is supposed to behave using the set of transaction attributes you've defined for the application logic, but as we've seen, there's definitely an issue. I'll post as I find out more. -Jeremy On Wed, Oct 29, 2008 at 10:17 PM, rjack [EMAIL PROTECTED] wrote: Folks, 1) The test connection works with all datasources. I did notice it wasn't connecting on all IP addresses. I fixed that, but it's still not working. 2) I couldn't get MS SQL Server to work either. I'm using SQL Server Express which might be part of the problem. It did work as Derby did on Weblogic. 3) I'm going to attach some pictures of the WebSphere setup. Robert Jackson Michael Dick wrote: Hi Robert, Quick question, does the test connection button on the WebSphere GUI work for the Derby and MS SQL datasources? If test connection works, then OpenJPA should have no trouble getting a connection.. --mike On Wed, Oct 29, 2008 at 2:29 PM, Kevin Sutter [EMAIL PROTECTED] wrote: RJack, From what you are telling me, things should be working... :-) It sounds like you are creating an appropriate j2c component authentication alias. I verified that this should be used even with a global jndi lookup of the datasource. Setting custom properties on the datasource is another alternative, but should not be required. Maybe a trace of the failure would help? Or, even to start with, the SystemOut.log that shows the error. Also, what did you do to get SQLServer to work? Thank you for your patience, Kevin On Wed, Oct 29, 2008 at 11:31 AM, rjack [EMAIL PROTECTED] wrote: Kevin, I'm attaching the EAR I'm using in WebSphere. I am defining a datasource with that name, JavaTranDerby. In both cases of Derby and Oracle, Im creating a login/password using J2C Authentication data and setting the login for XA Recovery and authentication for component management. I wonder if I need to set custom properties for Derby. In networked mode it seems to want a userId and Password even if they are fake. I can access Derby on the WebSphere server remotely using DBvisualizer with no problem. I tried the jars that come with WAS 7 and also the 10.4 Derby jars. Robert http://n2.nabble.com/file/n1394204/Transaction.ear Transaction.ear Kevin Sutter wrote: RJack, According to your persistence.xml file, you are attempting to use a jta-data-source: - # persistence-unit name=*TransactionEJBPU* transaction-type=*JTA* jta-data-sourceJavaTranDerby/jta-data-source /persistence-unit This indicates that you need to have a DataSource configured at the jndi name of JavaTranDerby. Do you? Normally, customers would preface the global Datasource jndi names with jdbc/, but that's not a hard requirement. If you have configured this datasource in WebSphere with that jndi name, then OpenJPA should be able to find it. And, if you do have it configured in WebSphere, then all of the login information should be configured on that datasource. If you use the jta-data-source element, then no additional datasource configuration properties will be used. If you do not plan to or want to configure a datasource in WebSphere for the jndi look, then you will need to configure datasource configuration properties in your persistence.xml file. I am very surprised that this same configuration worked just fine with WegLogic. Did you have the jndi name for the datasource configured in WebLogic? Or, did you have to provide some configuration parameters to get around the datasource access? Now, a few other observations. The TransactionEAR.jar is not a normal .ear file. It looks to be an Eclipse project (or possibly some other IDE). Correct? It only contains source files. And, it doesn't seem to follow normal .ear file formatting. For example, the META-INF directory is located in a src directory. This would not be a normal location to search for a persistence.xml file. Can you provide the actual .ear file that you are attempting to install and use? I also see the jpa.reveng.xml file which seems to indicate that maybe this project started with Hibernate and you are now moving to OpenJPA? Is that the case? Just curious since OpenJPA is always interested in
Re: Inconsistent Autocommit Handling
Hi Paul, The RelaxAutoCommit option appears to only allow transactional methods to be called if a connection is not transactional. From what I read, it does not change the auto-commit value. By default, auto-commit is true for a connection per the JDBC spec. I could have missed something, but I did not see a MySQL connection property to change the default for auto-commit. When OpenJPA gets a connection it receives whatever auto-commit value is set on the connection. OpenJPA will however, set auto-commit to false, if necessary, when you start a new transaction via tx.begin(). It will then change it back to the original value after a commit or rollback. IMHO, I don't think the two scenarios are bugs. -Jeremy
Re: Can't Create Tables
Hi Doug, By setting openjpa.jdbc.SynchronizeMappings property to the value you've specified, the schema should be created for you. You could try enabling OpenJPA trace to see if there are any messages in the log that may show whether there was a problem during the the schema creation process. There also could be a schema mismatch or other config issue. The trace may help determine that as well. Full trace can typically be enabled with the following property, unless Geronimo overrides the default trace facility/configuration. property name=openjpa.Log value=DefaultLevel=TRACE/ -Jeremy
Re: Problem with persist a object
Hi Thiago, If the entity cliente is managed by another instance of an entity manager manager you will see this exception. Make sure you either close (or clear, if you reuse the entity manager) any other entity managers that may have managed this entity. Closing the entity manager will put cliente in a detached state, allowing you to merge it into a new persistence context. I don't know exactly how faces is implemented, but from the stack trace it appears to be using a servlet. Servlets are typically a singleton, so you could be hitting a concurrency issue, where multiple clients are calling persistir() and using the cliente entity at the same time. As a simple test, you could synchronize persistir() to see if that solves the problem. Although, I wouldn't recommend that as a long term solution since it may cause a severe performance problem. -Jeremy
Re: having issues with first query.
Hi Fernando, Is TeamFan also defined as an entity and is there an inheritance strategy defined for the Fan - TeamFan hierarchy? If not, you'll need to make sure you have a valid JPA inheritance hierarchy strategy. If this is the case, could you post your entity classes or even better, a failing test case? -Jeremy
Re: having issues with first query.
Hi Fernando, I'm glad to see you got the code working. I was a bit off on my first comments/assumptions. I assumed that TeamFan was a subclass of Fan. Posting your entities and taking a closer look at your statement text cleared that up. I was just about to suggest that you need to specify 1) a relationship (OneToOne or ManyToOne) with FAN_JDOID as the join column or 2) tag Fan as embeddable; when I noticed your reply. It sounds like the Kodo behavior maps to option 1). I can't think of any shortcuts to automatically trigger the ManyToOne relationship. -Jeremy
Re: Trouble with Constructor Expressions
Hi there, According to the JPA spec, section 2.1: The entity class must have a no-arg constructor. The entity class may have other constructors as well. The no-arg constructor must be public or protected. If you don't have one, try adding a default constructor to ConfExtended. That should correct the issue. If you are using the compile-time PCEnhancer it should add a default constructor for you by default (-adc option), which would indicate there is a different problem. -Jeremy
Re: Trouble with Constructor Expressions
Roops.. I missed the key statement: The constructed object, which is not an entity, ... :-) I haven't verified, but there could be a problem with using the int primitives (non-nullable) on the constructor. Changing them to Integer (nullable) may correct the problem. I'll try a few variations as well. -Jeremy
Re: How to annotate a positional List
Kevin, I opened JIRA OPENJPA-743 (https://issues.apache.org/jira/browse/OPENJPA-743) for the issue you discovered where an OptimisticLockException is thrown when the Lob field was not being set. Apparently, when statement batching is enabled, Oracle does not like the mix of parameter types/values OpenJPA provides for null vs. non-null Lob fields. I'll look into the issue and hope to resolve it soon. Until a fix is available, if you need to store null values in a Lob field you may need to disable statement batching. The JIRA has details for disabling statement batching. -Jeremy
Re: How to annotate a positional List
Hi Kevin, Thanks for posting new code. This last set of code explains why I didn't see the updates. My test used the same entity manager throughout, while the code above creates a new EM for the remove operation. I also saw the updates using the code above, but only if I used runtime entity enhancement (on by default in 1.2.0). When I used the javaagent or build-time enhancer, I no longer saw the updates. OpenJPA can do a better job of tracking state with build time or javaagent enhanced entities. In regards to the double update operation, check to see if the last update is really an update. By default, OpenJPA does statement batching with Oracle so the last update entry you are be seeing may look like a duplicate, but in fact it is simply a report that the full batch update is being executed: For example: (batch two statements, then execute - the execute looks like a duplicate update) 4548 MapPU TRACE [main] openjpa.jdbc.SQL - t 26506390, conn 1309601 batching prepstmnt 8546123 UPDATE ORAUSER.PAGEOFBOOK SET DATA = ? WHERE ID = ? [params=(Reader) [EMAIL PROTECTED], (long) 120] 4548 MapPU TRACE [main] openjpa.jdbc.SQL - t 26506390, conn 1309601 [0 ms] spent 4548 MapPU TRACE [main] openjpa.jdbc.SQL - t 26506390, conn 1309601 batching prepstmnt 8546123 UPDATE ORAUSER.PAGEOFBOOK SET DATA = ? WHERE ID = ? [params=(Reader) [EMAIL PROTECTED], (long) 123] 4548 MapPU TRACE [main] openjpa.jdbc.SQL - t 26506390, conn 1309601 [0 ms] spent 4548 MapPU TRACE [main] openjpa.jdbc.SQL - t 26506390, conn 1309601 executing batch prepstmnt 8546123 UPDATE ORAUSER.PAGEOFBOOK SET DATA = ? WHERE ID = ? [params=(Reader) [EMAIL PROTECTED], (long) 123] In short, make sure you are using the build-time or javaagent enhancer and if you still see updates check the last update to see if it says executing batch prepstmt vs. batching prepstmt. -Jeremy
Re: How to annotate a positional List
Until a standardized method for ordered lists is defined by the spec, the org.apache.openjpa.persistence.jdbc.OrderColumn annotation (in possibly combination with other OpenJPA specific collection annotations) may be an option. Take a look at the unit test openjpa-persistence-jdbc\src\test\java\org\apache\openjpa\persistence\jdbc\annotations\NonstandardMappingEntity.java for example usage. -Jeremy
Re: How to annotate a positional List
Hi Kevin. I'm glad to see OrderColumn may work for you. There's a small bug in the code above that is causing the optimistic lock exception. PageOfBook p3 = new PageOfBook(); p3.setData(This is a page 3 in a book); PageOfBook p4 = new PageOfBook(); p3.setData(This is a page 4 in a book); Notice that the second setData is on p3 instead of p4. After I changed it to p4, the test ran OK. I'm not sure why this is resulting in an optimistic lock exception since that seems a bit misleading. It looks to be directly related to having null data in your lob data field though. I'll take a closer look and possibly open a JIRA. -Jeremy
Re: How to annotate a positional List
Hi Kevin, I was surprised to see updates in your SQL output, since you are simply adding and removing entries from the list. My test (also using OpenJPA 1.2.0) did not produce any update statements, only inserts and deletes. From the SQL appears that the data field is changing between commits? If you could post a new version of your test code, that may help - including entity classes, if those have changed. Also, do you have any extra Oracle dictionary related or other openjpa properties beyond the standard datasource config properties in your persistence.xml? PS, I haven't dug into the optimistic lock exception yet. I'll post as soon as I have any details. -Jeremy
Re: Data cache weirdness
Hi David. I'm am unable to reproduce the problem with the relationship definitions provided. Can you provide the entire entities? If you can provide a failing test case, that would be ideal. Also, which version of OpenJPA are you using? -Jeremy