Re: Select aliases not working in OpenJPA 1.2.1
Hi, I am trying a similar JPQL: select c.name, count(distinct d) as od from Corporation c, IN(c.divisions) d group by c.name order by od In the trunk level code, it works fine. The generated SQL is: SELECT t0.CORPORATION_NAME, COUNT(DISTINCT t1.ID) AS od FROM user318.CORPORATION t0 INNER JOIN user318.DIVISION t1 ON t0.ID = t1.CORPORATION_ID GROUP BY t0.CORPORATION_NAME ORDER BY od ASC The same JPQL, when running against openjpa 1.2.x, throws the exception as you reported. Removing the alias as you suggested: select c.name, count(distinct d) from Corporation c, IN(c.divisions) d group by c.name order by count(distinct d) The generated SQL is: SELECT t0.CORPORATION_NAME, COUNT(DISTINCT t1.ID), COUNT(DISTINCT t1.ID) FROM user318.CORPORATION t0 INNER JOIN user318.DIVISION t1 ON t0.ID = t1.CORPORATION_ID GROUP BY t0.CORPORATION_NAME ORDER BY COUNT(DISTINCT t1.ID) ASC The generated SQL has the order by clause, supposedly the result should be ordered. Can you turn on the openjpa trace to see what sql is generated? Regards, Fay - Original Message From: Christopher Giblin c...@zurich.ibm.com To: users@openjpa.apache.org Sent: Mon, October 11, 2010 7:36:42 AM Subject: Select aliases not working in OpenJPA 1.2.1 Hi, I am using the following OpenJPA version in an Eclipse RCP app: OpenJPA 1.2.1 version id: openjpa-1.2.1-r2180:4612 I receive errors when using aliases in a select statement: Example: select s.name, count(distinct g) as c from Systems s, IN(s.groups) g group by s.name order by c Error msg: Encountered as at character 34, but expected: [,, FROM].by c When I drop the alias and order by the count, as in the following example, select s.name, count(distinct g) from Systems s, IN(s.groups) g group by s.name order by count(g) the query is executed but the result is not ordered properly. Is this due to the use of distinct in the query, but not the ORDER? According to the query syntax, distinct cannot be used with ORDER. Is the use of aliases in the select as I describe here part of JPA 2.0 and therefore not supported in my OpenJPA 1.2.1? If so, what any suggestions on how to order on count of a distinct attribute? Thanks, Chris
Re: @OneToMany list object problem with IDENTITY keys
Hi, I am able to see the problem you reported. Note that em.merge(entity) returns a managed object and Verfahrenstatus gets merged internally/implicitly by OpenJPA along with Verfahrendokument. It appears that OpenJPA fail to set the Id for Verfahrenstatus after merge. I will investigate further for the resolution of this problem. Fay - Original Message From: mpf mrkspfeif...@gmail.com To: users@openjpa.apache.org Sent: Wed, September 29, 2010 7:01:35 AM Subject: Re: @OneToMany list object problem with IDENTITY keys At least someone can tell me if im going right that the ID had to be set? -- View this message in context: http://openjpa.208410.n2.nabble.com/OneToMany-list-object-problem-with-IDENTITY-keys-tp5583159p5584026.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: @OneToMany list object problem with IDENTITY keys
Hi, As mentioned in the email below, em.merge() returns a managed object. Since Verfahrenstatus gets merged internally by OpenJPA, not explicitly by the API call, the application can not get the merged object for Verfahrenstatus immediately after the em.merge call. The workaround is to comment out em.merge() and immediately call commit as shown below. That way, the id for s1 will be set. Verfahrendokument d1 = em.find(Verfahrendokument.class, did); em.getTransaction().begin(); Verfahrenstatus s1 = new Verfahrenstatus(); s1.setVerfahrendokument(d1); s1.setStatus(2); d1.addStatus(s1); //em.merge(d1); em.getTransaction().commit(); Regards, Fay - Original Message From: Fay Wang fyw...@yahoo.com To: users@openjpa.apache.org Sent: Wed, September 29, 2010 9:57:28 AM Subject: Re: @OneToMany list object problem with IDENTITY keys Hi, I am able to see the problem you reported. Note that em.merge(entity) returns a managed object and Verfahrenstatus gets merged internally/implicitly by OpenJPA along with Verfahrendokument. It appears that OpenJPA fail to set the Id for Verfahrenstatus after merge. I will investigate further for the resolution of this problem. Fay - Original Message From: mpf mrkspfeif...@gmail.com To: users@openjpa.apache.org Sent: Wed, September 29, 2010 7:01:35 AM Subject: Re: @OneToMany list object problem with IDENTITY keys At least someone can tell me if im going right that the ID had to be set? -- View this message in context: http://openjpa.208410.n2.nabble.com/OneToMany-list-object-problem-with-IDENTITY-keys-tp5583159p5584026.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JPA genereates non-exist id column in the select statement
Hi, Making the superclass an embeddable should not prevent it from being subclassed by other entities. Regards, Fay - Original Message From: llchen llc...@sympatico.ca To: users@openjpa.apache.org Sent: Tue, July 13, 2010 3:42:26 AM Subject: Re: JPA genereates non-exist id column in the select statement Thanks for your suggestion, I will try that embedable option. But that second entity VoVariableData actually is a super class for onother three entities. If I make that one into a embedable, then the other three will not be able to subclass from it. Lule -- View this message in context: http://openjpa.208410.n2.nabble.com/JPA-genereates-non-exist-id-column-in-the-select-statement-tp5282960p5286901.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JPA genereates non-exist id column in the select statement
You can try @PersistentCollection - Original Message From: llchen llc...@sympatico.ca To: users@openjpa.apache.org Sent: Tue, July 13, 2010 10:22:57 AM Subject: Re: JPA genereates non-exist id column in the select statement Sorry I forgot to mention that I am using JPA 1.0 and therefore I can't use @ElementCollection tag. Lule -- View this message in context: http://openjpa.208410.n2.nabble.com/JPA-genereates-non-exist-id-column-in-the-select-statement-tp5282960p5288555.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JPA genereates non-exist id column in the select statement
Since the underlying table does not have primary key, you might want to make VoParagraphData an embeddable: @Embeddable public class VoParagraphData implements Serializable { In the VoDocumentTemplateGroupObjectData, you can make the collection of VoParagraphData an ElementCollection: @ElementJoinColumn(name=PARA_VNBR,referencedColumnName=DTG_OBJ_VNBR)}) @ElementCollection @CollectionTable(name=TPARA, joinColumns={ @JoinColumn(name=PARA_ID, referencedColumnName=DTG_OBJ_ID), @JoinColumn(name=PARA_VNBR, referencedColumnName=DTG_OBJ_VNBR) } ) protected CollectionVoParagraphData paraObjects; - Original Message From: llchen llc...@sympatico.ca To: users@openjpa.apache.org Sent: Mon, July 12, 2010 3:51:45 PM Subject: RE: JPA genereates non-exist id column in the select statement Thanks for promptly replying. But how do I handle the entity without a primary key as the underline table does not have one? Set up a fake primary key in the entity or what? Lule _ From: Rick Curtis [via OpenJPA] [mailto:ml-node+5283244-1458393612-586...@n2.nabble.com] Sent: Monday, July 12, 2010 10:53 AM To: llchen Subject: Re: JPA genereates non-exist id column in the select statement Section 2.4 of the 2.0 spec states Every entity must have a primary key. I seem to remember that OpenJPA will do some magic when we enhance your Entities if we don't find an @Id column... I don't have time to try this am, but I'd be willing to bet that is what's going on. tht, Rick _ View message @ http://openjpa.208410.n2.nabble.com/JPA-genereates-non-exist-id-column-in-th e-select-statement-tp5282960p5283244.html To unsubscribe from JPA genereates non-exist id column in the select statement, click (link removed) aGVuQHN5bXBhdGljby5jYXw1MjgyOTYwfDIzMDMwNjc3MQ== here. -- View this message in context: http://openjpa.208410.n2.nabble.com/JPA-genereates-non-exist-id-column-in-the-select-statement-tp5282960p5285218.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JPA genereates non-exist id column in the select statement
Sorry, I have mistakenly copied and pasted the wrong annotations for the collection of VoParagraphData. Here is the correct annotation for it: @ElementCollection @CollectionTable(name=TPARA, joinColumns={ @JoinColumn(name=PARA_ID, referencedColumnName=DTG_OBJ_ID), @JoinColumn(name=PARA_VNBR, referencedColumnName=DTG_OBJ_VNBR) } ) protected CollectionVoParagraphData paraObjects; - Original Message From: Fay Wang fyw...@yahoo.com To: users@openjpa.apache.org Sent: Mon, July 12, 2010 4:09:31 PM Subject: Re: JPA genereates non-exist id column in the select statement Since the underlying table does not have primary key, you might want to make VoParagraphData an embeddable: @Embeddable public class VoParagraphData implements Serializable { In the VoDocumentTemplateGroupObjectData, you can make the collection of VoParagraphData an ElementCollection: @ElementJoinColumn(name=PARA_VNBR,referencedColumnName=DTG_OBJ_VNBR)}) @ElementCollection @CollectionTable(name=TPARA, joinColumns={ @JoinColumn(name=PARA_ID, referencedColumnName=DTG_OBJ_ID), @JoinColumn(name=PARA_VNBR, referencedColumnName=DTG_OBJ_VNBR) } ) protected CollectionVoParagraphData paraObjects; - Original Message From: llchen llc...@sympatico.ca To: users@openjpa.apache.org Sent: Mon, July 12, 2010 3:51:45 PM Subject: RE: JPA genereates non-exist id column in the select statement Thanks for promptly replying. But how do I handle the entity without a primary key as the underline table does not have one? Set up a fake primary key in the entity or what? Lule _ From: Rick Curtis [via OpenJPA] [mailto:ml-node+5283244-1458393612-586...@n2.nabble.com] Sent: Monday, July 12, 2010 10:53 AM To: llchen Subject: Re: JPA genereates non-exist id column in the select statement Section 2.4 of the 2.0 spec states Every entity must have a primary key. I seem to remember that OpenJPA will do some magic when we enhance your Entities if we don't find an @Id column... I don't have time to try this am, but I'd be willing to bet that is what's going on. tht, Rick _ View message @ http://openjpa.208410.n2.nabble.com/JPA-genereates-non-exist-id-column-in-th e-select-statement-tp5282960p5283244.html To unsubscribe from JPA genereates non-exist id column in the select statement, click (link removed) aGVuQHN5bXBhdGljby5jYXw1MjgyOTYwfDIzMDMwNjc3MQ== here. -- View this message in context: http://openjpa.208410.n2.nabble.com/JPA-genereates-non-exist-id-column-in-the-select-statement-tp5282960p5285218.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Missing table name in query
Hi, Which version of OpenJPA are you using? Using the trunk level code, I got the generated SQL as: 4306 testSubquery TRACE [main] openjpa.Query - Executing query: [select o from Role as o where (lower(o.name) like :search or lower(o.printCode) like :search) and o.id not in (select j.id from JobGroup as jg join jg.jobs as j where jg.id = :jgId )] with parameters: {jgId=1, search=search} 4396 testSubquery TRACE [main] openjpa.jdbc.SQL - t 21868771, conn 26596606 executing prepstmnt 9449509 SELECT t3.id, t3.name, t3.printCode, t3.ts FROM Role t3 WHERE ((LOWER(t3.name) LIKE ? ESCAPE '\' OR LOWER(t3.printCode) LIKE ? ESCAPE '\') AND NOT (t3.id IN (SELECT t2.id FROM JobGroup t0 INNER JOIN jobgroupsjobs t1 ON t0.jobgroupid = t1.jobgroupid INNER JOIN Role t2 ON t1.jobid = t2.roleid WHERE (t0.id = ?) ))) [params=(String) search, (String) search, (int) 1] - Original Message From: Daryl Stultz da...@6degrees.com To: OpenJPA User List users@openjpa.apache.org Sent: Tue, July 6, 2010 8:45:54 AM Subject: Missing table name in query Hello, I've got the following query (roles and jobs are the same thing): select o from Role as o where (lower(o.name) like :search or lower(o.printCode) like :search) and o.id not in ( select j.id from JobGroup as jg join jg.jobs as j where jg.id = :jgId ) I'm looking for Roles that match the search criteria but are not already members of a particular JobGroup.jobs. The IN phrase produces this SQL: AND 0 = (SELECT COUNT(*) FROM WHERE (t0.roleid IN ( SELECT t3.roleid FROM public.jobgroups t1, public.jobgroupsjobs t2, public.roles t3 WHERE (t1.jobgroupid ?) AND t1.jobgroupid = t2.jobgroupid AND t2.jobid = t3.roleid Notice the table name is missing from the count(*) query. Here is the mapping for JobGroup.jobs: @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = jobgroupsjobs, joinColumns = { @JoinColumn(name = jobgroupid, referencedColumnName = jobgroupid) }, inverseJoinColumns = { @JoinColumn(name = jobid, referencedColumnName = roleid) } ) private ListRole jobs = new ArrayListRole(0); Is there a problem with my query, mapping or is this a bug? Thanks. -- Daryl Stultz _ 6 Degrees Software and Consulting, Inc. http://www.6degrees.com http://www.opentempo.com mailto:daryl.stu...@opentempo.com
Re: Mapping different Embedded of the same type to the same table
Hi, You can use @AttributeOverride to override the mapping of an embeddable field. http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/jpa_overview_mapping_field.html#jpa_overview_mapping_embed Fay - Original Message From: stlecho stle...@gmail.com To: users@openjpa.apache.org Sent: Fri, June 18, 2010 7:41:27 AM Subject: Mapping different Embedded of the same type to the same table Hi, I would like to map 2 Embedded properties with the same Embeddable to the same table. When using underneath shown config, OpenJPA generates an InvalidStateException (see stacktrace below). Ideally, the Response.normalDetail and Response.servicesDetail properties should be mapped respectively to T_RESPONSE.NORMAL_AMOUNT,T_RESPONSE.NORMAL_DESCR and T_RESPONSE.SERV_AMOUNT,T_RESPONSE.SERV_DESCR. Is it possible to specify the NORMAL_ and SERVICES_ column prefixes in the configuration of the Embedded properties ? If the answer is no, which alternatives do I have to solve this issue ? @Entity @Table(name=T_RESPONSE) public class Response @Embedded protected Detail normalDetail; @Embedded protected Detail servicesDetail; @Embeddable public class Detail protected Integer amount; protected String description; Stacktrace Caused by: openjpa-1.2.2-r422266:898935 fatal user error org.apache.openjpa.persistence.InvalidStateException: Attempt to set column Response.amount to two different values: (class java.lang.Integer)10, (class java.lang.Integer)1 This can occur when you fail to set both sides of a two-sided relation between objects, or when you map different fields to the same column, but you do not keep the values of these fields in synch. at org.apache.openjpa.jdbc.sql.PrimaryRow.setObject(PrimaryRow.java:339) at org.apache.openjpa.jdbc.sql.RowImpl.setObject(RowImpl.java:504) at org.apache.openjpa.jdbc.meta.strats.EmbedFieldStrategy$EmbeddedRow.setObject(EmbedFieldStrategy.java:1416) -- View this message in context: http://openjpa.208410.n2.nabble.com/Mapping-different-Embedded-of-the-same-type-to-the-same-table-tp5195526p5195526.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: openjpa-2.0 how join fetch work?
Hi, I still could not reproduce the NPE problem using your entities. The following is the url for join fetch. http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/jpa_overview_query.html#jpa_overview_join_fetch - Original Message From: Zhanming Qi openglo...@gmail.com To: users@openjpa.apache.org Sent: Thu, June 3, 2010 4:19:10 AM Subject: Re: openjpa-2.0 how join fetch work? Hi, Here is my POJOs. Corporation is: @Entity @Table(name = CORPORATION) public class Corporation implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = ID, nullable = false) private int id; @Column(name = CORPORATION_NAME) private String name; @OneToMany(mappedBy = corporation, fetch = FetchType.LAZY) private SetDivision divisions; @Version private int version; public Corporation() { } getter and setter } Division is: @Entity @Table(name = DIVISION) public class Division implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = ID, nullable = false) private long id; private String name; private long mumber; @Embedded private Address address; @ManyToOne @JoinColumn(name = CORPORATION_ID) private Corporation corporation; @OneToMany(mappedBy = division) private SetDepartment departments; @Version private int version; public Division() { } getter and setter } Thanks. Zhanming -- View this message in context: http://openjpa.208410.n2.nabble.com/openjpa-2-0-how-join-fetch-work-tp5121731p5134729.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: IOB Error
Hi, Chris, Can you provide the entity definitions? Thanks, Fay - Original Message From: C N Davies c...@cndavies.com To: users@openjpa.apache.org Sent: Sun, April 25, 2010 2:51:56 AM Subject: IOB Error This application has been running just fine for the last few months, suddenly I am starting to get this error. I have restored the DB and there have been no code changes to this software for months other than updating to OpenJPA Beta 3 a few weeks ago. I tested on the latest OpenJPA 2.0 release and have the same issue. The code is just calling final(Class, key) and the key is valid. Using JPA 2.0 Beta 3 java.lang.ArrayIndexOutOfBoundsException: 1 org.apache.openjpa.jdbc.sql.SelectImpl.where(SelectImpl.java:1369) org.apache.openjpa.jdbc.sql.SelectImpl.wherePrimaryKey(SelectImpl.java:1293) org.apache.openjpa.jdbc.sql.SelectImpl.wherePrimaryKey(SelectImpl.java:1270) org.apache.openjpa.jdbc.sql.LogicalUnion$UnionSelect.wherePrimaryKey(Logical Union.java:751) org.apache.openjpa.jdbc.kernel.JDBCStoreManager$1.select(JDBCStoreManager.ja va:612) org.apache.openjpa.jdbc.sql.LogicalUnion.select(LogicalUnion.java:297) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.getInitializeStateUnionResul t(JDBCStoreManager.java:608) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.initializeState(JDBCStoreMan ager.java:392) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.initialize(JDBCStoreManager. java:342) org.apache.openjpa.kernel.DelegatingStoreManager.initialize(DelegatingStoreM anager.java:112) org.apache.openjpa.kernel.ROPStoreManager.initialize(ROPStoreManager.java:57 ) org.apache.openjpa.kernel.BrokerImpl.initialize(BrokerImpl.java:1005) org.apache.openjpa.kernel.BrokerImpl.find(BrokerImpl.java:963) org.apache.openjpa.kernel.BrokerImpl.find(BrokerImpl.java:880) org.apache.openjpa.kernel.DelegatingBroker.find(DelegatingBroker.java:223) org.apache.openjpa.persistence.EntityManagerImpl.find(EntityManagerImpl.java :476) Thx Chris
Re: [VOTE] Apache OpenJPA 2.0.0 release candidate #2
+1. - Original Message From: Donald Woods dwo...@apache.org To: d...@openjpa.apache.org Cc: users@openjpa.apache.org Sent: Mon, April 19, 2010 11:45:53 AM Subject: [VOTE] Apache OpenJPA 2.0.0 release candidate #2 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/ Site staging: http://people.apache.org/~dwoods/openjpa/2.0.0/staging-site/ Distribution artifacts: http://people.apache.org/~dwoods/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/ API Docs: http://people.apache.org/~dwoods/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: aggregates in ORDER BY
Hi, I tried the following jpql on openjpa trunk code: String jpql1 = SELECT k.keyname, SUM(k.keyval) FROM KeyGenEntity k GROUP BY k.keyname ORDER BY SUM(k.keyval) DESC; The generated sql is: SELECT t0.KEYNAME, SUM(t0.KEYVAL), SUM(t0.KEYVAL) FROM KEYGEN t0 GROUP BY t0.KEYNAME ORDER BY SUM(t0.KEYVAL) DESC It works just fine. Can you try the trunk code? Regards, Fay - Original Message From: jonathan de beir jonathan.de.b...@gmail.com To: users@openjpa.apache.org Sent: Thu, April 1, 2010 6:24:15 AM Subject: aggregates in ORDER BY Hello, I have the problem in OpenJPA v1.2.2 that aggregates in order by clauses doesn't works, altough it was fixed in version 1.1.0: https://issues.apache.org/jira/browse/OPENJPA-490?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel Jpql query giving the problem: SELECT b.cid, SUM(b.distance) FROM BestDistance b GROUP BY b.cid ORDER BY SUM(b.distance) DESC Working MySQL query with same functionality: SELECT cid, SUM(distance) FROM bestdistances GROUP BY cid ORDER BY SUM(distance) DESC This is a warning I get: WARN [http-thread-pool-8080-(1)] openjpa.Query - This JPQL query uses non-standard OpenJPA extensions in the ORDER BY clause. JPQL string: SELECT b.cid, SUM(b.distance) FROM BestDistance b GROUP BY b.cid ORDER BY SUM(b.distance) DESC. Query execution will proceed. The openjpa.Compatibility configuration setting is configured to log a warning the first time a given extended query is encountered. To me it looks like the issue wasn't fixed, altough I'm kinda new with OpenJPA / JPQL. Can someone clear it out for me? Greetings, Jonathan
Re: [VOTE] OpenJPA 2.0.0-beta3 release candidate
+1 Thanks! 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/ 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/ 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/ 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/ 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/ 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 -- Thanks, Rick
Re: @ElementCollection and @PersistentCollection
As Jerry points out, ElementCollection is a standard JPA 2.0 annotation, while PersistentCollection is OpenJPA-specific. Also, ElementCollection can be applied to Collection and Map for embeddables or basic types, while PersistentCollection can only apply to Collection, for Map, you need to use PersistentMap. Fay - Original Message From: No1UNo je...@jerrycarter.org To: users@openjpa.apache.org Sent: Mon, March 15, 2010 9:10:33 AM Subject: Re: @ElementCollection and @PersistentCollection Sorry that I can't give you any definitive answer. @ElementCollection is a JPA 2.0 element which creates a collection of embedded entities. The @PersistenceCollection element is older and may be more general. My general guideline is to prefer the standard annotations over package specific ones. If you are working with JPA 2.0 and are specifically using collections of embedded entities, consider using @ElementCollection. Otherwise, do what you've always done. On Mar 15, 2010, at 11:42 AM, Jean-Baptiste BRIAUD -- Novlog [via OpenJPA] wrote: Hi What are the differences between @ElementCollection and @PersistentCollection ? I'm already using @PersistentCollection but I encountred @ElementCollection in the examples folder of OpenJPA 2.0.0 beta 2 in a embedded folder. At the end, I'm not sure to see a difference ... so I'm puzzled. View message @ http://n2.nabble.com/ElementCollection-and-PersistentCollection-tp4737753p4737753.html To start a new topic under OpenJPA Users, email ml-node+208411-1595610943-93...@n2.nabble.com To unsubscribe from OpenJPA Users, click here. -- View this message in context: http://n2.nabble.com/ElementCollection-and-PersistentCollection-tp4737753p4737969.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Refreshing detached entities
hi Jerry, I could not reproduce this problem and I am using the trunk level code. 11256 callback TRACE [main] openjpa.jdbc.SQL - t 16785420, conn 20448186 executing prepstmnt 2721032 INSERT INTO EntityA (id) VALUES (?) [params=(int) 1] 11276 callback TRACE [main] openjpa.jdbc.SQL - t 16785420, conn 20448186 [20 ms] spent java.lang.IllegalArgumentException: refresh can not be invoked on callback.EntityA-1. This entity is either detached or not persistent or null. at org.apache.openjpa.persistence.EntityManagerImpl.assertValidAttchedEntity(EntityManagerImpl.java:1344) at org.apache.openjpa.persistence.EntityManagerImpl.refresh(EntityManagerImpl.java:744) at org.apache.openjpa.persistence.EntityManagerImpl.refresh(EntityManagerImpl.java:731) at callback.TestCallback.testRefreshOnDetachedEntity(TestCallback.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(Unknown Source) at junit.framework.TestCase.runBare(Unknown Source) at junit.framework.TestResult$1.protect(Unknown Source) at junit.framework.TestResult.runProtected(Unknown Source)SUCCESS: Refresh detached Here is my test code snippet: public void testRefreshOnDetachedEntity() { try { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); EntityA a = new EntityA(); a.setId(2); em.persist(a); em.flush(); em.detach(a); em.refresh(a); System.err.println(ERROR: No exception from em.refresh(detached)); } catch (IllegalArgumentException e) { e.printStackTrace(); System.out.println(SUCCESS: Refresh detached); } catch (Exception e) { e.printStackTrace(); System.err.println(ERROR: Unexpected exception from em.refresh(detached): + e.toString()); } } - Original Message From: Jerry Carter je...@jerrycarter.org To: users@openjpa.apache.org Sent: Thu, March 11, 2010 9:21:13 AM Subject: Refreshing detached entities Possible gap in my understanding, but I would expect an exception in this case based on section 3.2.5 of the JPA 2.0 specification: If [entity] X is new, detached, or removed entity, the IllegalArgumentException is thrown. try { TestEntity refreshDetached = new TestEntity(refresh detached); em.persist(refreshDetached); em.flush(); em.detach(refreshDetached); em.refresh(refreshDetached); logger.error(ERROR: No exception from em.refresh(detached)); } catch (IllegalArgumentException e) { logger.info(SUCCESS: Refresh detached); } catch (Exception e) { logger.error(ERROR: Unexpected exception from em.refresh(detached): + e.toString()); } ERROR: No exception from em.refresh(detached)
Re: Help on basic @Strategy
Hi Jerry, Ok, I take out the OneToOne annotation, and employ inheritance as shown below. The test works just fine. I don't see unmanaged object exception. (1) @Entity public class SimpleEntity { @Id private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } @Strategy(MyPointHandler) @Persistent(fetch = FetchType.LAZY) private MyPoint custom; public MyPoint getCustom() { return custom; } public void setCustom(MyPoint custom) { this. custom = custom; } } (2) public class MyPoint { String val; public MyPoint(String val) { this.val = val; } public String getValue() { return val; } } (3) public class SpecializedPoint extends MyPoint { int intVal; public SpecializedPoint(String val) { super(val); } public SpecializedPoint(String val, int intVal) { super(val); this.intVal = intVal; } public int getIntVal() { return intVal; } public void setIntVal(int intVal) { this.intVal = intVal; } } (4) public class MyPointHandler extends AbstractValueHandler { public Column[] map(ValueMapping vm, DBIdentifier name, ColumnIO io, boolean adapt) { String dbIdName = name.getName(); Column c1 = new Column(); c1.setIdentifier(DBIdentifier.newColumn(dbIdName + _val)); c1.setJavaType(JavaTypes.STRING); Column c2 = new Column(); c2.setIdentifier(DBIdentifier.newColumn(dbIdName + _intVal)); c2.setJavaType(JavaTypes.INT_OBJ); return new Column[]{ c1, c2 }; } public Column[] map(ValueMapping vm, String name, ColumnIO io, boolean adapt) { Column c1 = new Column(); c1.setIdentifier(DBIdentifier.newColumn(name + _val)); c1.setJavaType(JavaTypes.STRING); Column c2 = new Column(); c2.setIdentifier(DBIdentifier.newColumn(name + _intVal)); c2.setJavaType(JavaTypes.INT_OBJ); return new Column[]{ c1, c2 }; } public boolean isVersionable() { return true; } public Object toDataStoreValue(ValueMapping vm, Object val, JDBCStore store) { return new Object[] {((SpecializedPoint)val).getValue(), ((SpecializedPoint)val).getIntVal()}; } public Object toObjectValue(ValueMapping vm, Object val) { Object[] objVal = (Object[]) val; return new SpecializedPoint((String)objVal[0], (Integer)objVal[1]); } } (5) Here is my test program: public void testStrat() { EntityManager em = emf.createEntityManager(); SimpleEntity e = new SimpleEntity(); e.setId(1); SpecializedPoint custom = new SpecializedPoint(myPoint, 1); e.setCustom(custom); em.persist(e); em.getTransaction().begin(); em.getTransaction().commit(); em.clear(); SimpleEntity e1 = em.find(SimpleEntity.class, 1); System.out.println(e1 = + e1); } Fay - Original Message From: No1UNo je...@jerrycarter.org To: users@openjpa.apache.org Sent: Mon, March 8, 2010 8:08:55 PM Subject: Re: Help on basic @Strategy On Mar 8, 2010, at 4:03 PM, No1UNo [via OpenJPA] wrote: The 'unmanaged object' exception is being caused by an inheritance relationship on the Java side. Suppose that I have a specialized class derive from a base class: 'class SpecializedPoint extends MyPoint'. If I write the entity as @Strategy(MyPointHandler) private SpecializedPoint custom; SpecializedPoint getCustom() { return custom; } void setCustom(SpecializedPoint custom) { this. custom = custom; } everything works fine. If instead I have @Strategy(MyPointHandler) private MyPoint custom; MyPoint getCustom() { return custom; } void setCustom(MyPoint custom) { this. custom = custom; } and call 'setCustom(new SpecializedPoint())' then the exception is thrown when the data should be written to the database and BEFORE ever calling the class designated by @Strategy. Is this a bug in OpenJPA 2.0.0? Most likely the behavior is by design. This prevents scenarios where the child class requires persisting more information than the base class. Unfortunately, it doesn't help much in my case as the objects are serializing binary data to the database and only a single column is required for the whole family of classes. Is there a different mechanism for this scenario? FWIW, I've employed a slightly different workaround. I defined a simple class holding the base class and made corresponding changes to the setter, getter, and strategy class. @Strategy(MyPointHandler) private HolderClass custom; MyPoint GetCustom() { return custom.getPoint(); } void setCustom(MyPoint custom) { custom = new HolderClass(custom); } This seems unnecessary but it works. -- View this message in context: http://n2.nabble.com/Help-on-basic-Strategy-tp4696891p4700217.html Sent from the OpenJPA Users
Re: Help on basic @Strategy
Hi, As the exception clearly indicates, adding Cascade attribute should fix this unmanaged object problem, and the insert should work: @Strategy(MyPointHandler) @OneToOne(cascade=CascadeType.ALL) private MyPoint custom; Since you did not provide MyPoint.java, the following is the one I used: @Entity public class MyPoint { @Id String val; public MyPoint(String val) { this.val = val; } public String getValue() { return val; } } Regards, Fay - Original Message From: No1UNo je...@jerrycarter.org To: users@openjpa.apache.org Sent: Mon, March 8, 2010 10:20:16 AM Subject: Re: Help on basic @Strategy One other detail I should have mentioned. The values are correctly retrieved from the database, but the exception is thrown on INSERT before the @Strategy class is even invoked. On Mar 8, 2010, at 12:42 PM, No1UNo [via OpenJPA] wrote: I am seeing an 'unmanaged object' exception for the objects build using @Strategy, but isn't that exactly the point? These are supposed to be unmanaged with the strategy being invoked as necessary for conversion. I must be missing something obvious. ;-) Caused by: openjpa-2.0.0-beta2-r422266:915978 fatal user error org.apache.openjpa.persistence.InvalidStateException: Encountered unmanaged object in persistent field com.example.SimpleEntity.custom during flush. However, this field does not allow cascade persist. Set the cascade attribute for this field to CascadeType.PERSIST or CascadeType.ALL (JPA annotations) or persist or all (JPA orm.xml), or enable cascade-persist globally, or manually persist the related field value prior to flushing. You cannot flush unmanaged objects or graphs that have persistent associations to unmanaged objects. FailedObject: com.example.mypo...@a431693 at org.apache.openjpa.kernel.SingleFieldManager.preFlushPC(SingleFieldManager.java:767) My entity looks something like this: @Entity public abstract class SimpleEntity { @Id private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } @Strategy(MyPointHandler) private MyPoint custom; MyPoint getCustom() { return custom; } void setCustom(MyPoint custom) { this. custom = custom; } ... } With a very simple handler class: public class MyPointHandler extends AbstractValueHandler { @Override public Column[] map(ValueMapping vm, String name, ColumnIO io, boolean adapt) { Column c = new Column(); c.setIdentifier(DBIdentifier.newColumn(name)); c.setJavaType(JavaTypes.STRING); return new Column[]{ c }; } public boolean isVersionable() { return true; } public Object toDataStoreValue(ValueMapping vm, Object val, JDBCStore store) { return new MyPoint((String) val); } public Object toObjectValue(ValueMapping vm, Object val) { if (val == null) return null; return ((MyPoint) val).getValue(); } } I've used the PointHandler from the OpenJPA tests as a model. View message @ http://n2.nabble.com/Help-on-basic-Strategy-tp4696891p4696891.html To start a new topic under OpenJPA Users, email ml-node+208411-1595610943-93...@n2.nabble.com To unsubscribe from OpenJPA Users, click here. -- View this message in context: http://n2.nabble.com/Help-on-basic-Strategy-tp4696891p4697140.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: JPA adding class name to join column name
Hi, I noticed that you have name field in your Customer.java and ValuedCustomer.java. This field in both classes is mapped to the same column in the same table. Since ValuedCustomer inherits from Customer, I am wondering why you need to have a separate name field in the ValuedCustomer. If you take out this field from the ValuedCustomer, this column VALUEDCUSTOMER_ID will not be generated. Fay - Original Message From: open...@reider.net open...@reider.net To: users@openjpa.apache.org Sent: Wed, February 24, 2010 6:52:30 PM Subject: JPA adding class name to join column name I'm having an issue with JPA generating column names containing Java class names, with some mix of @Inheritance(strategy=InheritanceType.SINGLE_TABLE and @SecondaryTables. This results in an error because of a non existent column: openjpa-1.2.2-SNAPSHOT-r422266:821449 nonfatal general error org.apache.openjpa.persistence.PersistenceException: DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703, SQLERRMC: T1.VALUEDCUSTOMER_ID 1607819221 SELECT ... FROM CUSTOMERRATING t0 INNER JOIN CUSTOMER t1 on t0.ID = t1.VALUEDCUSTOMER_ID INNER JOIN GREATCUSTOMERDATA t2 ON t0.id = t2.id ... ValuedCustomer is the class of one of the Java entities on the table. Why would JPA prefix the column name with the class name (VALUEDCUSTOMER_ID)? The column name is just ID. The error goes away when removing the name field from ValuedCustomer class. It can be undesirable to have to define all columns in the root class. I did try copying down the @SecondaryTables annotation but it didnt help. This entity is being migrated from TOPLink (11g) which does not have this issue. (side problem: why does JPA insist the discriminator column be in the primary table and has this been addressed in later versions? I had to swap CUSTOMERRATING and CUSTOMER to make JPA happy (arguably, bad legacy table design to begin with). The configuration follows. The above error occurs for a find() for a row that maps to GREATCUSTOMER (not VALUEDCUSTOMER, which makes it even more insteresting). Hopefully i haven't mangled the example while substituting fake names... //CLASS 1 @Entity @Table(name=CUSTOMERRATING) @Inheritance(strategy=InheritanceType.SINGLE_TABLE) // in the real code, pkJoinColumns needed... @SecondaryTables({ @SecondaryTable(name=CUSTOMER,pkJoinColumns = @PrimaryKeyJoinColumn (name=ID, referencedColumnName=ID)) ,@SecondaryTable(name=MORECUSTOMERDATA,pkJoinColumns = @PrimaryKeyJoinColumn( name=ID , referencedColumnName=ID)) @DiscriminatorColumn(name=RATING) public class Customer extends EntityImpl implements Serializable { @Column(name=ID) @Id protected String id; @Column(table=CUSTOMERRATING,name=RATING) private String rating; @Column(table=CUSTOMER,name=NAME) private String name; //Class 2 @Entity @DiscriminatorValue(value=2) public class ValuedCustomer extends Customer implements Serializable { @Column(table=CUSTOMER,name=NAME) private String name;} // Class 3 @Entity @SecondaryTable( name=GREATCUSTOMERDATA ,pkJoinColumns = @PrimaryKeyJoinColumn( name=ID , referencedColumnName=ID)) @DiscriminatorValue(value=9) public class GreatCustomer extends ValuedCustomer implements Serializable { @Column(table=GREATCUSTOMERDATA,name=ID) private String greatCustomerdataId;
Re: JPA adding class name to join column name
Hi, I just realized that you mentioned removing name field will make the problem go away, and it is undesirable to define all columns in the root class. Can you try the following ValuedCustomer definition? I added a new field age to this class, and also added the SecondaryTable annotation to it: @Entity @SecondaryTable( name=CUSTOMER, pkJoinColumns = @PrimaryKeyJoinColumn( name=ID, referencedColumnName=ID)) @DiscriminatorValue(value=2) public class ValuedCustomer extends Customer implements Serializable { @Column(table=CUSTOMER,name=AGE) private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } } I also modified your Customer.class by taking out the rating field. You don't really need this rating field because your discriminator and the rating field map to the same column. @Entity @Table(name=CUSTOMERRATING) @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @SecondaryTables({ @SecondaryTable( name=CUSTOMER, pkJoinColumns = @PrimaryKeyJoinColumn(name=ID, referencedColumnName=ID)), @SecondaryTable( name=MORECUSTOMERDATA, pkJoinColumns = @PrimaryKeyJoinColumn(name=ID , referencedColumnName=ID)) }) @DiscriminatorColumn(name=RATING) public class Customer implements Serializable { @Column(name=ID) @Id protected String id; @Column(table=CUSTOMER,name=NAME) private String name; Finally, in your GreatCustomer.java, again your greatCustomerdataId originally is mapped to the same ID column of the GREATCUSTOMERDATA. However, this ID column is supposed to be the join column, you should map it to a different column. Otherwise, this value can not be stored. @Entity @SecondaryTable( name=GREATCUSTOMERDATA, pkJoinColumns = @PrimaryKeyJoinColumn( name=ID, referencedColumnName=ID)) @DiscriminatorValue(value=9) public class GreatCustomer extends ValuedCustomer implements Serializable { @Column(table=GREATCUSTOMERDATA,name=GC_ID) private String greatCustomerdataId; With these entity definitions, the tables created by openjpa are: CREATE TABLE CUSTOMER (ID VARCHAR(254), NAME VARCHAR(254), AGE INTEGER) CREATE TABLE CUSTOMERRATING (ID VARCHAR(254) NOT NULL, RATING VARCHAR(31), PRIMARY KEY (ID)) CREATE TABLE GREATCUSTOMERDATA (ID VARCHAR(254), GC_ID VARCHAR(254)) Fay - Original Message From: Fay Wang fyw...@yahoo.com To: users@openjpa.apache.org Sent: Thu, February 25, 2010 11:11:57 AM Subject: Re: JPA adding class name to join column name Hi, I noticed that you have name field in your Customer.java and ValuedCustomer.java. This field in both classes is mapped to the same column in the same table. Since ValuedCustomer inherits from Customer, I am wondering why you need to have a separate name field in the ValuedCustomer. If you take out this field from the ValuedCustomer, this column VALUEDCUSTOMER_ID will not be generated. Fay - Original Message From: open...@reider.net open...@reider.net To: users@openjpa.apache.org Sent: Wed, February 24, 2010 6:52:30 PM Subject: JPA adding class name to join column name I'm having an issue with JPA generating column names containing Java class names, with some mix of @Inheritance(strategy=InheritanceType.SINGLE_TABLE and @SecondaryTables. This results in an error because of a non existent column: openjpa-1.2.2-SNAPSHOT-r422266:821449 nonfatal general error org.apache.openjpa.persistence.PersistenceException: DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703, SQLERRMC: T1.VALUEDCUSTOMER_ID 1607819221 SELECT ... FROM CUSTOMERRATING t0 INNER JOIN CUSTOMER t1 on t0.ID = t1.VALUEDCUSTOMER_ID INNER JOIN GREATCUSTOMERDATA t2 ON t0.id = t2.id ... ValuedCustomer is the class of one of the Java entities on the table. Why would JPA prefix the column name with the class name (VALUEDCUSTOMER_ID)? The column name is just ID. The error goes away when removing the name field from ValuedCustomer class. It can be undesirable to have to define all columns in the root class. I did try copying down the @SecondaryTables annotation but it didnt help. This entity is being migrated from TOPLink (11g) which does not have this issue. (side problem: why does JPA insist the discriminator column be in the primary table and has this been addressed in later versions? I had to swap CUSTOMERRATING and CUSTOMER to make JPA happy (arguably, bad legacy table design to begin with). The configuration follows. The above error occurs for a find() for a row that maps to GREATCUSTOMER (not VALUEDCUSTOMER, which makes it even more insteresting). Hopefully i haven't mangled the example while substituting fake names... //CLASS 1 @Entity @Table(name=CUSTOMERRATING) @Inheritance(strategy=InheritanceType.SINGLE_TABLE) // in the real code, pkJoinColumns needed... @SecondaryTables({ @SecondaryTable(name=CUSTOMER
Re: Named query doesn't translate table/column names properly, UNLESS it's run after an identical inline query
I was wrong. You problem seems not related to JIRA-859. After digging in a little bit, it appears that the column name for the field specified in the orm.xml is properly parsed and set for the field in openjpa 1.2.x. It must be something else that causes the failure... - Original Message From: KARR, DAVID (ATTCINW) dk0...@att.com To: users@openjpa.apache.org Sent: Sat, January 23, 2010 11:28:15 AM Subject: RE: Named query doesn't translate table/column names properly, UNLESS it's run after an identical inline query -Original Message- From: Fay Wang [mailto:fyw...@yahoo.com] Sent: Saturday, January 23, 2010 10:53 AM To: users@openjpa.apache.org Subject: Re: Named query doesn't translate table/column names properly, UNLESS it's run after an identical inline query As you described, it seems that the information specified in the orm.xml is not picked up by OpenJPA. This issue seems resolved in JIRA- 859 in the trunk code and 1.3.x branch. Are you referring to OPENJPA-859, OpenJPA requires all persistent fields to be specified on an XML defined entity? - Original Message From: KARR, DAVID (ATTCINW) dk0...@att.com To: users@openjpa.apache.org Sent: Fri, January 22, 2010 5:11:19 PM Subject: Named query doesn't translate table/column names properly, UNLESS it's run after an identical inline query I've been running ok with 1.2.1, and I recently installed 1.2.2, which ran almost without changes out of the box. I decided to start looking into converting some of my inline queries to named queries, thinking it might be more efficient. I have a DAOImpl class that currently has an inline query. I copied it exactly as written to a @NamedQuery annotation above the entity class. In the DAOImpl method, I commented out the line that created the query and changed it to reference the named query. When I ran it, I found that the generated SQL didn't translate any of the table and column names, as described in the orm.xml file. Then, I reverted that last change, commenting out the reference to the named query and uncommenting the creation of the inline query. It was fine again. Then, I tried doing BOTH in the same method. I first did the inline query, and then after it got the results for it, I created another query using the named query, assigned the same parameter, and retrieved the result. Surprisingly, it worked. Yes, you read that right. I then tried reversing the order, doing the named query first, and then the inline query. Not surprisingly, that call to the named query failed to translate properly. When the named query goes bad, it ends up as: SELECT t0.id, t1.id, t1.description, t1.displayName, t1.longDescription, t1.seoLabel, t0.creationDate, t0.description, t0.displayName, t0.longDescription, t2.CATEGORY_ID, t2.SEQUENCE_NUM, t3.id, t3.CATEGORYES_ID, t3.creationDate, t3.description, t3.displayName, t3.longDescription FROM Category t0, CategoryES t1, Category_Category t2, Category t3 WHERE (t0.id = ?) AND t0.CATEGORYES_ID = t1.id(+) AND t0.id = t2.CATEGORY_ID(+) AND t2.CHILDCATEGORIES_ID = t3.id(+) ORDER BY t2.CATEGORY_ID ASC, t2.SEQUENCE_NUM ASC When I call it after the inline query, the named query translates (correctly) as: SELECT t0.CATEGORY_ID, t1.CATEGORY_ID, t1.DESCRIPTION, t1.DISPLAY_NAME, t1.LONG_DESCRIPTION, t1.SEO_LABEL, t0.CREATION_DATE, t0.DESCRIPTION, t0.DISPLAY_NAME, t0.LONG_DESCRIPTION, t2.CATEGORY_ID, t3.CATEGORY_ID, t3.CREATION_DATE, t3.DESCRIPTION, t3.DISPLAY_NAME, t3.LONG_DESCRIPTION FROM cat1.DCS_CATEGORY t0, cat1.ONLINE_DCS_CATEGORY_ES t1, cat1.DCS_CAT_CHLDCAT t2, cat1.DCS_CATEGORY t3 WHERE (t0.CATEGORY_ID = ?) AND t0.CATEGORY_ID = t1.CATEGORY_ID(+) AND t0.CATEGORY_ID = t2.CATEGORY_ID(+) AND t2.CHILD_CAT_ID = t3.CATEGORY_ID(+) ORDER BY t2.CATEGORY_ID ASC I verified that the generated SQL for the named query (when it's working) is identical to what I was getting from the inline query, which isn't surprising, as I copied it exactly. The DAO method in question is the following (note that entityClass.getName() is just com.att.ecom.dynamiccontent.domain.catalog.Category): -- public Category getCategoryWithProducts(String id) { Categoryresult = null; Query query = //entityManager.createNamedQuery(categoryWithChildren); entityManager.createQuery(select ctgry from + entityClass.getName() + ctgry + left join fetch ctgry.childCategories + left join fetch ctgry.childProducts + where ctgry.id = :id); query.setParameter(id, id); result = (Category) query.getSingleResult(); Query namedQuery = entityManager.createNamedQuery(categoryWithChildren); namedQuery.setParameter(id, id); Categorycategory= (Category
Re: Named query doesn't translate table/column names properly, UNLESS it's run after an identical inline query
As you described, it seems that the information specified in the orm.xml is not picked up by OpenJPA. This issue seems resolved in JIRA-859 in the trunk code and 1.3.x branch. Fay - Original Message From: KARR, DAVID (ATTCINW) dk0...@att.com To: users@openjpa.apache.org Sent: Fri, January 22, 2010 5:11:19 PM Subject: Named query doesn't translate table/column names properly, UNLESS it's run after an identical inline query I've been running ok with 1.2.1, and I recently installed 1.2.2, which ran almost without changes out of the box. I decided to start looking into converting some of my inline queries to named queries, thinking it might be more efficient. I have a DAOImpl class that currently has an inline query. I copied it exactly as written to a @NamedQuery annotation above the entity class. In the DAOImpl method, I commented out the line that created the query and changed it to reference the named query. When I ran it, I found that the generated SQL didn't translate any of the table and column names, as described in the orm.xml file. Then, I reverted that last change, commenting out the reference to the named query and uncommenting the creation of the inline query. It was fine again. Then, I tried doing BOTH in the same method. I first did the inline query, and then after it got the results for it, I created another query using the named query, assigned the same parameter, and retrieved the result. Surprisingly, it worked. Yes, you read that right. I then tried reversing the order, doing the named query first, and then the inline query. Not surprisingly, that call to the named query failed to translate properly. When the named query goes bad, it ends up as: SELECT t0.id, t1.id, t1.description, t1.displayName, t1.longDescription, t1.seoLabel, t0.creationDate, t0.description, t0.displayName, t0.longDescription, t2.CATEGORY_ID, t2.SEQUENCE_NUM, t3.id, t3.CATEGORYES_ID, t3.creationDate, t3.description, t3.displayName, t3.longDescription FROM Category t0, CategoryES t1, Category_Category t2, Category t3 WHERE (t0.id = ?) AND t0.CATEGORYES_ID = t1.id(+) AND t0.id = t2.CATEGORY_ID(+) AND t2.CHILDCATEGORIES_ID = t3.id(+) ORDER BY t2.CATEGORY_ID ASC, t2.SEQUENCE_NUM ASC When I call it after the inline query, the named query translates (correctly) as: SELECT t0.CATEGORY_ID, t1.CATEGORY_ID, t1.DESCRIPTION, t1.DISPLAY_NAME, t1.LONG_DESCRIPTION, t1.SEO_LABEL, t0.CREATION_DATE, t0.DESCRIPTION, t0.DISPLAY_NAME, t0.LONG_DESCRIPTION, t2.CATEGORY_ID, t3.CATEGORY_ID, t3.CREATION_DATE, t3.DESCRIPTION, t3.DISPLAY_NAME, t3.LONG_DESCRIPTION FROM cat1.DCS_CATEGORY t0, cat1.ONLINE_DCS_CATEGORY_ES t1, cat1.DCS_CAT_CHLDCAT t2, cat1.DCS_CATEGORY t3 WHERE (t0.CATEGORY_ID = ?) AND t0.CATEGORY_ID = t1.CATEGORY_ID(+) AND t0.CATEGORY_ID = t2.CATEGORY_ID(+) AND t2.CHILD_CAT_ID = t3.CATEGORY_ID(+) ORDER BY t2.CATEGORY_ID ASC I verified that the generated SQL for the named query (when it's working) is identical to what I was getting from the inline query, which isn't surprising, as I copied it exactly. The DAO method in question is the following (note that entityClass.getName() is just com.att.ecom.dynamiccontent.domain.catalog.Category): -- public Category getCategoryWithProducts(String id) { Categoryresult = null; Query query = //entityManager.createNamedQuery(categoryWithChildren); entityManager.createQuery(select ctgry from + entityClass.getName() + ctgry + left join fetch ctgry.childCategories + left join fetch ctgry.childProducts + where ctgry.id = :id); query.setParameter(id, id); result = (Category) query.getSingleResult(); Query namedQuery = entityManager.createNamedQuery(categoryWithChildren); namedQuery.setParameter(id, id); Categorycategory= (Category) namedQuery.getSingleResult(); return (result); } --- The relevant portion of the entity class is this: @Entity @NamedQueries({ @NamedQuery(name = categoryWithChildren, query = select ctgry from com.att.ecom.dynamiccontent.domain.catalog.Category ctgry + left join fetch ctgry.childCategories left join fetch ctgry.childProducts + where ctgry.id = :id) }) public class Category implements LocaleSpecific { @Id private String id; @Basic private String displayName; @Basic private String description; @Lob private String longDescription; @OneToOne private CategoryES categoryES; @Temporal(TemporalType.DATE) private DatecreationDate; @OneToMany @OrderColumn(name = SEQUENCE_NUM) private ListCategory childCategories; @OneToMany @OrderColumn(name =
Re: VerifyError when using IdClass with BigInteger/BigDecimal
I have seen this problem before, but somehow it went away. I am using your entity definition but could no longer reproduce the problem. Using java decompiler, the following is my pcCopyKeyFieldsToObjectId in EmailAddress. Can you post your problematic pcCopyKeyFieldsToObjectId? public void pcCopyKeyFieldsToObjectId(Object paramObject) { Object localObject; EmailAddressId localEmailAddressId = (EmailAddressId)((ObjectId)paramObject).getId(); Account localAccount = this.account; if (localAccount != null) localObject = ((PersistenceCapable)localAccount).pcNewObjectIdInstance(); localEmailAddressId.account = ((localObject != null) ? ((BigIntegerId)localObject).getId() : null); localEmailAddressId.ix = this.ix; } -Fay - Original Message From: Bender1199 sefr...@googlemail.com To: users@openjpa.apache.org Sent: Sun, January 17, 2010 1:38:37 PM Subject: VerifyError when using IdClass with BigInteger/BigDecimal I'm using openjpa-all 2.0.0-M3. I've following classes @Entity public class Account { @Id private BigInteger id; private String name; private String password; ... } @Entity @IdClass(EmailAddress.EmailAddressId.class) public class EmailAddress{ @Id @ManyToOne private account; @Id private BigInteger ix; private String address; public static class EmailAddressId{ public BigInteger account; public BigInteger ix; ... } } Now when I'm creating an EntityManager this error occures java.lang.VerifyError: (class: EmailAddress, method: pcCopyKeyFieldsToObjectId signature: (Ljava/lang/Object;)V) Bad type in putfield/putstatic at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at org.apache.openjpa.meta.MetaDataRepository.classForName(MetaDataRepository.java:1448) at org.apache.openjpa.meta.MetaDataRepository.loadPersistentTypes(MetaDataRepository.java:1421) at org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:273) at org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:229) at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203) at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:152) at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:199) at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:150) at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:56) Same behaviour when using BigDecimal as ID field. When using Long it works! Anyone an idea? -- View this message in context: http://n2.nabble.com/VerifyError-when-using-IdClass-with-BigInteger-BigDecimal-tp4410186p4410186.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: How to implement a map where the key is in the join table, not in the target table?
For JPA 2.0 (OpenJPA trunk), the map key does not need to be a field in the target entity. For example, please see the test case in org.apache.openjpa.persistence.jdbc.maps.*. - Original Message From: KARR, DAVID (ATTCINW) dk0...@att.com To: users@openjpa.apache.org Sent: Tue, December 29, 2009 9:36:53 AM Subject: How to implement a map where the key is in the join table, not in the target table? The information I've read about the map construct is that the key value used in the map is taken from a field in the target entity. I have a situation where I need to define a map where the key value is a column in a join table, not the target table. Here's an example of the structure I have: Table FOO: -- VARCHAR FOO_ID INT TYPE Table FOO_BILLING_INFO: -- VARCHAR FOO_ID VARCHAR BILLING_SYSTEM VARCHAR BILLING_INFO_ID Table BILLING_INFO: --- VARCHAR BILLING_INFO_ID VARCHAR BILL_CODE VARCHAR SYSTEM_NAME There is a OneToMany relationship from FOO to BILLING_INFO. The key value for the map is intended to be the BILLING_SYSTEM value in the join table. Also note that the values of BILLING_SYSTEM are not the same as or related to the values for SYSTEM_NAME in BILLING_INFO (that was my first guess). For each unique value of FOO_ID in FOO, there will be two FOO_BILLING_INFO rows with different BILLING_SYSTEM values, and each of those two rows will point to a BILLING_INFO row, sometimes the same one for both FOO_BILLING_INFO rows, but sometimes not.
Re: @Version annotation
Hi, You don't need to put generatedValue annotation for the version field. Openjpa will keep track of the version for you. @Version public long getVersion() { return this.version; } - Original Message From: yokenji kenji2...@gmail.com To: users@openjpa.apache.org Sent: Mon, November 16, 2009 8:46:48 AM Subject: @Version annotation Hi there, I trying to use an annotatoin field @version but when updating the record i don't see any version in the database. Also, Element class: package entities; import java.io.Serializable; import java.util.Set; import javax.annotation.Generated; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; import org.apache.openjpa.persistence.jdbc.ForeignKey; /** * @author Ken */ @Entity @NamedQueries({ @NamedQuery(name=roots.Element, query=Select e From Element e + where e.parentElement is null), @NamedQuery(name=one.Element, query=Select e From Element e + where e.dbID = :id) }) @Table(name=Element) public class Element implements ElementInterface, Serializable { private static final long serialVersionUID = 4627343050926103812L; private String dbID; private String internID; private String name; private String description; private long version; private SetPropertyproperties; private Element parentElement; private SetElement childElements; /** * This is the default constructor. */ public Element() { } /** * @see entities.ElementInterface#setDbID(java.lang.String) */ public void setDbID(String dbID) { this.dbID = dbID; } /** * @see entities.ElementInterface#getDbID() */ @Id @GeneratedValue(strategy = GenerationType.AUTO, generator=uuid-hex) public String getDbID() { return this.dbID; } /** * @see entities.ElementInterface#setInternID(java.lang.String) */ public void setInternID(String internID) { this.internID = internID; } /** * @see entities.ElementInterface#getInternID() */ public String getInternID() { return this.internID; } /** * @see entities.ElementInterface#getName() */ public String getName() { return this.name; } /** * @see entities.ElementInterface#setName(java.lang.String) */ public void setName(String name) { this.name = name; } /** * @see entities.ElementInterface#setDescription(java.lang.String) */ public void setDescription(String description) { this.description = description; } /** * @see entities.ElementInterface#getDescription() */ public String getDescription() { return this.description; } /** * @see entities.ElementInterface#setVersion(java.util.Date) */ private void setVersion(int version) { this.version = version; } /** * @see entities.ElementInterface#getVersion() */ @Version @GeneratedValue(strategy=GenerationType.AUTO) public long getVersion() { return this.version; } /** * Set the element properties. * * @param SetProperty properties */ public void setProperties(SetProperty properties) { this.properties = properties; } /** * Get the element properties. * * @return SetProperty */ @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy=element) public SetProperty getProperties() { return properties; } /** * Set the element parent. * * @param Element parentElement */ public void setParentElement(Element parentElement) { this.parentElement = parentElement; } /** * Get the element parent. * * @return Element */ @ManyToOne(optional=true, fetch=FetchType.LAZY) @ForeignKey(name=FK_parent_element) @JoinColumn(name=parent_element, referencedColumnName=dbID) public Element getParentElement() { return parentElement; } /** * Set the element children. * * @param SetElement childElements */ public void setChildElements(SetElement childElements) { this.childElements = childElements; } /** * Get the element children. * * @return SetElement */ @OneToMany(cascade=CascadeType.ALL, mappedBy=parentElement, fetch=FetchType.EAGER) public SetElement getChildElements() { return childElements; } } Class Property: package entities; import java.io.Serializable; import javax.persistence.*; import org.apache.openjpa.persistence.jdbc.ForeignKey; /** *
Re: Unexpected ArgumentException using 'IN' operator
Hi, I tried the following using openjpa trunk, and it works fine. I will try it using openjpa 1.2. Query q = em.createQuery(Select m from Manager m, IN (m.employees) emps where emps = :emp); Employee emp = new Employee(); emp.setId(1); q.setParameter(emp, emp); -Fay - Original Message From: Vivien Barousse barousse.viv...@gmail.com To: users@openjpa.apache.org Sent: Sun, November 8, 2009 7:23:44 AM Subject: Unexpected ArgumentException using 'IN' operator Hi, I'm having trouble using the IN operator in OpenJPA 1.2.1. In my application, I have an entity named 'Entry', which has a many to many relationship to itself on a 'parentEntries' field. Here is the (simplified) code for this entity : @Entity public class Entry implements Serializable { @Id private Long id; @ManyToMany @JoinTable private ListEntry parentEntries; /* ... getters and setters ... */ } I'm trying to retrieve all entities which parentEntries contains any given entry (passed as argument to my query). Here is the query: SELECT entry FROM Entry AS entry, IN (entry.parentEntries) AS parent WHERE parent = :entry This query fails on execution, with an ArgumentException : openjpa-1.2.1-r752877:753278 nonfatal user error org.apache.openjpa.persistence.ArgumentException: The parameter entry is of type com.aperigeek.jtentative.entity.Entry, but the declaration in the query is for type java.util.List at org.apache.openjpa.persistence.QueryImpl.validateParameter(QueryImpl.java:287) at org.apache.openjpa.persistence.QueryImpl.validateParameters(QueryImpl.java:274) at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:248) at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:294) ... This query works fine with other persistence provider (the above code has been successfully tested with Toplink). Am I missing something here? I saw in an old bug report (#OPENJPA-190) someone having the same difficulties. Could this be an OpenJPA bug? Thanks, -- Vivien Barousse
Re: Unexpected ArgumentException using 'IN' operator
Running against openjpa 1.2, I got the same error as you did. Apparently, this problem is fixed in the trunk code. - Original Message From: Fay Wang fyw...@yahoo.com To: users@openjpa.apache.org Sent: Mon, November 9, 2009 9:09:04 AM Subject: Re: Unexpected ArgumentException using 'IN' operator Hi, I tried the following using openjpa trunk, and it works fine. I will try it using openjpa 1.2. Query q = em.createQuery(Select m from Manager m, IN (m.employees) emps where emps = :emp); Employee emp = new Employee(); emp.setId(1); q.setParameter(emp, emp); -Fay - Original Message From: Vivien Barousse barousse.viv...@gmail.com To: users@openjpa.apache.org Sent: Sun, November 8, 2009 7:23:44 AM Subject: Unexpected ArgumentException using 'IN' operator Hi, I'm having trouble using the IN operator in OpenJPA 1.2.1. In my application, I have an entity named 'Entry', which has a many to many relationship to itself on a 'parentEntries' field. Here is the (simplified) code for this entity : @Entity public class Entry implements Serializable { @Id private Long id; @ManyToMany @JoinTable private ListEntry parentEntries; /* ... getters and setters ... */ } I'm trying to retrieve all entities which parentEntries contains any given entry (passed as argument to my query). Here is the query: SELECT entry FROM Entry AS entry, IN (entry.parentEntries) AS parent WHERE parent = :entry This query fails on execution, with an ArgumentException : openjpa-1.2.1-r752877:753278 nonfatal user error org.apache.openjpa.persistence.ArgumentException: The parameter entry is of type com.aperigeek.jtentative.entity.Entry, but the declaration in the query is for type java.util.List at org.apache.openjpa.persistence.QueryImpl.validateParameter(QueryImpl.java:287) at org.apache.openjpa.persistence.QueryImpl.validateParameters(QueryImpl.java:274) at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:248) at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:294) ... This query works fine with other persistence provider (the above code has been successfully tested with Toplink). Am I missing something here? I saw in an old bug report (#OPENJPA-190) someone having the same difficulties. Could this be an OpenJPA bug? Thanks, -- Vivien Barousse
Re: Insert is called instead of Update when merge() with complex IDs
This is a bug in openjpa. JIRA-1371 is open to address this problem. - Original Message From: Constantine Kulak c...@mail.by To: users@openjpa.apache.org Sent: Fri, October 30, 2009 12:54:19 AM Subject: Re: Insert is called instead of Update when merge() with complex IDs Hello! Neither of those, I just execute the program twice. So, it's not about the managed / detached entities. Fay Wang wrote: The em.merge will return the merged entity. EntityA mergedEntity = em.merge(newEntity); During your second merge call, did you call em.merge(mergedEntity) or em.merge(newEntity)? Fay - Original Message From: Constantine Kulak c...@mail.by To: users@openjpa.apache.org Sent: Thu, October 29, 2009 4:19:11 AM Subject: Insert is called instead of Update when merge() with complex IDs Hello! I need some help in the following situation - completely stuck with it :( Can you please point me in some direction? Anyway, thanks in advance! OpenJPA version is 2.0.0-M3. So, I have three entities: Prognosis contains many PrognosisEntry, and PrognosisEntry references some Stock. So, it's a many-to-many for Prognosis and Stock, having some additional data at PrognosisEntry join table. Fields: Stock: index (PK) length Prognosis: station (PK) type (PK) PrognosisEntry: prognosis.station (FK, PK) prognosis.type (FK, PK) stock.index (FK, PK) localState timestamp Relationship between Prognosis and PrognosisEntry is bidirectional (I really need Prognosis.getEntries() method). All IDs are taken from the real world and not generated because this data comes from the backend in XML and then deserialized using JAXB (annotations are removed from the sources below to simplify it). Then I do merge() and expect the data in the DB to be updated with the fresh one. When I call merge() for the 1st time (against the empty DB), all the necessary INSERTs are done. But when called for the 2nd time with the same data (I expect no changes to the DB), the exception is thrown because of the duplicate primary keys. Unexpectedly, it does INSERT instead of UPDATE in this case. The problem is seems to be with the PrognosisEntry-Stock relationship, because when I remove it (replacing reference to Stock in the PrognosisEntry with some dummy ID field) it starts working as expected (calls UPDATE). Exception and logs are given after the sources below. * Source for Prognosis.java: @Entity(name = Prognosis) @Table(name = PROGNOSIS) @IdClass(Prognosis.PrognosisId.class) @Inheritance(strategy = InheritanceType.JOINED) public class Prognosis { protected ListPrognosisEntry entries; protected String station; protected String type; @OneToMany(targetEntity = PrognosisEntry.class, cascade = {CascadeType.MERGE}, mappedBy=prognosis, fetch=FetchType.EAGER) public ListPrognosisEntry getEntries() { if (entries == null) { entries = new ArrayListPrognosisEntry(); } return this.entries; } public void setEntries(ListPrognosisEntry entries) { this.entries = entries; } @Id @Column(name = STATION) public String getStation() { return station; } public void setStation(String value) { this.station = value; } @Id @Column(name = TYPE_) public String getType() { return type; } public void setType(String value) { this.type = value; } public boolean equals(Object object) { ... } public int hashCode() { ... } public static class PrognosisId { protected String station; protected String type; public String getStation() { return station; } public void setStation(String value) { this.station = value; } public String getType() { return type; } public void setType(String value) { this.type = value; } public boolean equals(Object object) { ... } public int hashCode() { ... } } } * Source for PrognosisEntry.java: @Entity(name = PrognosisEntry) @Table(name = PROGNOSISENTRY) @Inheritance(strategy = InheritanceType.JOINED) @IdClass(PrognosisEntry.PrognosisEntryId.class) public class PrognosisEntry { protected String timestamp; protected String localState; protected Prognosis prognosis; protected Stock stock; @Id @ManyToOne(targetEntity = Stock.class, cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER) public Stock getStock() { return stock; } public void setStock(Stock stock) { this.stock = stock; } @Id @ManyToOne(targetEntity = Prognosis.class, cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER) public Prognosis getPrognosis() { return prognosis; } public void setPrognosis(Prognosis prognosis
Re: Insert is called instead of Update when merge() with complex IDs
The em.merge will return the merged entity. EntityA mergedEntity = em.merge(newEntity); During your second merge call, did you call em.merge(mergedEntity) or em.merge(newEntity)? Fay - Original Message From: Constantine Kulak c...@mail.by To: users@openjpa.apache.org Sent: Thu, October 29, 2009 4:19:11 AM Subject: Insert is called instead of Update when merge() with complex IDs Hello! I need some help in the following situation - completely stuck with it :( Can you please point me in some direction? Anyway, thanks in advance! OpenJPA version is 2.0.0-M3. So, I have three entities: Prognosis contains many PrognosisEntry, and PrognosisEntry references some Stock. So, it's a many-to-many for Prognosis and Stock, having some additional data at PrognosisEntry join table. Fields: Stock: index (PK) length Prognosis: station (PK) type (PK) PrognosisEntry: prognosis.station (FK, PK) prognosis.type (FK, PK) stock.index (FK, PK) localState timestamp Relationship between Prognosis and PrognosisEntry is bidirectional (I really need Prognosis.getEntries() method). All IDs are taken from the real world and not generated because this data comes from the backend in XML and then deserialized using JAXB (annotations are removed from the sources below to simplify it). Then I do merge() and expect the data in the DB to be updated with the fresh one. When I call merge() for the 1st time (against the empty DB), all the necessary INSERTs are done. But when called for the 2nd time with the same data (I expect no changes to the DB), the exception is thrown because of the duplicate primary keys. Unexpectedly, it does INSERT instead of UPDATE in this case. The problem is seems to be with the PrognosisEntry-Stock relationship, because when I remove it (replacing reference to Stock in the PrognosisEntry with some dummy ID field) it starts working as expected (calls UPDATE). Exception and logs are given after the sources below. * Source for Prognosis.java: @Entity(name = Prognosis) @Table(name = PROGNOSIS) @IdClass(Prognosis.PrognosisId.class) @Inheritance(strategy = InheritanceType.JOINED) public class Prognosis { protected ListPrognosisEntry entries; protected String station; protected String type; @OneToMany(targetEntity = PrognosisEntry.class, cascade = {CascadeType.MERGE}, mappedBy=prognosis, fetch=FetchType.EAGER) public ListPrognosisEntry getEntries() { if (entries == null) { entries = new ArrayListPrognosisEntry(); } return this.entries; } public void setEntries(ListPrognosisEntry entries) { this.entries = entries; } @Id @Column(name = STATION) public String getStation() { return station; } public void setStation(String value) { this.station = value; } @Id @Column(name = TYPE_) public String getType() { return type; } public void setType(String value) { this.type = value; } public boolean equals(Object object) { ... } public int hashCode() { ... } public static class PrognosisId { protected String station; protected String type; public String getStation() { return station; } public void setStation(String value) { this.station = value; } public String getType() { return type; } public void setType(String value) { this.type = value; } public boolean equals(Object object) { ... } public int hashCode() { ... } } } * Source for PrognosisEntry.java: @Entity(name = PrognosisEntry) @Table(name = PROGNOSISENTRY) @Inheritance(strategy = InheritanceType.JOINED) @IdClass(PrognosisEntry.PrognosisEntryId.class) public class PrognosisEntry { protected String timestamp; protected String localState; protected Prognosis prognosis; protected Stock stock; @Id @ManyToOne(targetEntity = Stock.class, cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER) public Stock getStock() { return stock; } public void setStock(Stock stock) { this.stock = stock; } @Id @ManyToOne(targetEntity = Prognosis.class, cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER) public Prognosis getPrognosis() { return prognosis; } public void setPrognosis(Prognosis prognosis) { this.prognosis = prognosis; } @Column(name = TIMESTAMP_, length = 255) public String getTimestamp() { return timestamp; } public void setTimestamp(String value) { this.timestamp = value; } @Basic @Column(name = LOCALSTATE, length = 255) public String getLocalState() { return localState; } public void setLocalState(String value) { this.localState = value; } public boolean equals(Object object) { ... } public int hashCode() { ... } public static class PrognosisEntryId {
Re: Limit the size of the projection of a query
You can call the following API to limit the number of rows returned by the query: Query.setMaxResults(maxResults); - Original Message From: Michael Simons michael.sim...@optitool.de To: users@openjpa.apache.org Sent: Thu, October 29, 2009 11:13:12 AM Subject: Limit the size of the projection of a query Hello, Is there a way in JPA or OpenJPA to limit the number of rows returned by a query? In our formerly used JDO-Implementation there was a function called maxrows doing so. I know there are several databases that support a limitation of the projection. But how can I achieve this in JPA? Kind Regards, Michael
Re: left join with filter on joined table
Hi, You might want to try: Select p.firstname, Case v.type WHEN 'v1' THEN v.type WHEN 'v2' THEN 'null' ELSE 'null' END + from Patient p left join p.vaccinCollection v However, this approach still requires post-processing of 'null' string to null value. Fay - Original Message From: Michel Ganguin mic...@ganguin.net To: users@openjpa.apache.org Sent: Mon, October 26, 2009 10:46:22 AM Subject: left join with filter on joined table Hi, I have two tables: patient --- id firstname lastname vaccine --- id patientid date type With an ejbqlquery i want to retrieve all patients that have 0 to n vaccines Select p.firstname, v.type from Patient p left join p.vaccinCollection v result: p1, v1 p1, v2 p2, v2 p3, null Now I want to filter by vaccine type (all patients that have 0 to n vaccines of type v2): Select p.firstname, v.type from Patient p left join p.vaccinCollection v where v.type = 'v2' result: p1, v2 p2, v2 But this filtered out patients without vaccine, so i tried: Select p.firstname, v.type from Patient p left join p.vaccinCollection v where v.type = 'v2' OR v.type is null result: p1, v2 p2, v2 p3, null This looks like what I want but doesn't work for v1 Select p.firstname, v.type from Patient p left join p.vaccinCollection v where v.type = 'v1' OR v.type is null result: p1, v1 p3, null I want to have p2, null in the result. How can I do that? I'm not against getting all result (first query) and filter out the unwanted data but this vaccine table becomes very huge and it sould be a dramatic performance loss! Is there a way to avoid post-join-filtering by adding a query hint or something like this. Or to use parameters in entity relations? If there is no solution I would use native queries but how can I map join queries to entities? Thanks in advance. Michel Ganguin
Re: Fetchgroups recursion problem
By default, the max fetch depth is set to -1 for no limit. However, this graph is an indirect recursion, i.e., from State - Transition - State. I think this makes Openjpa to stop prematurely... Fay - Original Message From: calin014 calin...@gmail.com To: users@openjpa.apache.org Sent: Fri, October 23, 2009 2:13:56 AM Subject: Re: Fetchgroups recursion problem Thanks for the quick reply. I tried that but with no luck. I did something like this before executing the query: OpenJPAEntityManager ojem = OpenJPAPersistence.cast(entityManager); System.out.println(getMaxFetchDepth() before: + ojem.getFetchPlan().getMaxFetchDepth()); ojem.getFetchPlan().setMaxFetchDepth(15); System.out.println(getMaxFetchDepth() after: + ojem.getFetchPlan().getMaxFetchDepth()); ojem.getFetchPlan().addFetchGroups(State_OutgoingTransitions, IncomingTransitions); The output is: getMaxFetchDepth() before: -1 getMaxFetchDepth() after: 15 The result is the same as described in the first post. Am i doing it wrong? Pinaki Poddar wrote: Hi, There are two attributes that control the closure of a graph as fetched by a FetchPlan/FetchConfiguration, namely Recursion Depth Max Fetch Depth According to the cited use case, Max Fetch Depth is the relevant attribute that will control depth of traversal from a root entity (s1). By default, the max fetch depth is set to 1 and hence the immediate neighbors of s1 are fetched and not s4 or s5 which is at depth 2 from s1. Recursion depth, on the other hand, controls the depth of traversal for recursive relation on types. If s1 had a recursive relation then recursion depth would have controlled traversal of that relation path. -- View this message in context: http://n2.nabble.com/Fetchgroups-recursion-problem-tp3874382p3877617.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Fetchgroups recursion problem
This apparently has something to do with the _availableRecursion in the FetchConfigurationImpl. I hardcoded a big number and the whole thing is retrieved. There seem a missing link between the recursionDepth in the FetchGroup and this field. More investigation is underway... Fay - Original Message From: calin014 calin...@gmail.com To: users@openjpa.apache.org Sent: Fri, October 23, 2009 10:37:46 AM Subject: Re: Fetchgroups recursion problem Craig L Russell wrote: One other thing to consider: there is a fetch plan for each query that may be different from the fetch plan for other operations. If you're modifying the fetch plan after the query is created, the modifications won't affect the query. Well, the order is: OpenJPAEntityManager ojem = OpenJPAPersistence.cast(entityManager); ojem.getFetchPlan().setMaxFetchDepth(15); ojem.getFetchPlan().addFetchGroups(State_OutgoingTransitions, State_IncomingTransitions); Flow flow = entityManager.find(Flow.class, id); And the query is affected because, if i don't add the fetch groups, only the first state gets loaded into memory. Fay Wang wrote: By default, the max fetch depth is set to -1 for no limit. However, this graph is an indirect recursion, i.e., from State - Transition - State. I think this makes Openjpa to stop prematurely... If this is the case, is there a workaround? -- View this message in context: http://n2.nabble.com/Fetchgroups-recursion-problem-tp3874382p3880166.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Fetchgroups recursion problem
Hi, Since this is an indirect recursion, i.e., from State - Transition - State - Transition - ... you need to add the recursionDepth in both State and Transition as shown below: (1) State.java @Entity @FetchGroups( { @FetchGroup(name = State_OutgoingTransitions, attributes = {...@fetchattribute(name = outgoingTransitions, recursionDepth = 10) }), @FetchGroup(name = State_IncomingTransitions, attributes = {...@fetchattribute(name = incomingTransitions, recursionDepth = 10) }) }) public class State implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 64) private String name; @OneToMany(mappedBy = fromState, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) private ListTransition outgoingTransitions; @OneToMany(mappedBy = toState, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) private ListTransition incomingTransitions; ... } (2) Transition.java @Entity @FetchGroups( { @FetchGroup(name = Transition_ToState, attributes = {...@fetchattribute(name = toState, recursionDepth = 10) }), @FetchGroup(name = Transition_FromState, attributes = {...@fetchattribute(name = fromState, recursionDepth = 10) }) }) public class Transition implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 64) private String name; @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) @JoinColumn(name = FROM_STATE_ID, referencedColumnName = ID) private State fromState; @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) @JoinColumn(name = TO_STATE_ID, referencedColumnName = ID) private State toState; ... } (3) When doing the findBy operation, add the fetch groups to the fetch plan: EntityManager em = emf.createEntityManager(); OpenJPAEntityManager oem = OpenJPAPersistence.cast (em); JDBCFetchPlan jfp = (JDBCFetchPlan)oem.getFetchPlan(); jfp.addFetchGroup(State_OutgoingTransitions); jfp.addFetchGroup(State_IncomingTransitions); jfp.addFetchGroup(Transition_ToState); jfp.addFetchGroup(Transition_FromState); State s1 = em.find(State.class, 2); The resulting s1 should contain the complete graph. Regards, Fay : - Original Message From: Fay Wang fyw...@yahoo.com To: users@openjpa.apache.org Sent: Fri, October 23, 2009 2:44:13 PM Subject: Re: Fetchgroups recursion problem This apparently has something to do with the _availableRecursion in the FetchConfigurationImpl. I hardcoded a big number and the whole thing is retrieved. There seem a missing link between the recursionDepth in the FetchGroup and this field. More investigation is underway... Fay - Original Message From: calin014 calin...@gmail.com To: users@openjpa.apache.org Sent: Fri, October 23, 2009 10:37:46 AM Subject: Re: Fetchgroups recursion problem Craig L Russell wrote: One other thing to consider: there is a fetch plan for each query that may be different from the fetch plan for other operations. If you're modifying the fetch plan after the query is created, the modifications won't affect the query. Well, the order is: OpenJPAEntityManager ojem = OpenJPAPersistence.cast(entityManager); ojem.getFetchPlan().setMaxFetchDepth(15); ojem.getFetchPlan().addFetchGroups(State_OutgoingTransitions, State_IncomingTransitions); Flow flow = entityManager.find(Flow.class, id); And the query is affected because, if i don't add the fetch groups, only the first state gets loaded into memory. Fay Wang wrote: By default, the max fetch depth is set to -1 for no limit. However, this graph is an indirect recursion, i.e., from State - Transition - State. I think this makes Openjpa to stop prematurely... If this is the case, is there a workaround? -- View this message in context: http://n2.nabble.com/Fetchgroups-recursion-problem-tp3874382p3880166.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Collection of enums: supported yet?
This feature is newly added in JPA 2.0 spec. I don't think it will be added to 1.2.x release. - Original Message From: Matthew Adams matt...@matthewadams.me To: users@openjpa.apache.org Sent: Friday, September 4, 2009 8:35:32 AM Subject: Re: Collection of enums: supported yet? Sweet. Do you suppose that will be in a 1.2.x release soon? On Thu, Sep 3, 2009 at 2:29 PM, Fay Wangfyw...@yahoo.com wrote: This is currently supported in openjpa trunk. @ElementCollection @Enumerated(EnumType.STRING) protected ListCreditRating cr = new ArrayListCreditRating(); where public enum CreditRating { POOR, GOOD, EXCELLENT }; Regards, Fay - Original Message From: Matthew Adams matt...@matthewadams.me To: users@openjpa.apache.org Sent: Thursday, September 3, 2009 1:00:59 PM Subject: Collection of enums: supported yet? Hi all, I searched the mailing list to determine the OpenJPA metadata required to store a collection of an enum type (ie, CollectionColor, SetColor, ListColor), and I noticed that Patrick answered a while ago (ca. 2007) that Kodo supports it but not OpenJPA. Is this still the case? I can't find doc in the OpenJPA reference guide that explains how to map collections of enums. I don't really need EnumSet or EnumMap, either. A plain, old CollectionColor will do fine. If it's currently supported, how to I configure OpenJPA to store the values of an enum in a collection as that enum's name()? Thanks, Matthew -- mailto:matt...@matthewadams.me skype:matthewadams12 yahoo:matthewadams aol:matthewadams12 google-talk:matthewadam...@gmail.com msn:matt...@matthewadams.me http://matthewadams.me http://www.linkedin.com/in/matthewadams -- mailto:matt...@matthewadams.me skype:matthewadams12 yahoo:matthewadams aol:matthewadams12 google-talk:matthewadam...@gmail.com msn:matt...@matthewadams.me http://matthewadams.me http://www.linkedin.com/in/matthewadams
Re: Collection of enums: supported yet?
This is currently supported in openjpa trunk. @ElementCollection @Enumerated(EnumType.STRING) protected ListCreditRating cr = new ArrayListCreditRating(); where public enum CreditRating { POOR, GOOD, EXCELLENT }; Regards, Fay - Original Message From: Matthew Adams matt...@matthewadams.me To: users@openjpa.apache.org Sent: Thursday, September 3, 2009 1:00:59 PM Subject: Collection of enums: supported yet? Hi all, I searched the mailing list to determine the OpenJPA metadata required to store a collection of an enum type (ie, CollectionColor, SetColor, ListColor), and I noticed that Patrick answered a while ago (ca. 2007) that Kodo supports it but not OpenJPA. Is this still the case? I can't find doc in the OpenJPA reference guide that explains how to map collections of enums. I don't really need EnumSet or EnumMap, either. A plain, old CollectionColor will do fine. If it's currently supported, how to I configure OpenJPA to store the values of an enum in a collection as that enum's name()? Thanks, Matthew -- mailto:matt...@matthewadams.me skype:matthewadams12 yahoo:matthewadams aol:matthewadams12 google-talk:matthewadam...@gmail.com msn:matt...@matthewadams.me http://matthewadams.me http://www.linkedin.com/in/matthewadams
Re: OpenJPA1.2.2 - NativeQuery - IN clause
Sorry, I probably confuse you about the JPQL and native (SQL) query. The CollectionString approach will work with JPQL, but not with SQL (native query, regardless it is named or not). For JPQL, the Query object is created in the following way: Query q = em.createQuery(select e from Entity1 e where e.name in (?1)); For SQL or native query, the Query object is created in the following way: Query q = em.createNativeQuery(select e.* from Entity1Table e where e.name in (?1)); For the SQL, you either have to provide the literals in your IN clause as you did, e.g. in (A, B, C) or you have to set the parameter markers, e.g., in (?1, ?2, ?3) and then set parameters to the query accordingly. - Original Message From: HaricotBean b...@wilkins-family.org.uk To: users@openjpa.apache.org Sent: Tuesday, September 1, 2009 7:10:45 AM Subject: Re: OpenJPA1.2.2 - NativeQuery - IN clause Thanks to all. I did try the CollectionString approach but OpenJPA generates an error and complains about the underlying type (ArrayList, HashSet, etc.) being an invalid type for th expression. Not being familiar with the OpenJPA source I took a quick look at fisheye for org.apache.openjpa.persistence.query.ArrayExpression and it seems to suggest that it expects an String[]. That failed to produce the expect results. In the end I fell back to generating the sql string manually and abandoning NamedQuery, e.g: private static String mostRefersType = select count(e.eid), e.* from Entity e, Property p where e.eid=p.refersTo and p.type IN ( ) group by e.eid order by count(e.eid) desc;; public static ListEntityHolder findMostUsed(Registry registry, CollectionString types, int limit) { ... sql = mostRefersType.replace(, asString(types)); q = registry.getEntityManager().createNativeQuery(sql, MostUsedResults); list = (ListObject[]) q.getResultList(); ... } private static String asString(CollectionString types) { StringBuffer typesAsString = new StringBuffer(); int i = 0; for (String type : types) { if ( typesAsString.length() 0 ) typesAsString.append(,); typesAsString.append('+type+'); } return typesAsString.toString(); } This approach works fine. I have to assume that there is either a bug in the Native Named Query processing or some requirement that isnt very well documented. Regards -- View this message in context: http://n2.nabble.com/OpenJPA1-2-2-NativeQuery-IN-clause-tp3556433p3560749.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OpenJPA1.2.2 - NativeQuery - IN clause
Hi, For native query: String sql = select count(e.eid), e.* from Entity e, Property p where e.eid=p.refersTo and p.type IN ( ?1 ) group by e.eid order by count(e.eid) desc; As you observed, the following parameter setting will work, since you have only one parameter marker: query.setParameter(1, A); If you want to match with more than one value, you have to modify your sql, for example, to p.type IN ( ?1, ?2, ?3) and in the parameter setting, you have to set it in accordance with your parameter markers: query.setParameter(1, A); query.setParameter(2, B); query.setParameter(3, C); This is the SQL syntax, and openjap simply sends this request to the backend server without any further modifications. Setting the parameter value to an array or a collection will not work. Hope this helps. Regards, Fay - Original Message From: HaricotBean b...@wilkins-family.org.uk To: users@openjpa.apache.org Sent: Monday, August 31, 2009 3:28:28 PM Subject: OpenJPA1.2.2 - NativeQuery - IN clause Which type is NativeQuery expecting for a parameter that maps to a IN clause? Through trial and error I found that Collections cause an error to be throw and Arrays execute but return no results. However if I pass a single String value it works... @NamedNativeQuery(name = Entity.mostRefersType, query = select count(e.eid), e.* from Entity e, Property p where e.eid=p.refersTo and p.type IN ( ?1 ) group by e.eid order by count(e.eid) desc;, resultSetMapping = MostUsedResults), Surprisingly (to me at least) the following has been my observation: query.setParameter(1, A); // successful query.setParameter(1, {A,B}); // executes but fails to match CollectionString set = new ArraySet(); set.add(A); query.setParameter(1, set); // throws invalid parameter exception on execute Does anyone have any clues as to what the right approach might be to use a named query. The alternative is to build a string representation of the sql statement but I would like to find the answer. Regards ... -- View this message in context: http://n2.nabble.com/OpenJPA1-2-2-NativeQuery-IN-clause-tp3556433p3556433.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OpenJPA1.2.2 - NativeQuery - IN clause
Just wanted to mention that JPQL allows collection parameter in the IN clause. String jpql = select count(e.eid), e from Entity e, Property p where e.eid=p.refersTo and p.type IN ( ?1 ) group by e.eid order by count(e.eid) desc; In this case, you can set a Collection object to the parameter: Query q = em.createQuery(jpql); List coll = new ArrayList(); coll.add(A); coll.add(B); coll.add(C); q.setParameter(1, coll); Internally, openjpa will loop through the collection and generate a SQL that has the same number of parameter markers as the number of elements in your collection, and set parameters accordingly. The push-down sql will look like: select ... where ... p.typeIN (?1, ?2, ?3) -Fay - Original Message From: Fay Wang fyw...@yahoo.com To: users@openjpa.apache.org Sent: Monday, August 31, 2009 8:59:56 PM Subject: Re: OpenJPA1.2.2 - NativeQuery - IN clause Hi, For native query: String sql = select count(e.eid), e.* from Entity e, Property p where e.eid=p.refersTo and p.type IN ( ?1 ) group by e.eid order by count(e.eid) desc; As you observed, the following parameter setting will work, since you have only one parameter marker: query.setParameter(1, A); If you want to match with more than one value, you have to modify your sql, for example, to p.type IN ( ?1, ?2, ?3) and in the parameter setting, you have to set it in accordance with your parameter markers: query.setParameter(1, A); query.setParameter(2, B); query.setParameter(3, C); This is the SQL syntax, and openjap simply sends this request to the backend server without any further modifications. Setting the parameter value to an array or a collection will not work. Hope this helps. Regards, Fay - Original Message From: HaricotBean b...@wilkins-family.org.uk To: users@openjpa.apache.org Sent: Monday, August 31, 2009 3:28:28 PM Subject: OpenJPA1.2.2 - NativeQuery - IN clause Which type is NativeQuery expecting for a parameter that maps to a IN clause? Through trial and error I found that Collections cause an error to be throw and Arrays execute but return no results. However if I pass a single String value it works... @NamedNativeQuery(name = Entity.mostRefersType, query = select count(e.eid), e.* from Entity e, Property p where e.eid=p.refersTo and p.type IN ( ?1 ) group by e.eid order by count(e.eid) desc;, resultSetMapping = MostUsedResults), Surprisingly (to me at least) the following has been my observation: query.setParameter(1, A); // successful query.setParameter(1, {A,B}); // executes but fails to match CollectionString set = new ArraySet(); set.add(A); query.setParameter(1, set); // throws invalid parameter exception on execute Does anyone have any clues as to what the right approach might be to use a named query. The alternative is to build a string representation of the sql statement but I would like to find the answer. Regards ... -- View this message in context: http://n2.nabble.com/OpenJPA1-2-2-NativeQuery-IN-clause-tp3556433p3556433.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Key and Value limitations in a MapKey,Value
Hi Krzysztof, The exception reported in JIRA-291 is apparently different from the exception that you reported: [java] Caused by: openjpa-2.0.0-SNAPSHOT-r422266:798026 fatal user error org.apache.openjpa.util.MetaDataException: Field DerivedTS.parentModel cannot be a primary key. It is of an unsupported type. [java] at org.apache.openjpa.meta.ClassMetaData.validateAppIdClassPKs(ClassMetaData.java:2105) I found that changing AbstractModel from MappedSuperClass to an Entity is a workaround for this exception. Can you try it? At the same time, will take a look at the JIRA-291. Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 6:12:19 AM Subject: Re: Key and Value limitations in a MapKey,Value Hello Fay, Thank you for the hint. In the end I narrowed down the problem to self-referencing, composite ID which is not supported. Kludging with a generated syntatic Id helps in cases where object model is modifiable but it would be wonderful to have this supported at some time. Do you think it is possible in a foreseeable future? https://issues.apache.org/jira/browse/OPENJPA-291 That's a pity since more and more DBs support hierarchical queries natively (connect-by in oracle, with() in db2, recently postgres) and gives huge performance kick where complicated traversal is needed in a single query. Cheers Krzysztof Fay Wang wrote: Hi, Can you try making AbstractModel an Entity instead of MappedSuperClass, and making this class a concrete class as shown below? // abstract class that has common identity and some additional fields, it is //a Key in a map @Inheritance(strategy = InheritanceType.JOINED) @Entity @IdClass(ModelId.ModelImplId.class) public class AbstractModel { ... } -Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 5, 2009 9:31:53 AM Subject: Key and Value limitations in a MapKey,Value Hello, Seems I am completely knotted in a convoluted class graph without any hint from documentation, spec or forum archive. Could somebody enlighten me if it is possible to: A. Have a Key in a persistent MapKey,Value such as 1. the Key has a composite ID composed of classes which have composite IDs themselves? and 2. They Key is an abstract class that is also used in a Value as a parent in ManyToOne relationship being the part of the Values identity (actual objects - parent and Value being rather different entities) Hope this example clarifies this rather complicated scenario: //abstract class of which children are Values in a map @Entity @IdClass(AbstractTS.TSId.class) //TSId covers SomeOtherClass identity too @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class AbstractTS { @id SomeOtherClass parent; @id int local_id; @OneToMany private MapModelId, DerivedTS derivedMap; // DerivedTS inherits from AbstractTS - seems to impossible to be mapped properly. } // abstract class that has common identity and some additional fields, it is a Key in a map @Inheritance(strategy = InheritanceType.JOINED) @MappedSuperclass @IdClass(ModelId.ModelImplId.class) public abstract class AbstractModel { @id AbstractTS parent; @id int x; @id double y; @Basic @Lob double[] some_common_data; } // Identity domain class, that is in fact stripped down version of an abstractModel, both reuse same ID class, used to retrieve unknown models. @IdClass(ModelId.ModelImplId.class) @Embeddable public class ModelId { @ManyToOne public AbstractTS parentTS; //could be either DerivedTS or RawTS. @Id @Basic public double some_value; @Id public int modelType; @Basic int some_derived_value; } @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) //identity derived from AbstractTS public class RawTS extends AbstractTS { @Basic int some_values; } @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @IdClass(DerivedTS.DerivedTSId.class) // inherits from TSId with additional Identities for parentTS and parentModel public class DerivedTS extends AbstractTS { @ManyToOne //@PrimaryKeyJoinColumns(..) // possibly to provide direct mappings to either RawTS or DerivedTS identity fields @Id private AbstractTS parentTS; @Id @ManyToOne //@PrimaryKeyJoinColumns( {... }) //possibly to provide direct mappings to any model derived from AbstractModel private AbstractModel parentModel = null; } To create any working mapping for MapModelId, DerivedTS seems like an impossible mission, I would appreciate any hints if it is doable at all. I tried various combinations of @ManyToOne combined with @PrimaryKeys, @MapPrimaryKeys, @ElementCollection etc. Persistence.xml lists all
Re: Enum as a Key in a Map
Hi Krzysztof, I could not reproduce your problem using my own test case. From your annotation, I would suppose that tsType is a persistent field of the map value, and it is of EnumType. Could you provide your domain model for further investigation? Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 10:30:00 AM Subject: Re: Enum as a Key in a Map Hello, I'm reviving this as @MapKeyEnumerated has been introduced recently which seemed addressing this issue. Unfortunately, if I use enum as a key where Source is amended with following annotation for the map: @OneToMany(mappedBy = source,cascade={ CascadeType.ALL },fetch = FetchType.LAZY, orphanRemoval = true) @MapKeyEnumerated(EnumType.ORDINAL) @MapKey(name = tsType) objects are committed gracefully and generated data and schema looks ok, but the exception reappears during retrieval: java.lang.ClassCastException: TSType cannot be cast to org.apache.openjpa.util.ObjectId gaia.cu7.omimpl.ClassificationResultsImpl.pcCopyKeyFieldsToObjectId(ClassificationResultsImpl.java) org.apache.openjpa.enhance.PCRegistry.copyKeyFieldsToObjectId(PCRegistry.java:172) org.apache.openjpa.util.ApplicationIds.fromPKValues(ApplicationIds.java:219) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:216) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:147) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:934) org.apache.openjpa.jdbc.sql.AbstractResult.load(AbstractResult.java:280) org.apache.openjpa.jdbc.sql.SelectImpl$SelectResult.load(SelectImpl.java:2349) org.apache.openjpa.jdbc.meta.strats.RelationToManyInverseKeyFieldStrategy.loadElement(RelationToManyInverseKeyFieldStrategy.java:87) org.apache.openjpa.jdbc.meta.strats.StoreCollectionFieldStrategy.load(StoreCollectionFieldStrategy.java:554) org.apache.openjpa.jdbc.meta.FieldMapping.load(FieldMapping.java:919) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:641) org.apache.openjpa.kernel.DelegatingStoreManager.load(DelegatingStoreManager.java:116) org.apache.openjpa.kernel.ROPStoreManager.load(ROPStoreManager.java:78) org.apache.openjpa.kernel.StateManagerImpl.loadFields(StateManagerImpl.java:3035) org.apache.openjpa.kernel.StateManagerImpl.loadField(StateManagerImpl.java:3113) org.apache.openjpa.kernel.StateManagerImpl.beforeAccessField(StateManagerImpl.java:1606) org.apache.openjpa.kernel.StateManagerImpl.accessingField(StateManagerImpl.java:1591) Source.pcGetclassificationResultsMap(SourceImpl.java) 2.0.0 trunk version. Is is possible to use enumeration as a Key in a directly mapped (no join table), bidirectional Map? Anybody with a workaround? Best regards, Krzysztof Krzysztof wrote: Indeed, changing the map to be keyed on a plain type does not solve the problem until the owning 'source' field becomes plain type too. So, Source ... @OneToMany(mappedBy=source,cascade=CascadeType.ALL) @MapKey(name=tsType) private MapInteger, TSImpl tsMap; ... /Source TSimpl @Id @Basic(optional=false) @Enumerated(EnumType.ORDINAL) @Column(name=tsType,updatable=false) private TSType tsType; //stays as enum, same exception thrown /TSImpl gives exactly same cast exception, but if we change this part of Id to int it works. Also calling persist on root persists map elements properly. @Id @Basic(optional=false) //@Enumerated(EnumType.ORDINAL) @Column(name=tsType,updatable=false) //private TSType tsType; private int tsType; This is not really elegant and affects a lot of code. Could you please suggest any workaround so enum could be used as a key and is compatible with ObjectId? Annotating enum as Embeddable gives enhancer error and creating class wrapping an enum is also questionable in this particular case. Best regards, Krzysztof -- View this message in context: http://n2.nabble.com/Enum-as-a-Key-in-a-Map-tp1639596p3474057.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Enum as a Key in a Map
Hi Krzysztof, Given your description below, I am able to reproduce this problem. I will take a look at it. Thanks! Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 11:38:36 AM Subject: Re: Enum as a Key in a Map Thanks Kevin, Certainly, I have checked your roadmap and the relevant JIRA issue, also test cases you have in the trunk - have not seen @MapKeyEnumerated used with @OneToMany though. In the Id class of the child I kept enum as a field and used ordinal() obviously. I'm debugging this now and can see that _key enum field of the oid passed to pcCopyKeyFieldsToObjectId is null. As mentioned before, value in the DB looks ok. After dissasembling public void pcCopyKeyFieldsToObjectId(FieldSupplier fieldsupplier, Object obj) of that class I can see that TSimplId.tsType = (TSType)((ObjectId)fieldsupplier.fetchObjectField(2 + i)).getId(); for some reason enum is treated as a composite Id and cast to ObjectId fails? Cheers, Krzysztof Kevin Sutter wrote: Hi Krzysztof, The MapKeyEnumerated support was introduced as part of JPA 2.0. It looks like this was committed via OPENJPA-1055. I've pinged Fay (owner of the JIRA) to take a look to see if she has any ideas. If you are interested in what's been done for JPA 2.0 already, you can reference our roadmap [1]. I'm bringing this up in case you try some other JPA 2.0 items that haven't even been touched yet... :-) Thanks, Kevin [1] http://openjpa.apache.org/jpa-20-roadmap.html On Wed, Aug 19, 2009 at 12:30 PM, Krzysztof yaz...@gmail.com wrote: Hello, I'm reviving this as @MapKeyEnumerated has been introduced recently which seemed addressing this issue. Unfortunately, if I use enum as a key where Source is amended with following annotation for the map: @OneToMany(mappedBy = source,cascade={ CascadeType.ALL },fetch = FetchType.LAZY, orphanRemoval = true) @MapKeyEnumerated(EnumType.ORDINAL) @MapKey(name = tsType) objects are committed gracefully and generated data and schema looks ok, but the exception reappears during retrieval: java.lang.ClassCastException: TSType cannot be cast to org.apache.openjpa.util.ObjectId gaia.cu7.omimpl.ClassificationResultsImpl.pcCopyKeyFieldsToObjectId(ClassificationResultsImpl.java) org.apache.openjpa.enhance.PCRegistry.copyKeyFieldsToObjectId(PCRegistry.java:172) org.apache.openjpa.util.ApplicationIds.fromPKValues(ApplicationIds.java:219) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:216) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:147) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:934) org.apache.openjpa.jdbc.sql.AbstractResult.load(AbstractResult.java:280) org.apache.openjpa.jdbc.sql.SelectImpl$SelectResult.load(SelectImpl.java:2349) org.apache.openjpa.jdbc.meta.strats.RelationToManyInverseKeyFieldStrategy.loadElement(RelationToManyInverseKeyFieldStrategy.java:87) org.apache.openjpa.jdbc.meta.strats.StoreCollectionFieldStrategy.load(StoreCollectionFieldStrategy.java:554) org.apache.openjpa.jdbc.meta.FieldMapping.load(FieldMapping.java:919) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:641) org.apache.openjpa.kernel.DelegatingStoreManager.load(DelegatingStoreManager.java:116) org.apache.openjpa.kernel.ROPStoreManager.load(ROPStoreManager.java:78) org.apache.openjpa.kernel.StateManagerImpl.loadFields(StateManagerImpl.java:3035) org.apache.openjpa.kernel.StateManagerImpl.loadField(StateManagerImpl.java:3113) org.apache.openjpa.kernel.StateManagerImpl.beforeAccessField(StateManagerImpl.java:1606) org.apache.openjpa.kernel.StateManagerImpl.accessingField(StateManagerImpl.java:1591) Source.pcGetclassificationResultsMap(SourceImpl.java) 2.0.0 trunk version. Is is possible to use enumeration as a Key in a directly mapped (no join table), bidirectional Map? Anybody with a workaround? Best regards, Krzysztof Krzysztof wrote: Indeed, changing the map to be keyed on a plain type does not solve the problem until the owning 'source' field becomes plain type too. So, Source ... @OneToMany(mappedBy=source,cascade=CascadeType.ALL) @MapKey(name=tsType) private MapInteger, TSImpl tsMap; ... /Source TSimpl @Id @Basic(optional=false) @Enumerated(EnumType.ORDINAL) @Column(name=tsType,updatable=false) private TSType tsType; //stays as enum, same exception thrown /TSImpl gives exactly same cast exception, but if we change this part of Id to int it works. Also calling persist on root persists map elements properly. @Id @Basic(optional=false) //@Enumerated(EnumType.ORDINAL) @Column(name=tsType,updatable=false) //private TSType tsType; private int tsType;
Re: Enum as a Key in a Map
Hi Krzysztof, This is a generic problem in openjpa. If an entity, say EntityA, has an IdClass which contains an Enum type, and EntityB has a one-to-one relationship with EntityA. This problem will surface during retrieval of EntityA when doing the findBy for EntityB. Apparently there is a bug in the Enhancer code. I will open a JIRA for this problem. Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 12:07:31 PM Subject: Re: Enum as a Key in a Map Thank you, I just tried to add Id class to the enum as a dirty hack but it's not doable of course. Good luck! Krzysztof Fay Wang wrote: Hi Krzysztof, Given your description below, I am able to reproduce this problem. I will take a look at it. Thanks! Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 11:38:36 AM Subject: Re: Enum as a Key in a Map Thanks Kevin, Certainly, I have checked your roadmap and the relevant JIRA issue, also test cases you have in the trunk - have not seen @MapKeyEnumerated used with @OneToMany though. In the Id class of the child I kept enum as a field and used ordinal() obviously. I'm debugging this now and can see that _key enum field of the oid passed to pcCopyKeyFieldsToObjectId is null. As mentioned before, value in the DB looks ok. After dissasembling public void pcCopyKeyFieldsToObjectId(FieldSupplier fieldsupplier, Object obj) of that class I can see that TSimplId.tsType = (TSType)((ObjectId)fieldsupplier.fetchObjectField(2 + i)).getId(); for some reason enum is treated as a composite Id and cast to ObjectId fails? Cheers, Krzysztof Kevin Sutter wrote: Hi Krzysztof, The MapKeyEnumerated support was introduced as part of JPA 2.0. It looks like this was committed via OPENJPA-1055. I've pinged Fay (owner of the JIRA) to take a look to see if she has any ideas. If you are interested in what's been done for JPA 2.0 already, you can reference our roadmap [1]. I'm bringing this up in case you try some other JPA 2.0 items that haven't even been touched yet... :-) Thanks, Kevin [1] http://openjpa.apache.org/jpa-20-roadmap.html On Wed, Aug 19, 2009 at 12:30 PM, Krzysztof yaz...@gmail.com wrote: Hello, I'm reviving this as @MapKeyEnumerated has been introduced recently which seemed addressing this issue. Unfortunately, if I use enum as a key where Source is amended with following annotation for the map: @OneToMany(mappedBy = source,cascade={ CascadeType.ALL },fetch = FetchType.LAZY, orphanRemoval = true) @MapKeyEnumerated(EnumType.ORDINAL) @MapKey(name = tsType) objects are committed gracefully and generated data and schema looks ok, but the exception reappears during retrieval: java.lang.ClassCastException: TSType cannot be cast to org.apache.openjpa.util.ObjectId gaia.cu7.omimpl.ClassificationResultsImpl.pcCopyKeyFieldsToObjectId(ClassificationResultsImpl.java) org.apache.openjpa.enhance.PCRegistry.copyKeyFieldsToObjectId(PCRegistry.java:172) org.apache.openjpa.util.ApplicationIds.fromPKValues(ApplicationIds.java:219) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:216) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:147) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:934) org.apache.openjpa.jdbc.sql.AbstractResult.load(AbstractResult.java:280) org.apache.openjpa.jdbc.sql.SelectImpl$SelectResult.load(SelectImpl.java:2349) org.apache.openjpa.jdbc.meta.strats.RelationToManyInverseKeyFieldStrategy.loadElement(RelationToManyInverseKeyFieldStrategy.java:87) org.apache.openjpa.jdbc.meta.strats.StoreCollectionFieldStrategy.load(StoreCollectionFieldStrategy.java:554) org.apache.openjpa.jdbc.meta.FieldMapping.load(FieldMapping.java:919) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:641) org.apache.openjpa.kernel.DelegatingStoreManager.load(DelegatingStoreManager.java:116) org.apache.openjpa.kernel.ROPStoreManager.load(ROPStoreManager.java:78) org.apache.openjpa.kernel.StateManagerImpl.loadFields(StateManagerImpl.java:3035) org.apache.openjpa.kernel.StateManagerImpl.loadField(StateManagerImpl.java:3113) org.apache.openjpa.kernel.StateManagerImpl.beforeAccessField(StateManagerImpl.java:1606) org.apache.openjpa.kernel.StateManagerImpl.accessingField(StateManagerImpl.java:1591) Source.pcGetclassificationResultsMap(SourceImpl.java) 2.0.0 trunk version. Is is possible to use enumeration as a Key in a directly mapped (no join table), bidirectional Map? Anybody with a workaround? Best regards, Krzysztof Krzysztof wrote: Indeed, changing the map to be keyed on a plain type does not solve the problem until the owning 'source' field becomes
Re: Enum as a Key in a Map
hi Krzysztof, I have checked the fix into the trunk (r-806011). Please extract the fix, enhance your entities and run the test case again. Please let me know if you still have problem. Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 1:28:44 PM Subject: Re: Enum as a Key in a Map Thank you Fay, Probably ApplicationIdTool could be updated as well - it actually creates some code for such cases, but not digestible by the compiler. Best regards, Krzysztof Fay Wang wrote: Hi Krzysztof, This is a generic problem in openjpa. If an entity, say EntityA, has an IdClass which contains an Enum type, and EntityB has a one-to-one relationship with EntityA. This problem will surface during retrieval of EntityA when doing the findBy for EntityB. Apparently there is a bug in the Enhancer code. I will open a JIRA for this problem. Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 12:07:31 PM Subject: Re: Enum as a Key in a Map Thank you, I just tried to add Id class to the enum as a dirty hack but it's not doable of course. Good luck! Krzysztof Fay Wang wrote: Hi Krzysztof, Given your description below, I am able to reproduce this problem. I will take a look at it. Thanks! Regards, Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 19, 2009 11:38:36 AM Subject: Re: Enum as a Key in a Map Thanks Kevin, Certainly, I have checked your roadmap and the relevant JIRA issue, also test cases you have in the trunk - have not seen @MapKeyEnumerated used with @OneToMany though. In the Id class of the child I kept enum as a field and used ordinal() obviously. I'm debugging this now and can see that _key enum field of the oid passed to pcCopyKeyFieldsToObjectId is null. As mentioned before, value in the DB looks ok. After dissasembling public void pcCopyKeyFieldsToObjectId(FieldSupplier fieldsupplier, Object obj) of that class I can see that TSimplId.tsType = (TSType)((ObjectId)fieldsupplier.fetchObjectField(2 + i)).getId(); for some reason enum is treated as a composite Id and cast to ObjectId fails? Cheers, Krzysztof Kevin Sutter wrote: Hi Krzysztof, The MapKeyEnumerated support was introduced as part of JPA 2.0. It looks like this was committed via OPENJPA-1055. I've pinged Fay (owner of the JIRA) to take a look to see if she has any ideas. If you are interested in what's been done for JPA 2.0 already, you can reference our roadmap [1]. I'm bringing this up in case you try some other JPA 2.0 items that haven't even been touched yet... :-) Thanks, Kevin [1] http://openjpa.apache.org/jpa-20-roadmap.html On Wed, Aug 19, 2009 at 12:30 PM, Krzysztof yaz...@gmail.com wrote: Hello, I'm reviving this as @MapKeyEnumerated has been introduced recently which seemed addressing this issue. Unfortunately, if I use enum as a key where Source is amended with following annotation for the map: @OneToMany(mappedBy = source,cascade={ CascadeType.ALL },fetch = FetchType.LAZY, orphanRemoval = true) @MapKeyEnumerated(EnumType.ORDINAL) @MapKey(name = tsType) objects are committed gracefully and generated data and schema looks ok, but the exception reappears during retrieval: java.lang.ClassCastException: TSType cannot be cast to org.apache.openjpa.util.ObjectId gaia.cu7.omimpl.ClassificationResultsImpl.pcCopyKeyFieldsToObjectId(ClassificationResultsImpl.java) org.apache.openjpa.enhance.PCRegistry.copyKeyFieldsToObjectId(PCRegistry.java:172) org.apache.openjpa.util.ApplicationIds.fromPKValues(ApplicationIds.java:219) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:216) org.apache.openjpa.jdbc.meta.ClassMapping.getObjectId(ClassMapping.java:147) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:934) org.apache.openjpa.jdbc.sql.AbstractResult.load(AbstractResult.java:280) org.apache.openjpa.jdbc.sql.SelectImpl$SelectResult.load(SelectImpl.java:2349) org.apache.openjpa.jdbc.meta.strats.RelationToManyInverseKeyFieldStrategy.loadElement(RelationToManyInverseKeyFieldStrategy.java:87) org.apache.openjpa.jdbc.meta.strats.StoreCollectionFieldStrategy.load(StoreCollectionFieldStrategy.java:554) org.apache.openjpa.jdbc.meta.FieldMapping.load(FieldMapping.java:919) org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:641) org.apache.openjpa.kernel.DelegatingStoreManager.load(DelegatingStoreManager.java:116) org.apache.openjpa.kernel.ROPStoreManager.load(ROPStoreManager.java:78) org.apache.openjpa.kernel.StateManagerImpl.loadFields(StateManagerImpl.java:3035
Re: Key and Value limitations in a MapKey,Value
Hi, Can you try making AbstractModel an Entity instead of MappedSuperClass, and making this class a concrete class as shown below? // abstract class that has common identity and some additional fields, it is //a Key in a map @Inheritance(strategy = InheritanceType.JOINED) @Entity @IdClass(ModelId.ModelImplId.class) public class AbstractModel { ... } -Fay - Original Message From: Krzysztof yaz...@gmail.com To: users@openjpa.apache.org Sent: Wednesday, August 5, 2009 9:31:53 AM Subject: Key and Value limitations in a MapKey,Value Hello, Seems I am completely knotted in a convoluted class graph without any hint from documentation, spec or forum archive. Could somebody enlighten me if it is possible to: A. Have a Key in a persistent MapKey,Value such as 1. the Key has a composite ID composed of classes which have composite IDs themselves? and 2. They Key is an abstract class that is also used in a Value as a parent in ManyToOne relationship being the part of the Values identity (actual objects - parent and Value being rather different entities) Hope this example clarifies this rather complicated scenario: //abstract class of which children are Values in a map @Entity @IdClass(AbstractTS.TSId.class) //TSId covers SomeOtherClass identity too @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class AbstractTS { @id SomeOtherClass parent; @id int local_id; @OneToMany private MapModelId, DerivedTS derivedMap; // DerivedTS inherits from AbstractTS - seems to impossible to be mapped properly. } // abstract class that has common identity and some additional fields, it is a Key in a map @Inheritance(strategy = InheritanceType.JOINED) @MappedSuperclass @IdClass(ModelId.ModelImplId.class) public abstract class AbstractModel { @id AbstractTS parent; @id int x; @id double y; @Basic @Lob double[] some_common_data; } // Identity domain class, that is in fact stripped down version of an abstractModel, both reuse same ID class, used to retrieve unknown models. @IdClass(ModelId.ModelImplId.class) @Embeddable public class ModelId { @ManyToOne public AbstractTS parentTS; //could be either DerivedTS or RawTS. @Id @Basic public double some_value; @Id public int modelType; @Basic int some_derived_value; } @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) //identity derived from AbstractTS public class RawTS extends AbstractTS { @Basic int some_values; } @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @IdClass(DerivedTS.DerivedTSId.class) // inherits from TSId with additional Identities for parentTS and parentModel public class DerivedTS extends AbstractTS { @ManyToOne //@PrimaryKeyJoinColumns(..) // possibly to provide direct mappings to either RawTS or DerivedTS identity fields @Id private AbstractTS parentTS; @Id @ManyToOne //@PrimaryKeyJoinColumns( {... }) //possibly to provide direct mappings to any model derived from AbstractModel private AbstractModel parentModel = null; } To create any working mapping for MapModelId, DerivedTS seems like an impossible mission, I would appreciate any hints if it is doable at all. I tried various combinations of @ManyToOne combined with @PrimaryKeys, @MapPrimaryKeys, @ElementCollection etc. Persistence.xml lists all the classes, using openjpa 2.0.0 snapshot. The last error I got is during enhancement: [java] Exception in thread main openjpa-2.0.0-SNAPSHOT-r422266:798026 fatal user error org.apache.openjpa.util.MetaDataException: Errors encountered while resolving metadata. See nested exceptions for details. [java] at org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:578) [java] at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:323) [java] at org.apache.openjpa.meta.MetaDataRepository.resolveMeta(MetaDataRepository.java:625) [java] at org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:556) [java] at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:323) [java] at org.apache.openjpa.enhance.PCEnhancer.init(PCEnhancer.java:251) [java] at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4593) [java] at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4540) [java] at org.apache.openjpa.enhance.PCEnhancer$1.run(PCEnhancer.java:4510) [java] at org.apache.openjpa.lib.conf.Configurations.launchRunnable(Configurations.java:726) [java] at org.apache.openjpa.lib.conf.Configurations.runAgainstAllAnchors(Configurations.java:711) [java] at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4505) [java] at org.apache.openjpa.enhance.PCEnhancer.main(PCEnhancer.java:4496) [java] Caused by: openjpa-2.0.0-SNAPSHOT-r422266:798026 fatal user error
Re: SQL generation for OneToMany object graph
- Original Message From: David Minor davemi...@gmail.com To: users@openjpa.apache.org Sent: Monday, June 29, 2009 5:23:25 PM Subject: SQL generation for OneToMany object graph Hi, If I have a deep object graph with a root element that has OneToMany relationships with other elements, and those have OneToMany relationships (and so on), and all the objects are included via a fetch group, how does openjpa decide how to generate the SQL for a statement like: SELECT r FROM RootElement r WHERE r.uid IN (:list) Looking at the SQL logging (this is using mysql BTW), the initial statements use an OR to select among rows in the root element's table, and some of the other initial tables, but then it seems to start issuing individual SELECT statements as it gets deeper into the graph. Is there any way to make it use OR combined with JOIN statements instead? Thanks, Dave -- _ David Minor
Re: SQL generation for OneToMany object graph
Hi, it seems that you are using the Join strategy for your eager fetch mode. Can you try parallel? property name=openjpa.jdbc.EagerFetchMode value=parallel/ Fay - Original Message From: David Minor davemi...@gmail.com To: users@openjpa.apache.org Sent: Monday, June 29, 2009 5:23:25 PM Subject: SQL generation for OneToMany object graph Hi, If I have a deep object graph with a root element that has OneToMany relationships with other elements, and those have OneToMany relationships (and so on), and all the objects are included via a fetch group, how does openjpa decide how to generate the SQL for a statement like: SELECT r FROM RootElement r WHERE r.uid IN (:list) Looking at the SQL logging (this is using mysql BTW), the initial statements use an OR to select among rows in the root element's table, and some of the other initial tables, but then it seems to start issuing individual SELECT statements as it gets deeper into the graph. Is there any way to make it use OR combined with JOIN statements instead? Thanks, Dave -- _ David Minor
Re: SQL generation for OneToMany object graph
Hi David, Do you mind sending me your entity definitions for further investigation? Regards, Fay - Original Message From: David Minor davemi...@gmail.com To: users@openjpa.apache.org Sent: Thursday, July 2, 2009 9:38:47 AM Subject: Re: SQL generation for OneToMany object graph Fay, thanks for your reply! openjpa.jdbc.EagerFetchMode is currently set to parallel. openjpa.jdbc.SubclassFetchMode is set to parallel as well. The description of parallel mode seems to be exactly what I want to happen, but not what seems to be happening. Is there any other setting, or anything in the object graph that would prevent this behavior? -Original Message- From: Fay Wang [mailto:fyw...@yahoo.com] Sent: Thursday, July 02, 2009 9:19 AM To: users@openjpa.apache.org Subject: Re: SQL generation for OneToMany object graph Hi, it seems that you are using the Join strategy for your eager fetch mode. Can you try parallel? property name=openjpa.jdbc.EagerFetchMode value=parallel/ Fay - Original Message From: David Minor davemi...@gmail.com To: users@openjpa.apache.org Sent: Monday, June 29, 2009 5:23:25 PM Subject: SQL generation for OneToMany object graph Hi, If I have a deep object graph with a root element that has OneToMany relationships with other elements, and those have OneToMany relationships (and so on), and all the objects are included via a fetch group, how does openjpa decide how to generate the SQL for a statement like: SELECT r FROM RootElement r WHERE r.uid IN (:list) Looking at the SQL logging (this is using mysql BTW), the initial statements use an OR to select among rows in the root element's table, and some of the other initial tables, but then it seems to start issuing individual SELECT statements as it gets deeper into the graph. Is there any way to make it use OR combined with JOIN statements instead? Thanks, Dave -- _ David Minor -- _ David Minor
Re: Problem with @TableGenerator [OpenJPA 1.2.2]
Hi, I used your annotation and my test case runs fine. Given your pkColumnName = table_name, openjpa internally makes this column name valid for a given database. This code is in ValueTableJDBCSeq: protected Column addPrimaryKeyColumn(Table table) { DBDictionary dict = getConfiguration().getDBDictionaryInstance(); Column pkColumn = table.addColumn(dict.getValidColumnName (getPrimaryKeyColumn(), table)); ... } Note that the return value from dict.getValidColumnName is table_name0. From my jdbc log, the table jdo_keygen is created as: CREATE TABLE jdo_keygen (TABLE_NAME0 VARCHAR(254) NOT NULL, LAST_USED_ID BIGINT, PRIMARY KEY (TABLE_NAME0)) As a result, there is no problem executing SELECT LAST_USED_ID FROM jdo_keygen WHERE TABLE_NAME0 = ? FOR UPDATE I am using openjpa trunk for this exercise. You might want to turn on jdbc log to see how create jdo_keygen is created. Hope this helps. Fay - Original Message From: Michael Simons michael.sim...@optitool.de To: users@openjpa.apache.org Sent: Monday, June 22, 2009 6:48:17 AM Subject: Problem with @TableGenerator [OpenJPA 1.2.2] Hello, Here's my annotation: @TableGenerator(name = pkGenSessionConfig, table = jdo_keygen, pkColumnName = table_name, valueColumnName = last_used_id, pkColumnValue = session_config, allocationSize = 10) @Id @GeneratedValue(strategy=GenerationType.TABLE, generator=pkGenSessionConfig) @Column(name=session_config_id, unique=true, nullable=false) private int id; And here's the according SQL generated by OpenJPA: Unknown column 'TABLE_NAME0' in 'where clause' {prepstmnt 32845046 SELECT LAST_USED_ID FROM jdo_keygen WHERE TABLE_NAME0 = ? FOR UPDATE [params=(String) session_config]} [code=1054, state=42S22] Question: Where does OpenJPA take TABLE_NAME0 from while pkColumnValue=table_name Kind Regards, Michael
Re: Problem with @TableGenerator [OpenJPA 1.2.2]
As a workaround so that you can proceed, could you alter your jdo_keygen table by changing the column table_name to table_name0, meanwhile you might want to open a jira issue for this problem. Regards, Fay - Original Message From: Michael Simons michael.sim...@optitool.de To: users@openjpa.apache.org Sent: Monday, June 22, 2009 9:58:33 AM Subject: Re: Problem with @TableGenerator [OpenJPA 1.2.2] Hi Fay Wang, thanks for your reply. As you probably already guessed beacuse of the name jdo_keygen, we are porting an application that was based on JDO to JPA. So the table already exists and we must not generate it. As the table already exists with a column table_name this name is valid as a column name for these databases (we tested with MS SQL Server and MySQL, both failed for the same reason). Can't I tell JPA to take the pkColumnName as is when accessing the database table? Can we influence what's assumed a valid column name? Is there any other opportunity to come around this problem. I thought about dropping the whole @GeneratedValue thing and doing the key generating on my own. How do you think about that idea? kind regards, Michael Fay Wang schrieb: Hi, I used your annotation and my test case runs fine. Given your pkColumnName = table_name, openjpa internally makes this column name valid for a given database. This code is in ValueTableJDBCSeq: protected Column addPrimaryKeyColumn(Table table) { DBDictionary dict = getConfiguration().getDBDictionaryInstance(); Column pkColumn = table.addColumn(dict.getValidColumnName (getPrimaryKeyColumn(), table)); ... } Note that the return value from dict.getValidColumnName is table_name0. From my jdbc log, the table jdo_keygen is created as: CREATE TABLE jdo_keygen (TABLE_NAME0 VARCHAR(254) NOT NULL, LAST_USED_ID BIGINT, PRIMARY KEY (TABLE_NAME0)) As a result, there is no problem executing SELECT LAST_USED_ID FROM jdo_keygen WHERE TABLE_NAME0 = ? FOR UPDATE I am using openjpa trunk for this exercise. You might want to turn on jdbc log to see how create jdo_keygen is created. Hope this helps. Fay - Original Message From: Michael Simons michael.sim...@optitool.de To: users@openjpa.apache.org Sent: Monday, June 22, 2009 6:48:17 AM Subject: Problem with @TableGenerator [OpenJPA 1.2.2] Hello, Here's my annotation: @TableGenerator(name = pkGenSessionConfig, table = jdo_keygen, pkColumnName = table_name, valueColumnName = last_used_id, pkColumnValue = session_config, allocationSize = 10) @Id @GeneratedValue(strategy=GenerationType.TABLE, generator=pkGenSessionConfig) @Column(name=session_config_id, unique=true, nullable=false) private int id; And here's the according SQL generated by OpenJPA: Unknown column 'TABLE_NAME0' in 'where clause' {prepstmnt 32845046 SELECT LAST_USED_ID FROM jdo_keygen WHERE TABLE_NAME0 = ? FOR UPDATE [params=(String) session_config]} [code=1054, state=42S22] Question: Where does OpenJPA take TABLE_NAME0 from while pkColumnValue=table_name Kind Regards, Michael
Re: Problem with join fetch
The number of queries depends on the fetch strategy. Currently there are two fetch strategy: property name=openjpa.jdbc.EagerFetchMode value=join/ property name=openjpa.jdbc.EagerFetchMode value=parallel/ If you are using join strategy, in the example that A contains oneToMany relation to B, and B contains OneToMany relation to C, openjpa will generate the following sql for JPQL select a from EntityA a: SELECT t0.id, t0.age, t0.name FROM EntityA t0 SELECT t0.id, t0.age, t0.name FROM EntityB t0 WHERE t0.A_ID = ? SELECT t0.id, t0.name FROM EntityC t0 WHERE t0.B_ID = ? SELECT t0.id, t0.name FROM EntityC t0 WHERE t0.B_ID = ? The number of queries will be 1 + (L*M). where L is the number of A instances. M is the number of B instances per A. If you are using parallel strategy, openjpa will generate sql with inner join to retrieve all the data to reduce the number of queries. In the above example, a JPQL select a from EntityA a will only generate three queries: (1) SELECT t0.id, t0.age, t0.name FROM EntityA t0 (2) SELECT t0.id, t1.id, t1.age, t1.name FROM EntityA t0 INNER JOIN EntityB t1 ON t0.id = t1.A_ID ORDER BY t0.id ASC (3) SELECT DISTINCT t1.id, t2.id, t2.name FROM EntityA t0 INNER JOIN EntityB t1 ON t0.id = t1.A_ID INNER JOIN EntityC t2 ON t1.id = t2.B_ID ORDER BY t1.id ASC Hope this helps! Fay --- On Mon, 5/25/09, Michael Simons michael.sim...@optitool.de wrote: From: Michael Simons michael.sim...@optitool.de Subject: Re: Problem with join fetch To: users@openjpa.apache.org Date: Monday, May 25, 2009, 5:01 AM Hello Catalina, If you define ToMany fetch type to EAGER, then a simple select a from A will get all Bs and Cs loaded. unfortunately, using EAGER does not solve the (N+1)-problem. If there are L instances of A each holds M instances of B and each b has N instances of C then there will be L*M*N queries generated to get the instances of C. In the case that we need to solve here, there are about L=100, M=15, N=2 and there's even one more level D with about 2 instances per each c. So there are about 6000 queries, to get information that can be fetched in one single select. Michael
Re: @MappedSuperClass Cause Null Pointer Exception in Class With IdClass
) at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:210) at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:188) at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:165) at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:217) at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:77) at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:321) ... 22 more Caused by: openjpa-2.0.0-M1-SNAPSHOT-r422266:725770 nonfatal general error org.apache.openjpa.persistence.PersistenceException: null at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203) at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:142) at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:196) at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:60) at org.apache.openejb.persistence.JtaEntityManagerRegistry.getEntityManager(JtaEntityManagerRegistry.java:105) at org.apache.openejb.persistence.JtaEntityManager.getEntityManager(JtaEntityManager.java:61) at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:173) at com.kishware.common.persistence.dao.ejb.SearcherImpl.findByField(SearcherImpl.java:159) at com.kishware.core.gl.dao.jpa.GeneralLedgerDaoImpl.getEntry(GeneralLedgerDaoImpl.java:389) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:158) at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:141) at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:67) at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:210) at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:188) at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:165) at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:217) at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:77) at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:321) ... 45 more Caused by: java.lang.NullPointerException at org.apache.openjpa.meta.ClassMetaData.validateAppIdClass(ClassMetaData.java:1883) at org.apache.openjpa.meta.ClassMetaData.validateIdentity(ClassMetaData.java:1840) at org.apache.openjpa.meta.ClassMetaData.validateMeta(ClassMetaData.java:1757) at org.apache.openjpa.meta.ClassMetaData.resolve(ClassMetaData.java:1630) at org.apache.openjpa.meta.MetaDataRepository.processBuffer(MetaDataRepository.java:717) at org.apache.openjpa.meta.MetaDataRepository.resolveMeta(MetaDataRepository.java:616) at org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:541) at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:308) at org.apache.openjpa.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:286) at org.apache.openjpa.jdbc.meta.MappingTool.getMapping(MappingTool.java:676) at org.apache.openjpa.jdbc.meta.MappingTool.buildSchema(MappingTool.java:748) at org.apache.openjpa.jdbc.meta.MappingTool.run(MappingTool.java:646) at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDBCBrokerFactory.java:153) at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.newBrokerImpl(JDBCBrokerFactory.java:119) at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:196) ... 66 more Fay Wang wrote: The NPE is because the SituationDA is inherited from CashBaseEntity and CashBaseEntity does not have Id class. JIRA 873 is open to address this issue. Regards, Fay --- On Sat, 1/24/09, Drifter pioneer...@yahoo.com wrote: From: Drifter pioneer...@yahoo.com Subject: @MappedSuperClass Cause Null Pointer Exception in Class With IdClass To: users@openjpa.apache.org Date: Saturday, January 24, 2009, 4:30 AM Dear All .. i have four fieild that exist in all tables ..i want to use @MapperSuperClass .I test and I found that when there is a extended class that have IdClass PCEnhancer cuase null pointer exception. I use
Re: Database support
Hi Kevin, What about SolidDB? The memory-based relational database? --- On Fri, 5/15/09, Kevin Sutter kwsut...@gmail.com wrote: From: Kevin Sutter kwsut...@gmail.com Subject: Re: Database support To: users@openjpa.apache.org Date: Friday, May 15, 2009, 2:09 PM Okay, so I'm looking at our stated database support [1]. From this chart, I would divide up the databases into the following categories. The Not Currently Covered category is where I would focus my phishing efforts first. Any discussion? Covered Interest by members of OpenJPA Community === o Derby o DB2 o Informix o Oracle o MS SQL Server ??? o Sybase ??? Not Currently Covered Interest by members of OpenJPA Community = o MySQL o PostgreSQL o H2 o HSQLDB (Hypersonic) o Firebird ??? Are these still required? = o Borland Interbase o Borland JDataStore o Empress o Intersystems Cache o MS Access o MS Visual FoxPro o Pointbase Thanks, Kevin [1] http://openjpa.apache.org/builds/latest/docs/manual/manual.html#dbsupport On Thu, May 14, 2009 at 10:01 AM, David Beer david.m.b...@googlemail.comwrote: Hi Kevin Some database vendors usually have some sort of universal contact which might be the best way of going about it. Posting a one of message to support forums might well be an idea that could work. David On Thu, 14 May 2009 08:46:03 -0500 Kevin Sutter kwsut...@gmail.com wrote: Hi David, On Wed, May 13, 2009 at 5:10 PM, David Beer david.m.b...@googlemail.comwrote: Hi Kevin I currently use OpenJPA with the H2 database for my embeded programs, and will be considering MySQL for larger scale programs. I think that the more database vendors or suppliers we can get links with the better for both sides. I am happily using H2 with OpenJPA but there were some features I had to ask about and how to work with OenJPA. So my point is that we need a way of getting committers or users from both sides to help so we need a way of maybe certifying a database version. It sounds like we're on the same page. The tricky part is signing up this help and support from these database vendors and users groups. Maybe I should just post to these vendor's user forums and ask for some support. Just go phishing... :-) Kevin Jut my thoughts. David On Wed, 13 May 2009 16:36:53 -0500 Kevin Sutter kwsut...@gmail.com wrote: Hi, I'm trolling... I'm looking for ideas on how we can better integrate with the various database vendors. Many of us committers have our own favorite databases due to our employers' needs. But, what about the MySQL, or Postgres, or SQL Server, or pick your favorite databases? I know we have had some interest from these database vendors on our users and dev forums, but I'm looking for ways to get these vendors more involved. When they produce a new version of their database, it would be great to announce OpenJPA support. And, if they have new features to take advantage of, that would be even better. Everybody's development and tests teams are limited. I understand that. But, I'm looking for ideas on how we can work together to accomplish this task. I'm going to cross post on both users and dev forums to see if there any lurkers that might have some ideas. Just to provide a real world example... I was just pinged about MS SQL Server 2008 support. Our OpenJPA manual only documents SQL Server 2005 support. I don't have experience with SQL Server. So, it made me think how we could improve this aspect of our OpenJPA database support. Any thoughts? Kevin
Re: Inner Join
Hi Earnie, For your named query: SELECT p FROM Person p ORDER BY p.me DESC, p.lastName, p.firstName, p.middleName, p.lineage.description If you take out order by p.lineage.description, the push-down SQL will become left outer join. Fay --- On Tue, 4/28/09, Earnie Dyke earnied...@yahoo.com wrote: From: Earnie Dyke earnied...@yahoo.com Subject: Inner Join To: users@openjpa.apache.org Date: Tuesday, April 28, 2009, 7:09 AM Greetings all, I am using OpenJPA v1.2.1 with the following class and the SQL that is created uses an INNER JOIN for the join between the PERSON and LINEAGE tables. How can I make that an OUTER JOIN? Earnie! @Entity @EPenEntity(listNamedQueryName = Person.people) @Table(name = PERSON) @NamedQueries({ @NamedQuery(name = Person.people, query = SELECT p FROM Person p ORDER BY p.me DESC, p.lastName, p.firstName, p.middleName, p.lineage.description), @NamedQuery(name = Person.findMe, query = SELECT p FROM Person p WHERE p.me = true) }) public class Person implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = ME, nullable = false) private Boolean me = false; @Column(name = DATEOFBIRTH) @Temporal(TemporalType.DATE) private Date dateOfBirth; @Column(name = GENDER, length = 6) private String gender; @Column(name = FIRSTNAME, length = 50) private String firstName; @Column(name = MIDDLENAME, length = 50) private String middleName; @Column(name = LASTNAME, length = 50) private String lastName; @ManyToOne(fetch = FetchType.EAGER,cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH}) @JoinColumn(name = LINEAGEID) private Lineage lineage; @ManyToOne(fetch = FetchType.EAGER,cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH}) @JoinColumn(name = TITLEID) private Title title; @OneToMany(fetch = FetchType.EAGER,cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH}) @JoinTable(name = PERSONADDRESS, joinColumns = @JoinColumn(name = PERSONID),inversejoincolum...@joincolumn(name=ADDRESSID)) private CollectionPersonAddress addresses = new ArrayListPersonAddress(0); @OneToMany(fetch = FetchType.EAGER,cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH}) @JoinTable(name = PERSONPHONENUMBER, joinColumns = @JoinColumn(name = PERSONID),inversejoincolum...@joincolumn(name=PHONENUMBERID)) private CollectionPersonPhoneNumber phoneNumbers = new ArrayListPersonPhoneNumber(0). ...other stuff not shown -- View this message in context: http://n2.nabble.com/Inner-Join-tp2733679p2733679.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Can't query against a MappedSuperclass
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: NativeQuery resulting in combination of Values
Hi, Here is a simple example: (1) EntityA.java: package queryTest; import javax.persistence.*; @SqlResultSetMapping(name=ResultCMapping, entitie...@entityresult(entityClass=ResultC.class)} ) @NamedNativeQuery( name=nativefindAandB, query=SELECT a.id, a.name, b.value FROM EntityA a, EntityB b WHERE a.id = b.id, resultSetMapping=ResultCMapping ) @Entity public class EntityA { @Id private long id; @OneToOne private EntityB b; String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public EntityB getB() { return b; } public void setB(EntityB b) { this.b = b; } public String getName() { return name; } public void setName(String name) { this.name = name; } } = (2) EntityB.java: package queryTest; import javax.persistence.*; @Entity public class EntityB { @Id long id; String value; @OneToOne EntityA a; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public EntityA getA() { return a; } public void setA(EntityA a) { this.a = a; } } == (3) query: ListResultC list1 = em.createNamedQuery(nativefindAandB).getResultList(); for (ResultC c: list1) { System.err.println(value = + c.getValue()); } Hope this helps. --- On Tue, 4/21/09, it-media.k...@daimler.com it-media.k...@daimler.com wrote: From: it-media.k...@daimler.com it-media.k...@daimler.com Subject: NativeQuery resulting in combination of Values To: users@openjpa.apache.org Date: Tuesday, April 21, 2009, 1:22 AM Hello, I'm currently trying to build a native query for ORACLE that combines several columns of different tables in a complex JOIN/UNION way including some ORACLE specific things that do not allow me to redesign it for JPA-native querys. However, I'm having trouble to understand how to handle this kind of 'virtual' result set. I figured that I have to use an @SqlResultSetMapping() somewhere on the resulting object. My problems arise here, which lead to several questions: If I design a Result-Object, how do I tell JPA that this shall be the represence of a single row of the ResultSet? I can't use @Entity nor @Table somehow, cause I always get error messages telling me that there is no such table (which is correct) What is the correct way of using SqlResultSetMapping for a simple result with 12 columns that shall be mapped to 12 simple values in the resulting 'Entity'? Does anybody have a good (maybe commented) example of such a ResultSetMapping? Where exactly do you put the SqlResultSetMapping? Do you annotate the class that shall hold a row? Do I have to register that class in persistence.xml? My current solution always stucks with error messages like: Invalid Index (Oracle Error) the Message: Result path {2} in result type {1} of mapping {0} attempts to map a field that does not have exactly 1 column. (I figured it actually can't find a single column) Table {0} given for {1} does not exist. (Happens when I try to use @Entity on the resulting type) Any help on these questions is gladly appreciated. Thanks, Heiko If you are not the intended addressee, please inform us immediately that you have received this e-mail in error, and delete it. We thank you for your cooperation.
Re: Can't query against a MappedSuperclass
Ya, this apparently is an inconsistency... --- 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, 9:53 AM 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: Optimistic locking errors were detected when flushing to the data store
Can you turn on the trace : property name=openjpa.Log value=File=c:/trace.log, DefaultLevel=TRACE / and attach the trace file for further investigation? -Fay --- On Thu, 4/16/09, Georgi Naplatanov go...@oles.biz wrote: From: Georgi Naplatanov go...@oles.biz Subject: Optimistic locking errors were detected when flushing to the data store To: users@openjpa.apache.org Date: Thursday, April 16, 2009, 12:36 PM Hello list. I upgraded OpenJPA from 1.2.0 to 1.2.1 and have the following exception. My environment is MySql 5.0.51 (MyISAM storage manager) and JRE Sun 1.6.0_13-b03. The application works without this exception with OpenJPA 1.2.0. Optimistic locking errors were detected when flushing to the data store. The following objects may have been concurrently modified in another transaction: [org.opencms.db.jpa.persistence.CmsDAOOfflineResources-3e51ea18-2abb-11de-93fb-4b60ca370499] openjpa-1.2.1-r752877:753278 fatal store error org.apache.openjpa.persistence.RollbackException: Optimistic locking errors were detected when flushing to the data store. The following objects may have been concurrently modified in another transaction: [org.opencms.db.jpa.persistence.CmsDAOOfflineResources-3e51ea18-2abb-11de-93fb-4b60ca370499] at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:523) at org.opencms.db.jpa.CmsDbContext.commitAndClose(CmsDbContext.java:129) at org.opencms.db.jpa.CmsDbContext.clear(CmsDbContext.java:73) at org.opencms.db.CmsSecurityManager.publishProject(CmsSecurityManager.java:3107) at org.opencms.publish.CmsPublishManager.publishProject(CmsPublishManager.java:501) at org.opencms.publish.CmsPublishManager.publishProject(CmsPublishManager.java:525) at org.opencms.publish.CmsPublishManager.publishResource(CmsPublishManager.java:563) at org.opencms.file.TestPublishIssues.testPublishFolderWithDeletedFileFromOtherProject(TestPublishIssues.java:335) at junit.extensions.TestDecorator.basicRun(TestDecorator.java:22) at junit.extensions.TestSetup$1.protect(TestSetup.java:19) at junit.extensions.TestSetup.run(TestSetup.java:23) Caused by: openjpa-1.2.1-r752877:753278 nonfatal store error org.apache.openjpa.persistence.OptimisticLockException: Optimistic locking errors were detected when flushing to the data store. The following objects may have been concurrently modified in another transaction: [org.opencms.db.jpa.persistence.CmsDAOOfflineResources-3e51ea18-2abb-11de-93fb-4b60ca370499] at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2160) at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2010) at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:1908) at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:1826) at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81) at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1350) at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:877) at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:512) Caused by: openjpa-1.2.1-r752877:753278 nonfatal store error org.apache.openjpa.persistence.OptimisticLockException: An optimistic lock violation was detected when flushing object instance org.opencms.db.jpa.persistence.CmsDAOOfflineResources-3e51ea18-2abb-11de-93fb-4b60ca370499 to the data store. This indicates that the object was concurrently modified in another transaction. FailedObject: org.opencms.db.jpa.persistence.CmsDAOOfflineResources-3e51ea18-2abb-11de-93fb-4b60ca370499 at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flushAndUpdate(PreparedStatementManagerImpl.java:124) at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushAndUpdate(BatchingPreparedStatementManagerImpl.java:82) at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flushInternal(PreparedStatementManagerImpl.java:89) at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flush(PreparedStatementManagerImpl.java:72) at org.apache.openjpa.jdbc.kernel.ConstraintUpdateManager.flush(ConstraintUpdateManager.java:543) at org.apache.openjpa.jdbc.kernel.ConstraintUpdateManager.flush(ConstraintUpdateManager.java:106) at org.apache.openjpa.jdbc.kernel.BatchingConstraintUpdateManager.flush(BatchingConstraintUpdateManager.java:59) at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:89) at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:72) at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:717) at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:130) at
Re: Identity class and parent/children entity relationship
Hi Paul, JIRA-1004 is for derived identity with IdClass. It appears that you did not use @IdClass for identity. In this case, JIRA-1004 does not apply. Fay - Original Message From: Paul Copeland t...@jotobjects.com To: users@openjpa.apache.org Sent: Wednesday, April 8, 2009 10:44:23 PM Subject: Re: Identity class and parent/children entity relationship Hi Fay - Found my error here - my case now works on 1.2.1. I had a mapping error that caused the reentrant flush exception -- this is probably not the problem fixed by JIRA-1004. This is the story - I have a class with a OneToMany relationship to itself (parent has a collection of children of the same type). My mistake was to mark the optional attribute false. Obviously somebody is the granddaddy with no parent or you have a pathological cycle. So this works now - @Table (name=product_category) public class ProductCategory implements java.io.Serializable { @GeneratedValue(strategy=GenerationType.IDENTITY) @Id private long id; @OrderBy @OneToMany(mappedBy=parentCategory, fetch=FetchType.LAZY, cascade={CascadeType.PERSIST,CascadeType.REMOVE}) private ListProductCategory subCategories; @ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.PERSIST) private ProductCategory parentCategory; } On 4/7/2009 2:26 PM, Paul Copeland wrote: I also have a hard requirement to work with 1.x.x OpenJPA (JPA 1.0) for a production delivery same as Nemanja. So I am willing to jump through hoops for a work around even it means changing the identity type or doing lots of flushes or something else like that. Just wondering what my options are. I already tried doing flushes. Maybe I need to do a refresh too? - Paul On 4/7/2009 1:51 PM, Fay Wang wrote: The fix is in JIRA-1004. I only checked in the fix to trunk, not 1.2.x, though. -Fay - Original Message From: Paul Copeland t...@jotobjects.com To: users@openjpa.apache.org Sent: Tuesday, April 7, 2009 12:34:05 PM Subject: Re: Identity class and parent/children entity relationship Is there a workaround for 1.2.1? I'm also hitting the reentrant flush exception with GenerationType.IDENTITY On 3/30/2009 10:26 AM, Nemanja Joksovic wrote: Thanks Fay, I tried it before and it's working fine. But in production environment I need to using stable OpenJPA 1.2.x version (JPA 1.0 specification). Regards, Nemanja J. The workaround is to use MappedById annotation (JPA 2.0 spec) in Openjpa trunk: @Entity public class Child implements Serializable { @EmbeddedId @Column(name = id, unique = false, nullable = false) private ChildId childId; @MappedById(parent) @ManyToOne @JoinColumn(name = parent_id, referencedColumnName = id) private Parent parent; ... } @Embeddable public class ChildId { public long id; public long parent; ...} @Entity public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = id, unique = true, insertable = false, updatable = false, nullable = false) private long id; @OneToMany(cascade = CascadeType.ALL, mappedBy = parent) private ListChild children = new ArrayListChild(); private String name; ...} For more detail, please see org.apache.openjpa.persistence.enhance.identity.TestMappedById.testMappedById5 -Fay --- On Mon, 3/30/09, Nemanja Joksovic joksov...@gmail.com wrote: From: Nemanja Joksovic joksov...@gmail.com Subject: Re: Identity class and parent/children entity relationship To: users@openjpa.apache.org Date: Monday, March 30, 2009, 9:56 AM Thank you very much. Nemanja J. The second problem is a known problem. I will open a JIRA for it. --- On Sun, 3/29/09, Nemanja Joksovic joksov...@gmail.com wrote: From: Nemanja Joksovic joksov...@gmail.com Subject: Identity class and parent/children entity relationship To: users@openjpa.apache.org Date: Sunday, March 29, 2009, 5:33 AM Hi all, I've been experiencing few problems with Identity class and Parent/Children entity relationship. I tried with both OpenJPA 1.2.1 and 2.0.0-SNAPSHOT. I have a very simple test case which can briefly explain problems: @Entity public class Parent implements Serializable { private long id; private ListChild children = new LinkedListChild(); @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = id, unique = true, insertable = false, updatable = false, nullable = false) public long getId() { return id; } public void setId(long id) { this.id = id; } ... @OneToMany(cascade = CascadeType.ALL, mappedBy = parent) public
Re: Identity class and parent/children entity relationship
The fix is in JIRA-1004. I only checked in the fix to trunk, not 1.2.x, though. -Fay - Original Message From: Paul Copeland t...@jotobjects.com To: users@openjpa.apache.org Sent: Tuesday, April 7, 2009 12:34:05 PM Subject: Re: Identity class and parent/children entity relationship Is there a workaround for 1.2.1? I'm also hitting the reentrant flush exception with GenerationType.IDENTITY On 3/30/2009 10:26 AM, Nemanja Joksovic wrote: Thanks Fay, I tried it before and it's working fine. But in production environment I need to using stable OpenJPA 1.2.x version (JPA 1.0 specification). Regards, Nemanja J. The workaround is to use MappedById annotation (JPA 2.0 spec) in Openjpa trunk: @Entity public class Child implements Serializable { @EmbeddedId @Column(name = id, unique = false, nullable = false) private ChildId childId; @MappedById(parent) @ManyToOne @JoinColumn(name = parent_id, referencedColumnName = id) private Parent parent; ... } @Embeddable public class ChildId { public long id; public long parent; ...} @Entity public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = id, unique = true, insertable = false, updatable = false, nullable = false) private long id; @OneToMany(cascade = CascadeType.ALL, mappedBy = parent) private ListChild children = new ArrayListChild(); private String name; ...} For more detail, please see org.apache.openjpa.persistence.enhance.identity.TestMappedById.testMappedById5 -Fay --- On Mon, 3/30/09, Nemanja Joksovic joksov...@gmail.com wrote: From: Nemanja Joksovic joksov...@gmail.com Subject: Re: Identity class and parent/children entity relationship To: users@openjpa.apache.org Date: Monday, March 30, 2009, 9:56 AM Thank you very much. Nemanja J. The second problem is a known problem. I will open a JIRA for it. --- On Sun, 3/29/09, Nemanja Joksovic joksov...@gmail.com wrote: From: Nemanja Joksovic joksov...@gmail.com Subject: Identity class and parent/children entity relationship To: users@openjpa.apache.org Date: Sunday, March 29, 2009, 5:33 AM Hi all, I've been experiencing few problems with Identity class and Parent/Children entity relationship. I tried with both OpenJPA 1.2.1 and 2.0.0-SNAPSHOT. I have a very simple test case which can briefly explain problems: @Entity public class Parent implements Serializable { private long id; private ListChild children = new LinkedListChild(); @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = id, unique = true, insertable = false, updatable = false, nullable = false) public long getId() { return id; } public void setId(long id) { this.id = id; } ... @OneToMany(cascade = CascadeType.ALL, mappedBy = parent) public ListChild getChildren() { return children; } public void addChild(Child child) { if (child == null) { throw new IllegalArgumentException(Cannot add a null Child); } this.getChildren().add(child); } public void setChildren(ListChild children) { this.children = children; } } @Entity @IdClass(ChildId.class) public class Child implements Serializable { private long id; ... private Parent parent; @Id @Column(name = id, unique = false, nullable = false) public long getId() { return id; } public void setId(long id) { this.id = id; } ... @Id @ManyToOne @JoinColumn(name = parent_id, referencedColumnName = id) public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } } ChidId is generated with the Application Identity Tool: public class ChildId implements Serializable { ... public long id; public long parent; ... } 1) Merge operation fail in any case with following exception: java.lang.NullPointerException at net.company.persistence.Child.pcCopyKeyFieldsFromObjectId(Child.java) at net.company.persistence.Child.pcNewInstance(Child.java) at org.apache.openjpa.kernel.AttachStrategy.persist(AttachStrategy.java:93) at org.apache.openjpa.kernel.VersionAttachStrategy.attach(VersionAttachStrategy.java:100) at org.apache.openjpa.kernel.AttachManager.attach(AttachManager.java:241) at org.apache.openjpa.kernel.AttachStrategy.attachCollection(AttachStrategy.java:333) at org.apache.openjpa.kernel.AttachStrategy.replaceList(AttachStrategy.java:359)
Re: Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping.
It appears that openjpa currently does not support MapKey annotation applied to a relation field. This, however, is not explicitly stated in the user guide or JPA 2.0 spec. Please open a JIRA for it. Thanks! - Original Message From: Michael Vorburger mvorbur...@odyssey-group.com To: users@openjpa.apache.org Sent: Thursday, April 2, 2009 8:00:28 AM Subject: Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping. Hello! Would anybody be able to enlighten us on how to Use an inverse key or join table mapping. with a @PersistentMap... I'm encoutering the Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping. error message. Full test case reproducing this is attached... you'll find three Entities, a Language, a Translation (with a field of type Language), and a Something which has a MapLanguage, Translation ... sounds trivial? ;-) -- That 'entity_dict_id' you'll find on the Translation is a kind of discriminator (but not for subclassing, I need to use it to classify the map association - imagine that in real world there is SomethingElse and many other Entities which are also translated, all stored in one and the same Translation table.) I'm sure this is possible, I gathered standard JPA 1.0's @OneToMany with a @MapKey can not do this, but with a @PersistentMap this should work... only how?? Any help appreciated... Thanks a lot, Michael • 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: Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping.
Hi Mike, Regarding #2, you can take a look at an Openjpa test case: org.apache.openjpa.persistence.jdbc.meta.TestMappedByKeyMaps This test case tests InverseKeyMapMapping and JoinTableMapMapping. When MapKey annotation is applied, the map field strategy should be RelationMapTableStrategy as the map key is a field of the entity which is the map value. However, since the map key is a relation, openjpa wrongly (I believe) set the strategy as RelationRelationMapTableFieldStrategy. This strategy is used when the map key is an independent entity. An exception is therefore thrown out when a MapKey annotation is detected by this strategy. -Fay - Original Message From: Michael Vorburger mvorbur...@odyssey-group.com To: users@openjpa.apache.org; users@openjpa.apache.org Sent: Thursday, April 2, 2009 3:06:01 PM Subject: RE: Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping. I can open a JIRA, BUT... a few points: 1. Pinaki, you responded to a very similar question for what appears to be a very similiar domain model (a Map with some Translation (relation) field as key) that OpenJPA can map this domain model using @PersistenceMap on http://n2.nabble.com/Map%3CClassA,ClassB%3E-problem-td534546.html ... any advise on how? The link you had provided in that post 404s (and what I think you probably referred to in the doc doesn't actually have such an example) 2. Fay, I've actually tried this on OpenJPA 1.2.0... what does the error Use an inverse key or join table mapping. actually mean, how would one use an inverse key (to what?). 3. Reg. JPA 2.0, the spec actually says If the map key type is an entity, the MapKeyJoinColumn and MapKeyJoinColumns annotations are used to specify the column mappings for the map key. ... would anybody be able to try my example as a test on the OpenJPA for JPA 2.0 version? -Original Message- From: Fay Wang [mailto:fyw...@yahoo.com] Sent: Thu 4/2/2009 10:05 PM To: users@openjpa.apache.org Subject: Re: Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping. It appears that openjpa currently does not support MapKey annotation applied to a relation field. This, however, is not explicitly stated in the user guide or JPA 2.0 spec. Please open a JIRA for it. Thanks! - Original Message From: Michael Vorburger mvorbur...@odyssey-group.com To: users@openjpa.apache.org Sent: Thursday, April 2, 2009 8:00:28 AM Subject: Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping. Hello! Would anybody be able to enlighten us on how to Use an inverse key or join table mapping. with a @PersistentMap... I'm encoutering the Map field ... is attempting to use a map table, but its key is mapped by another field. Use an inverse key or join table mapping. error message. Full test case reproducing this is attached... you'll find three Entities, a Language, a Translation (with a field of type Language), and a Something which has a MapLanguage, Translation ... sounds trivial? ;-) -- That 'entity_dict_id' you'll find on the Translation is a kind of discriminator (but not for subclassing, I need to use it to classify the map association - imagine that in real world there is SomethingElse and many other Entities which are also translated, all stored in one and the same Translation table.) I'm sure this is possible, I gathered standard JPA 1.0's @OneToMany with a @MapKey can not do this, but with a @PersistentMap this should work... only how?? Any help appreciated... Thanks a lot, Michael . 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. • 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
Re: usage of embeddable
You can use @AttributeOverrides to map the fields in the embeddable to the same columns. -Fay --- On Tue, 3/24/09, Adam Hardy adam@cyberspaceroad.com wrote: From: Adam Hardy adam@cyberspaceroad.com Subject: usage of embeddable To: users@openjpa.apache.org Date: Tuesday, March 24, 2009, 3:03 AM I have a requirement to display some price data using different formats according to its origin, i.e. decimal places vary, or are shown as fractions e.g. 129 21/32 My idea is to use 'embeddable' to persist a field of type MyBigDecimalWrapper which knows how to display itself, i.e. it has a BigDecimal and an enum specifying display type. However I then realised I would need to have an extra column for every price column. This seems like overkill, considering that some persistent entities might have five price fields and the display type is the same for each. There is no way around this, is there, because I can't map a column more than once?
Re: IndexOutOfBoundsException in OpenJPA 1.2.1 on Oracle
I could not reproduce your problem in OpenJPA 1.2.x. What revision are you using? From the stack trace, you might want to set property name=openjpa.jdbc.QuerySQLCache value=false / to see if it works. -Fay --- On Tue, 3/24/09, Richard Rak richard@gmail.com wrote: From: Richard Rak richard@gmail.com Subject: IndexOutOfBoundsException in OpenJPA 1.2.1 on Oracle To: users@openjpa.apache.org Date: Tuesday, March 24, 2009, 9:52 AM Hello all, I have an application that I have upgraded from OpenJPA 1.1 (I could not use 1.2.0, as I was hitting an Oracle dictionary bug) to 1.2.1, and now I am getting an IndexOutOfBoundsException while executing the following code: s = (com.onehosp.entity.common.Staff) em.createQuery(SELECT s + FROM Staff s + WHERE s.username = :username ) .setParameter(username, username) .getSingleResult(); Here is the stack trace: Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.RangeCheck(ArrayList.java:547) at java.util.ArrayList.get(ArrayList.java:322) at org.apache.openjpa.jdbc.sql.SQLBuffer.setParameters(SQLBuffer.java:615) at org.apache.openjpa.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:515) at org.apache.openjpa.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:471) at org.apache.openjpa.jdbc.sql.SelectImpl.prepareStatement(SelectImpl.java:463) at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:379) at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:325) at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.getInitializeStateResult(JDBCStoreManager.java:503) at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.initializeState(JDBCStoreManager.java:322) at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.initialize(JDBCStoreManager.java:278) at org.apache.openjpa.kernel.DelegatingStoreManager.initialize(DelegatingStoreManager.java:111) at org.apache.openjpa.datacache.DataCacheStoreManager.initialize(DataCacheStoreManager.java:352) at org.apache.openjpa.kernel.DelegatingStoreManager.initialize(DelegatingStoreManager.java:111) at org.apache.openjpa.kernel.ROPStoreManager.initialize(ROPStoreManager.java:57) at org.apache.openjpa.kernel.BrokerImpl.initialize(BrokerImpl.java:894) at org.apache.openjpa.kernel.BrokerImpl.find(BrokerImpl.java:852) ... 94 more Here is the staff entity class: @DiscriminatorValue(S) @Entity @Table(name = STAFF) public class Staff extends Customer { private static final long serialVersionUID = 1L; @Column(name = USERNAME, length = 65, nullable = false, unique = true) private String username; ... } And here is the Customer entity: @DiscriminatorColumn(name=CUST_TYPE,discriminatorType=DiscriminatorType.STRING,length=1) @Entity @Inheritance(strategy=InheritanceType.JOINED) @Table(name = CUSTOMER) public class Customer implements Serializable { ... } persistence.xml: ?xml version=1.0 encoding=UTF-8? persistence version=1.0 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; persistence-unit name=onePU transaction-type=RESOURCE_LOCAL providerorg.apache.openjpa.persistence.PersistenceProviderImpl/provider non-jta-data-sourcejdbc/ONEunmanaged/non-jta-data-source exclude-unlisted-classesfalse/exclude-unlisted-classes properties property name=openjpa.ConnectionRetainMode value=always/ property name=openjpa.DataCache value=true(CacheSize=5000)/ property name=openjpa.DynamicDataStructs value=true/ property name=openjpa.QueryCache value=true(CacheSize=1000)/ property name=openjpa.RemoteCommitProvider value=sjvm/ property name=openjpa.RuntimeUnenhancedClasses value=unsupported/ /properties /persistence-unit /persistence And here is the oracle dictionary: INFO - Using dictionary class org.apache.openjpa.jdbc.sql.OracleDictionary (Oracle Oracle Database 11g Release 11.1.0.0.0 - Production ,Oracle JDBC driver 11.1.0.6.0-Production+). If you require anymore information, I'll be glad to provide it. Regards, Richard Rak richard@gmail.com
Re: How do I persist timestamp in UTC timezone?
Hi Fazi, I found that by putting TimeZone.setDefault(TimeZone.getTimeZone(Etc/UTC)); to make your java app in UTC time zone (see below in testDate), openjpa will store the dates in UTC in the database. public void testDate(){ TimeZone.setDefault(TimeZone.getTimeZone(Etc/UTC)); DateTest dt = new DateTest(); dt.setId(id); dt.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(UTC))); dt.setStartTime(new Date()); -Fay --- On Tue, 3/17/09, fazi faisal.ans...@gmail.com wrote: From: fazi faisal.ans...@gmail.com Subject: How do I persist timestamp in UTC timezone? To: users@openjpa.apache.org Date: Tuesday, March 17, 2009, 9:56 AM Hi I need to persist all timestamps in UTC timezone. I found this documentation which talks about using Calendar by setting the timezone value to the desired timezone (http://openjpa.apache.org/builds/1.1.0/apache-openjpa-1.1.0/docs/manual/ref_guide_pc_scos.html#ref_guide_pc_calendar_timezone), plus this JIRA (https://issues.apache.org/jira/browse/OPENJPA-322) that gives me some idea on how I can initialize Calendar to insert/update time in UTC but nothing has worked so far. The timestamps are always entered and read in DB local timezone (PDT). I noticed that the Calendar timezone of the retrieved object is set correctly to UTC, however, the time is still in local timezone (PDT). I also noticed that the retrieved object has JPA implementation of the Calendar object: org.apache.openjpa.util.java$util$GregorianCalendar$proxy. We are using openJPA version 1.1.0. I am copying my artifacts below. The test class has two timestamp fields, one is for UTC timezone and the other one is for local timezone to show that both values are same. Please let me know if any other information can help understand this problem better. Any help on this matter will be greatly appreciated. - TestDate table: CREATE TABLE DATETEST ( ID VARCHAR(255) NOT NULL, CREATEDTIME TIMESTAMP, STARTTIME TIMESTAMP) -- -- JPA class: -- package com.my.package.entity; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import javax.persistence.*; @Entity @Table(name=DATETEST) public class DateTest implements Serializable { @Id @Column(name=ID) private String id; @Temporal(TemporalType.TIMESTAMP) @Column(name=CREATEDTIME) private Calendar createdTime = Calendar.getInstance(TimeZone.getTimeZone(UTC)); @Temporal(TemporalType.TIMESTAMP) @Column(name=STARTTIME) private Date startTime; public Calendar getCreatedTime() { return createdTime; } public void setCreatedTime(Calendar createdTime) { this.createdTime = createdTime; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } } -- -- JUnit test: -- @Test public void testDate() { DateTest dt = new DateTest(); dt.setId(id); dt.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(UTC))); dt.setStartTime(new Date()); try { //persist } catch (Exception e) { fail(e.getMessage()); } // Check result DateTest returned = null; try { returned = //find by id; Calendar createdTimeC = returned.getCreatedTime(); System.out.println(createdTime type: + createdTimeC.getClass().getName()); System.out.println(createdTime timezone: + createdTimeC.getTimeZone()); System.out.println(Created time: + createdTimeC.getTime()); System.out.println(Start time : + returned.getStartTime()); System.out.println(Created time (millisecs): + createdTimeC.getTimeInMillis()); System.out.println(Start time (millisecs) : + returned.getStartTime().getTime()); } catch (Exception e) { fail(e.getMessage()); } } -- The output is: createdTime type: org.apache.openjpa.util.java$util$GregorianCalendar$proxy createdTime
Re: How do I persist timestamp in UTC timezone?
To my knowledge, as far as DB2 is concerned, DB2 v9 and below does not have timestamp with time zone data type. The value stored in the DB2 timestamp column is without time zone information. It is up to the application to determine the time zone. For example, in my db2 table, I have the following value 2009-03-17-22.05.37.569000 stored in my timestamp column. If I set the default time zone to UTC in my application, I get the value back as: Created time: Tue Mar 17 22:05:37 UTC 2009 If I did not set the default time zone to UTC, I get this value: Created time: Tue Mar 17 22:05:37 PDT 2009 A new data type Timestamp with time zone may be introduced in the next DB2 release, but currently there is no way to store the time zone information in the timestamp column. DB2 experts, please correct me if I am wrong. Having said that, with this statement, dt.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(Etc/UTC))); when application sets default time zone to UTC, the timestamp value in the database becomes 2009-03-17-23.26.53.32. Without setting the default time zone, the timestamp value in the database is 2009-03-17-16.23.27.494000. Let me try a simple POJO test case to see if this is an openjpa problem or not. --- On Tue, 3/17/09, Paul Copeland t...@jotobjects.com wrote: From: Paul Copeland t...@jotobjects.com Subject: Re: How do I persist timestamp in UTC timezone? To: users@openjpa.apache.org Date: Tuesday, March 17, 2009, 3:04 PM Of course java.util.Date is already measured in milliseconds UTC without regard to TimeZone. So it may seem that you are converting your Date objects to a different timezone, but that's not the case. This is why you can use Calendar.compareTo() with objects in different TimeZones. By definition - new Date() is the same thing as new Date(System.currentTimeMillis()) no matter what the default TimeZone! The link cited by Fazi implies that you have to store the TimeZone along with the date if you want to load the date (milliseconds) back into a Calendar object representing that TimeZone. If you change the default timezone to UTC (or Moscow, etc.) then all the other Calendar objects that are meant to represent the default Locale will be wrong! - Paul On 3/17/2009 2:15 PM, Fay Wang wrote: Hi Fazi, I found that by putting TimeZone.setDefault(TimeZone.getTimeZone(Etc/UTC)); to make your java app in UTC time zone (see below in testDate), openjpa will store the dates in UTC in the database. public void testDate(){ TimeZone.setDefault(TimeZone.getTimeZone(Etc/UTC)); DateTest dt = new DateTest(); dt.setId(id); dt.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(UTC))); dt.setStartTime(new Date()); -Fay --- On Tue, 3/17/09, fazi faisal.ans...@gmail.com wrote: From: fazi faisal.ans...@gmail.com Subject: How do I persist timestamp in UTC timezone? To: users@openjpa.apache.org Date: Tuesday, March 17, 2009, 9:56 AM Hi I need to persist all timestamps in UTC timezone. I found this documentation which talks about using Calendar by setting the timezone value to the desired timezone (http://openjpa.apache.org/builds/1.1.0/apache-openjpa-1.1.0/docs/manual/ref_guide_pc_scos.html#ref_guide_pc_calendar_timezone), plus this JIRA (https://issues.apache.org/jira/browse/OPENJPA-322) that gives me some idea on how I can initialize Calendar to insert/update time in UTC but nothing has worked so far. The timestamps are always entered and read in DB local timezone (PDT). I noticed that the Calendar timezone of the retrieved object is set correctly to UTC, however, the time is still in local timezone (PDT). I also noticed that the retrieved object has JPA implementation of the Calendar object: org.apache.openjpa.util.java$util$GregorianCalendar$proxy. We are using openJPA version 1.1.0. I am copying my artifacts below. The test class has two timestamp fields, one is for UTC timezone and the other one is for local timezone to show that both values are same. Please let me know if any other information can help understand this problem better. Any help on this matter will be greatly appreciated. - TestDate table: CREATE TABLE DATETEST ( ID VARCHAR(255) NOT NULL, CREATEDTIME TIMESTAMP, STARTTIME TIMESTAMP) -- -- JPA class: -- package com.my.package.entity; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import
Re: How do I persist timestamp in UTC timezone?
Hi Adam, Thank you for the clarification. That makes sense. I also observe that the milliseconds value from the java Data/Calendar object is the same regardless of the timezone setting. So we can not actually persist timestamp in UTC timezone in the database with timestamp column, right? (because database timestamp column is timezone indepenent, and also the java timestamp value is already normalized with UTC based on the O/S time zone setting). --- On Tue, 3/17/09, Adam Hardy adam@cyberspaceroad.com wrote: From: Adam Hardy adam@cyberspaceroad.com Subject: Re: How do I persist timestamp in UTC timezone? To: users@openjpa.apache.org Date: Tuesday, March 17, 2009, 5:15 PM Hello Fay, no reason to worry, it is logical that the time saved to the database depends on the default time zone in Java. If you don't set the default time zone, it uses the time in your operating system. I did say that the database field TIMESTAMP default is without time zone - you can specify that it does save the timezone, but that is an optional extra and database vendor specific (I think). The issue here is that Java times and dates are time-zone-independent, because they are held as milliseconds past 1970-01-01 GMT/UTC As Paul said, your database stores time-zone-dependent values (i.e. times without a timezone) and the time zone that they are dependent on is the time zone of your operating system, because JDBC uses that to work out what the millisecond past 1970 value is. So if you change your OS timezone, you change all the timestamps in your database - as far as Java is concerned. I figure that this not optimal, since you have to be careful if you move a database from a host in one timezone to a host in another timezone, but how often does that happen? Fay Wang on 17/03/09 23:41, wrote: To my knowledge, as far as DB2 is concerned, DB2 v9 and below does not have timestamp with time zone data type. The value stored in the DB2 timestamp column is without time zone information. It is up to the application to determine the time zone. For example, in my db2 table, I have the following value 2009-03-17-22.05.37.569000 stored in my timestamp column. If I set the default time zone to UTC in my application, I get the value back as: Created time: Tue Mar 17 22:05:37 UTC 2009 If I did not set the default time zone to UTC, I get this value: Created time: Tue Mar 17 22:05:37 PDT 2009 A new data type Timestamp with time zone may be introduced in the next DB2 release, but currently there is no way to store the time zone information in the timestamp column. DB2 experts, please correct me if I am wrong. Having said that, with this statement, dt.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(Etc/UTC))); when application sets default time zone to UTC, the timestamp value in the database becomes 2009-03-17-23.26.53.32. Without setting the default time zone, the timestamp value in the database is 2009-03-17-16.23.27.494000. Let me try a simple POJO test case to see if this is an openjpa problem or not. --- On Tue, 3/17/09, Paul Copeland t...@jotobjects.com wrote: From: Paul Copeland t...@jotobjects.com Subject: Re: How do I persist timestamp in UTC timezone? To: users@openjpa.apache.org Date: Tuesday, March 17, 2009, 3:04 PM Of course java.util.Date is already measured in milliseconds UTC without regard to TimeZone. So it may seem that you are converting your Date objects to a different timezone, but that's not the case. This is why you can use Calendar.compareTo() with objects in different TimeZones. By definition - new Date() is the same thing as new Date(System.currentTimeMillis()) no matter what the default TimeZone! The link cited by Fazi implies that you have to store the TimeZone along with the date if you want to load the date (milliseconds) back into a Calendar object representing that TimeZone. If you change the default timezone to UTC (or Moscow, etc.) then all the other Calendar objects that are meant to represent the default Locale will be wrong! - Paul On 3/17/2009 2:15 PM, Fay Wang wrote: Hi Fazi, I found that by putting TimeZone.setDefault(TimeZone.getTimeZone(Etc/UTC)); to make your java app in UTC time zone (see below in testDate), openjpa will store the dates in UTC in the database. public void testDate(){ TimeZone.setDefault(TimeZone.getTimeZone(Etc/UTC)); DateTest dt = new DateTest(); dt.setId(id); dt.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(UTC))); dt.setStartTime(new Date()); -Fay --- On Tue, 3/17/09, fazi faisal.ans...@gmail.com wrote: From: fazi faisal.ans...@gmail.com Subject: How do I persist timestamp in UTC timezone
Re: ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve
Hmmm. I could not reproduce the error using your domain model in 1.2.0 and trunk. Attached is the test case. Could you run it to see it passes? Regards, Fay --- On Tue, 3/3/09, Michael Vorburger mvorbur...@odyssey-group.com wrote: From: Michael Vorburger mvorbur...@odyssey-group.com Subject: ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve To: users@openjpa.apache.org Date: Tuesday, March 3, 2009, 11:57 AM Hello, I'm getting a ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve(A pplicationIds.java:602), full stack trace below. This occurs when I try to use application ID Identity Hierarchies as per http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/ jpa_overview_pc_identity.html#jpa_overview_pc_identity_hierarchy, may be because I was trying to use them together with Entities as Identity Fields as per http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/ ref_guide_pc_oid.html#ref_guide_pc_oid_entitypk ... Both of this is not JPA 1.0 spec, is it? Will this later be possible via standard in JPA 2.0? Is there a better (in the sense of spec compliant) way to do this, or a workaround or even better bug fix for OpenJPA? Here is an attempt to sketch out the model that this occurs with: @javax.persistence.Entity(name = DictLabel) @IdClass(DictLabelId.class) @javax.persistence.Table(name = dict_label_vw) @javax.persistence.Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name=entity_dict_id, discriminatorType=DiscriminatorType.INTEGER) public abstract class DictLabelEntity { @Basic(optional = false) @javax.persistence.Column(name = name, nullable = false) private String name; @Id @javax.persistence.ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.LAZY, optional = false) @javax.persistence.JoinColumn(name = language_dict_id, nullable = false) private DictLanguageEntity language; @Id @Basic(optional = false) @javax.persistence.Column(name = entity_dict_id, nullable = false) private long entityRef; } @Entity(name = DictLanguageLabel) @IdClass(DictLanguageLabelId.class) @DiscriminatorValue(value=1106) public class DictLanguageLabelEntity extends DictLabelEntity { @Id @javax.persistence.ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.LAZY, optional = false) @javax.persistence.JoinColumn(name = object_dict_id, nullable = false) private DictLanguageEntity forLanguage; } public abstract class DictLabelId implements Serializable { public long language; public long entityRef; // ... equals() ... hashCode() ... } public class DictLanguageLabelId extends DictLabelId { public long forLanguage; // ... equals() ... hashCode() ... } With this, a simple query for SELECT l FROM DictLanguageLabel l leads to the exception below. The DictLanguageEntity is another entity deliberately omitted, it's a standard one with a simple @Id private long id. If this model seems to make little sense, I have to admit that it is simplified, as in real life there are other subclasses of DictLabelEntity, where that object_dict_id is a ManyToOne to other entities than DictLanguageEntity. I actually found a work-around, as follows: No DictLanguageLabelId extends DictLabelId (and no @IdClass on DictLanguageLabelEntity), and make DictLabelId not abstract. Then add the following to the DictLabelEntity to double map that object_dict_id column (which is also mapped in the DictLanguageLabelEntity subclass), and remove the @Id from the forLanguage in DictLanguageLabelEntity: @Id @Basic(optional = false) @javax.persistence.Column(name = object_dict_id, nullable = false) private long objectRef; and add a public long objectRef; to the DictLabelId (with updated equals() and hashCode()). seems to work, but is clearly a work-around for what appears to be a bug... Regards, Michael ___ openjpa-1.2.0-r422266:683325 nonfatal user error org.apache.openjpa.persistence.ArgumentException: 2 at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:814) at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:775) at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:771) at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:5 17) at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:254) at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:29 3) at com.odcgroup.tangij.nls.LabelsDAO.getAllLabels(LabelsDAO.java:38) at com.odcgroup.tangij.nls.LabelsDAOTest.testLabels(LabelsDAOTest.java:34) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
RE: ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve
Yes, with your test case, I did see the problem. The difference between our test cases is that in your test case, you have pre-created/populated the tables, while I let openjpa to create and populate the tables for me. Let me take a look to see why this causes the ArrayIndexOutOfBoundsException. Regards, Fay --- On Tue, 3/3/09, Michael Vorburger mvorbur...@odyssey-group.com wrote: From: Michael Vorburger mvorbur...@odyssey-group.com Subject: RE: ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve To: users@openjpa.apache.org Date: Tuesday, March 3, 2009, 2:51 PM Hello Fay, Uhm, I fiddled with the infrastructure of your ZIP a bit (NO code changed, but Mavenized, added a missing/forgotten persistence.xml, two CREATE TABLE and INSERT INTO), and voilà, run a mvn clean test on the attached updated test package and you'll see the problem! Do you confirm? Regards, Michael -Original Message- From: Fay Wang [mailto:fyw...@yahoo.com] Sent: Tuesday, March 03, 2009 10:21 PM To: users@openjpa.apache.org Subject: Re: ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve Hmmm. I could not reproduce the error using your domain model in 1.2.0 and trunk. Attached is the test case. Could you run it to see it passes? Regards, Fay --- On Tue, 3/3/09, Michael Vorburger mvorbur...@odyssey-group.com wrote: From: Michael Vorburger mvorbur...@odyssey-group.com Subject: ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve To: users@openjpa.apache.org Date: Tuesday, March 3, 2009, 11:57 AM Hello, I'm getting a ArrayIndexOutOfBoundsException in org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.retrieve (A pplicationIds.java:602), full stack trace below. This occurs when I try to use application ID Identity Hierarchies as per http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manua l/ jpa_overview_pc_identity.html#jpa_overview_pc_identity_hierarchy, may be because I was trying to use them together with Entities as Identity Fields as per http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manua l/ ref_guide_pc_oid.html#ref_guide_pc_oid_entitypk ... Both of this is not JPA 1.0 spec, is it? Will this later be possible via standard in JPA 2.0? Is there a better (in the sense of spec compliant) way to do this, or a workaround or even better bug fix for OpenJPA? Here is an attempt to sketch out the model that this occurs with: @javax.persistence.Entity(name = DictLabel) @IdClass(DictLabelId.class) @javax.persistence.Table(name = dict_label_vw) @javax.persistence.Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name=entity_dict_id, discriminatorType=DiscriminatorType.INTEGER) public abstract class DictLabelEntity { @Basic(optional = false) @javax.persistence.Column(name = name, nullable = false) private String name; @Id @javax.persistence.ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.LAZY, optional = false) @javax.persistence.JoinColumn(name = language_dict_id, nullable = false) private DictLanguageEntity language; @Id @Basic(optional = false) @javax.persistence.Column(name = entity_dict_id, nullable = false) private long entityRef; } @Entity(name = DictLanguageLabel) @IdClass(DictLanguageLabelId.class) @DiscriminatorValue(value=1106) public class DictLanguageLabelEntity extends DictLabelEntity { @Id @javax.persistence.ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.LAZY, optional = false) @javax.persistence.JoinColumn(name = object_dict_id, nullable = false) private DictLanguageEntity forLanguage; } public abstract class DictLabelId implements Serializable { public long language; public long entityRef; // ... equals() ... hashCode() ... } public class DictLanguageLabelId extends DictLabelId { public long forLanguage; // ... equals() ... hashCode() ... } With this, a simple query for SELECT l FROM DictLanguageLabel l leads to the exception below. The DictLanguageEntity is another entity deliberately omitted, it's a standard one with a simple @Id private long id. If this model seems to make little sense, I have to admit that it is simplified, as in real life there are other subclasses of DictLabelEntity, where that object_dict_id is a ManyToOne to other entities than DictLanguageEntity. I actually found a work-around, as follows: No DictLanguageLabelId extends DictLabelId (and no @IdClass on DictLanguageLabelEntity), and make DictLabelId
Re: @MappedSuperClass Cause Null Pointer Exception in Class With IdClass
The NPE is because the SituationDA is inherited from CashBaseEntity and CashBaseEntity does not have Id class. JIRA 873 is open to address this issue. Regards, Fay --- On Sat, 1/24/09, Drifter pioneer...@yahoo.com wrote: From: Drifter pioneer...@yahoo.com Subject: @MappedSuperClass Cause Null Pointer Exception in Class With IdClass To: users@openjpa.apache.org Date: Saturday, January 24, 2009, 4:30 AM Dear All .. i have four fieild that exist in all tables ..i want to use @MapperSuperClass .I test and I found that when there is a extended class that have IdClass PCEnhancer cuase null pointer exception. I use OpenJPA.1.2 in other cases there is no problem. in the following class in ValuableItemDA there is no problem and everything work well.. but in SituationDA that have a IdClass it cause null pointer excpetion. in PCEnhancer..i think i should add some extera annotation?but i dont know how solve the problem... @MappedSuperclass public abstract class CashBaseEntity extends BaseEntity{ @Column(name=TRCCRUI) private String createUser; @Column(name=TRCCRTS) private Date createTime; @Column(name=TRCLUUID) private String updateUser; @Column(name=TRCLUTS) private Date updateTime; @Version @Column(name=TRCVER) private int version; //getter setter removed ..for short post } @Entity @Table ( name = cc2SITUATION) @IdClass(SituationDA.SituationId.class) public class SituationDA extends CashBaseEntity{ @Id @Column(name=C2008SRL) private String CashBoxPeriodSerial; @Id @Column(name=C2012TYPE) private short Type; public static class SituationId implements Serializable{ private static final long serialVersionUID = 1L; public String CashBoxPeriodSerial; public short Type; public SituationId(){ } public boolean equals(Object other){ if (other instanceof SituationId) { final SituationId otherId = (SituationId)other; return ( otherId.CashBoxPeriodSerial.equals(this.CashBoxPeriodSerial) otherId.Type == this.Type ); } return false; } public int hashCode() { return super.hashCode(); } } //getter setter removed for short post.. } @Entity @Table (name = CF2VLUITEM) public class ValuableItemDA extends CashBaseEntity{ @Id @Column(name=C2001COD) private short Code; //getter setter removed for short post.. } -- View this message in context: http://n2.nabble.com/%40MappedSuperClass-Cause-Null-Pointer-Exception-in-Class-With-IdClass-tp2208581p2208581.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 Mike, I could not reproduce your problem. I used your entity definitions with the following modification: (1) put @Entity to the Test class (2) made Test class an abstract class, After the insert, my table has 5 rows in it: select id_column, CONTAINING_OBJ_ID from test_table ID_COLUMNCONTAINING_OBJ_ID - 1 1 3 1 4 - 2 1 5 - I then tested with the following: ContainingObject co = em.find(ContainingObject.class, 1); SetTestChild1 children = co.getTestChildren(); System.out.println(There are + children.size() + testChild1 objs); // THIS WILL SHOW all 5. The JDBC trace shows the push-down sql as: 1191 inheritance TRACE [main] openjpa.jdbc.SQL - t 1094861122, conn 910046782 executing prepstmnt 1434473856 SELECT t0.id_column, t0.discriminator, t0.containing_obj_id, t0.column_a, t0.site_id, t0.column_b FROM test_table t0 WHERE t0.containing_obj_id = ? [params=(int) 1] and I got 3 objects back. Which revision are you using? can you get the jdbc trace? Regards, Fay --- On Mon, 12/8/08, Jeremy Bauer [EMAIL PROTECTED] wrote: From: Jeremy Bauer [EMAIL PROTECTED] Subject: Re: Help - Single table inheritance not working with one-to-many collection To: users@openjpa.apache.org Date: Monday, December 8, 2008, 1:07 PM 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
Re: Help - Single table inheritance not working with one-to-many collection
Hi Mike, I could not reproduce your problem. I used your entity definitions with the following modification: (1) put @Entity to the Test class (2) made Test class an abstract class, After the insert, my table has 5 rows in it: select id_column, CONTAINING_OBJ_ID from test_table ID_COLUMNCONTAINING_OBJ_ID - 1 1 3 1 4 - 2 1 5 - I then tested with the following: ContainingObject co = em.find(ContainingObject.class, 1); SetTestChild1 children = co.getTestChildren(); System.out.println(There are + children.size() + testChild1 objs); // THIS WILL SHOW all 5. The JDBC trace shows the push-down sql as: and I got 3 back. Which revision are you using? can you get the jdbc trace? Regards, Fay --- On Mon, 12/8/08, Jeremy Bauer [EMAIL PROTECTED] wrote: From: Jeremy Bauer [EMAIL PROTECTED] Subject: Re: Help - Single table inheritance not working with one-to-many collection To: users@openjpa.apache.org Date: Monday, December 8, 2008, 1:07 PM 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
Re: Help - Single table inheritance not working with one-to-many collection
Sorry, the jdbc trac is missing in the previous mail: 1191 inheritance TRACE [main] openjpa.jdbc.SQL - t 1094861122, conn 910046782 executing prepstmnt 1434473856 SELECT t0.id_column, t0.discriminator, t0.containing_obj_id, t0.column_a, t0.site_id, t0.column_b FROM test_table t0 WHERE t0.containing_obj_id = ? [params=(int) 1] --- On Mon, 12/8/08, Fay Wang [EMAIL PROTECTED] wrote: From: Fay Wang [EMAIL PROTECTED] Subject: Re: Help - Single table inheritance not working with one-to-many collection To: users@openjpa.apache.org Cc: Fay Wang [EMAIL PROTECTED] Date: Monday, December 8, 2008, 2:21 PM Hi Mike, I could not reproduce your problem. I used your entity definitions with the following modification: (1) put @Entity to the Test class (2) made Test class an abstract class, After the insert, my table has 5 rows in it: select id_column, CONTAINING_OBJ_ID from test_table ID_COLUMNCONTAINING_OBJ_ID - 1 1 3 1 4 - 2 1 5 - I then tested with the following: ContainingObject co = em.find(ContainingObject.class, 1); SetTestChild1 children = co.getTestChildren(); System.out.println(There are + children.size() + testChild1 objs); // THIS WILL SHOW all 5. The JDBC trace shows the push-down sql as: and I got 3 back. Which revision are you using? can you get the jdbc trace? Regards, Fay --- On Mon, 12/8/08, Jeremy Bauer [EMAIL PROTECTED] wrote: From: Jeremy Bauer [EMAIL PROTECTED] Subject: Re: Help - Single table inheritance not working with one-to-many collection To: users@openjpa.apache.org Date: Monday, December 8, 2008, 1:07 PM 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
Re: Help - Single table inheritance not working with one-to-many collection
Hi Mike, I do have the discriminator column. I have the following columns in my test_table: Column name -- ID_COLUMN COLUMN_A SITE_ID DISCRIMINATOR COLUMN_B CONTAINING_OBJ_ID The sql select id_column, CONTAINING_OBJ_ID, discriminator from test_table generates the following result: ID_COLUMNCONTAINING_OBJ_ID DISCRIMINATOR - --- 1 1 S 3 1 S 4 - D 2 1 S 5 - D To get the trace, you can put property name=openjpa.Log value=DefaultLevel=TRACE / in your persistence.xml. Regards, Fay --- On Mon, 12/8/08, nibbler [EMAIL PROTECTED] wrote: From: nibbler [EMAIL PROTECTED] Subject: Re: Help - Single table inheritance not working with one-to-many collection To: users@openjpa.apache.org Date: Monday, December 8, 2008, 2:51 PM Hi Fay, I will figure out how to turn the trace on in eclipse and then do that and report back. I did notice in your trace it's not using the discriminator column? Did you set any values for that column in your table when running your example (thanks for doing that, btw :) If 2 of your rows have the discriminator set to 'S', then you should only get 2 TestChild1s back in the getTestChildren() method. I'm getting 5. Thanks, -Mike Fay Wang wrote: Hi Mike, I could not reproduce your problem. I used your entity definitions with the following modification: (1) put @Entity to the Test class (2) made Test class an abstract class, After the insert, my table has 5 rows in it: select id_column, CONTAINING_OBJ_ID from test_table ID_COLUMNCONTAINING_OBJ_ID - 1 1 3 1 4 - 2 1 5 - I then tested with the following: ContainingObject co = em.find(ContainingObject.class, 1); SetTestChild1 children = co.getTestChildren(); System.out.println(There are + children.size() + testChild1 objs); // THIS WILL SHOW all 5. The JDBC trace shows the push-down sql as: and I got 3 back. Which revision are you using? can you get the jdbc trace? Regards, Fay -- View this message in context: http://n2.nabble.com/Help---Single-table-inheritance-not-working-with-one-to-many-collection-tp1620948p1631360.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 Mike, I am not sure why your table has different values from mine. I don't explicitly set the null value for TestChild2 in the table. I used the following statements to persist the TestChild1, TestChild2 and ContainingObject according to your test scenario: TestChild1 c1 = new TestChild1(); c1.setIdColumn(1); c1.setColumnA(c1); c1.setColumnB(c1); c1.setSiteId(1); TestChild1 c2 = new TestChild1(); c2.setIdColumn(2); c2.setColumnA(c2); c2.setColumnB(c2); c2.setSiteId(2); TestChild1 c3 = new TestChild1(); c3.setIdColumn(3); c3.setColumnA(c3); c3.setColumnB(c3); c3.setSiteId(3); TestChild2 c4 = new TestChild2(); c4.setIdColumn(4); c4.setColumnA(c4); c4.setSiteId(5); TestChild2 c5 = new TestChild2(); c5.setIdColumn(5); c5.setColumnA(c5); c5.setSiteId(5); ContainingObject co = new ContainingObject(); co.addTestChild(c1); co.addTestChild(c2); co.addTestChild(c3); co.setId(1); c1.setContainingObject(co); c2.setContainingObject(co); c3.setContainingObject(co); tran.begin(); em.persist(c1); em.persist(c2); em.persist(c3); em.persist(c4); em.persist(c5); em.persist(co); tran.commit(); em.close(); These operations produce the rows in the test_table as I showed in the earlier mail. Also, in your ContainingObject, you have: // This is supposed to map a collection of TestChild1 objects. @OneToMany (mappedBy=co) private SetTestChild1 testChildren = new HashSetTestChild1(); so you should only see NULL value for your containing_obj_id column in your test_table for rows with discrimator = 'D'. Please let us know how you populate your test_table. Thanks! Regards, Fay --- On Mon, 12/8/08, nibbler [EMAIL PROTECTED] wrote: From: nibbler [EMAIL PROTECTED] Subject: Re: Help - Single table inheritance not working with one-to-many collection To: users@openjpa.apache.org Date: Monday, December 8, 2008, 3:53 PM I think you're actually having the same results as me, but your table values are different (specifically the containing_obj_id column). My trace looks like yours, i.e. it doesn't have the discriminator column in the sql. 1271 test TRACE [main] openjpa.jdbc.SQL - t 3916302, conn 24124380 executing prepstmnt 14008569 SELECT t0.id_column, t0.discriminator, t0.containing_obj_id, t0.column_a, t0.column_b FROM test_table t0 WHERE t0.containing_obj_id = ? [params=(long) 1] Your containing_obj_id column has null values for type 'D' discriminators, I think that's why you're getting the 3 TestChild1s back. If I null the 'D' rows, I also get 3. This Query: Query a = em.createQuery(select tc1 from TestChild tc1 where tc1.containingObjId=1); ListTestChild1 list = (ListTestChild1)query.getResultList(); will result in the correct sql: 1444 test TRACE [main] openjpa.jdbc.SQL - t 3916302, conn 33187868 executing prepstmnt 22975191 SELECT t0.id_column, t0.discriminator, t0.containing_obj_id, t0.column_a, t0.column_b FROM test_table t0 WHERE (t0.containing_obj_id = ?) AND t0.discriminator = ? [params=(long) 1, (String) S] The discriminator column is being used here. I think if you set the containing_obj_id column for the other rows, you'll see the problem I am seeing. Is this a bug in openjpa or am I misusing it? I am using openjpa-1.0.2.jar, with the Enhancer. Thanks again, -Mike Fay Wang wrote: Hi Mike, I do have the discriminator column. I have the following columns in my test_table: Column name -- ID_COLUMN COLUMN_A SITE_ID DISCRIMINATOR COLUMN_B CONTAINING_OBJ_ID The sql select id_column, CONTAINING_OBJ_ID, discriminator from test_table generates the following result: ID_COLUMNCONTAINING_OBJ_ID DISCRIMINATOR - --- 1 1 S 3 1 S 4 - D 2 1 S 5 - D To get the trace, you can put property name=openjpa.Log value=DefaultLevel=TRACE / in your persistence.xml. Regards, Fay -- View this message in context: http://n2.nabble.com/Help---Single-table-inheritance-not-working-with-one-to-many-collection-tp1620948p1631574.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Timestamp
Hi, You might want to try native query as follows: Query query = em.createNativeQuery(SELECT id FROM table WHERE MONTH( DATE(timestamp1) - DATE(timestamp2) ) 3 ) Fay --- On Thu, 11/20/08, du27177 [EMAIL PROTECTED] wrote: From: du27177 [EMAIL PROTECTED] Subject: Timestamp To: users@openjpa.apache.org Date: Thursday, November 20, 2008, 6:07 AM I have problem with timestamp in JPA query. I wonna select all data from database where difference between two timestamps is more than 2 month. Database: ID timestamp1 timestamp2 1 20008-11-19 15:0200020008-08-19 15:02000 2 20008-11-19 15:0200020008-11-14 15:02000 .. @Column(name = timestamp1, nullable = false) @Temporal(TemporalType.TIMESTAMP) public Date timestamp1; @Column(name = timestamp2, nullable = false) @Temporal(TemporalType.TIMESTAMP) public Date timestamp2; sql query works: select id from table where MONTH( DATE(timestamp1) - DATE(timestamp2) ) 3 but how I can write in Java? I't doesnt wrk: Query query = em.createQuery(SELECT id FROM table WHERE MONTH( DATE(timestamp1) - DATE(timestamp2) ) 3 ) -- View this message in context: http://n2.nabble.com/Timestamp-tp1557213p1557213.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key
Hi, Eli, It seems that you want to have pactId as a primary key and join column in the assigned_activities (child) table, and you want the pactId automatically generated in the project_activities (parent) table to fill in the pactId column (it is a primary key column) in the child table. I got the following error when trying to persist an Activity entity with two AssignedActivity objects to the database because PACT_ID column is both a primary key column and a foreign key column: openjpa-0.0.0-rnull fatal user error org.apache.openjpa.util.InvalidStateException: Attempt to set column ASSIGNED_ACTIVITIES.PACT_ID to two different values: (class java.lang.Integer)0, (class java.lang.Integer)7 This can occur when you fail to set both sides of a two-sided relation between objects, or when you map different fields to the same column, but you do not keep the values of these fields in synch. The workaround is not to use IdClass. Instead, to have consId alone as the primary key in the child table and pactId as the join column (foreign key column) in the child table. Hope this is helpful. Fay --- On Wed, 11/19/08, piltrafeta [EMAIL PROTECTED] wrote: From: piltrafeta [EMAIL PROTECTED] Subject: Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key To: users@openjpa.apache.org Date: Wednesday, November 19, 2008, 9:38 AM Hi Fay, I've done the modification you told me but it's still not working... when i insert new registers the pactId from assignedActivities remains null. I copy the class activity with the modification: @Entity @Table (name=PROJECT_ACTIVITIES) @SequenceGenerator(name = SEQ_PACT_ID, sequenceName = SEQ_PACT_ID, allocationSize = 1) public class Activity implements IsSerializable{ @Id @Column(name=PACT_ID, nullable=false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQ_PACT_ID) private Integer id = null; @Column(name=PACT_DESC) private String desc = null; @Column (name =STATE) private Integer state = null; @Column (name =PROJ_ID) private Integer idProject = null; @Column (name =PACT_DUE_DATE) private Date dueDate = null; @OneToMany (mappedBy=activity, fetch = FetchType.LAZY) @JoinColumn (name = PACT_ID, nullable = false) @Cascade({CascadeType.ALL,CascadeType.DELETE_ORPHAN}) private SetAssignedActivity assignedTo = new HashSetAssignedActivity(); ..} Regards, Eli Fay Wang wrote: Hi, In your test case, you have OneToMany relation from Activity to AssignedActivity. The mappedBy attribute in the OneToMany relation should be the name of the many-to-one field in the related entity that maps this bidirectional relation. Could you change mappedBy to activity and try again? Regards, Fay --- On Tue, 11/18/08, piltrafeta [EMAIL PROTECTED] wrote: From: piltrafeta [EMAIL PROTECTED] Subject: Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key To: users@openjpa.apache.org Date: Tuesday, November 18, 2008, 11:56 AM Hi! I'm having a similar problem for a while, maybe you can help me... My classes are like this : @Entity @Table(name = ASSIGNED_ACTIVITIES) @IdClass(AssignedActivityPk.class) public class AssignedActivity implements IsSerializable { @Id @Column (name = CONS_ID, nullable=false) private Integer consId; @Id @Column (name = PACT_ID, nullable=false) private Integer pactId; @Column (name = TYPE) private Integer type; @Column (name = ASG_EST_TIME) private Integer asgEstTime; @ManyToOne @JoinColumn (name = PACT_ID, nullable=false, insertable = false, updatable = false) private Activity activity; ...} @Embeddable public class AssignedActivityPk implements Serializable { @Id @Column (name = CONS_ID, nullable=false) private Integer consId; @Id @Column (name = PACT_ID, nullable=false) private Integer pactId; ...} @Entity @Table (name=PROJECT_ACTIVITIES) @SequenceGenerator(name = SEQ_PACT_ID, sequenceName = SEQ_PACT_ID, allocationSize = 1) public class Activity implements IsSerializable{ @Id @Column(name=PACT_ID, nullable=false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQ_PACT_ID) private Integer id = null; @Column(name=PACT_DESC) private String desc = null; @OneToMany (mappedBy=pactId, fetch = FetchType.LAZY) @JoinColumn (name = PACT_ID, nullable = false) @Cascade({CascadeType.ALL,CascadeType.DELETE_ORPHAN}) private SetAssignedActivity assignedTo = new HashSetAssignedActivity(); ...} As the id from the parent class (Activity) is generated by a sequence from the database, when I'm trying to insert a new Activity, the record for parent object is correct (the id
Re: WebSphere @OneToOne problem
Can you turn on the trace? -Fay --- On Tue, 11/4/08, John VanAntwerp [EMAIL PROTECTED] wrote: From: John VanAntwerp [EMAIL PROTECTED] Subject: WebSphere @OneToOne problem To: users@openjpa.apache.org Date: Tuesday, November 4, 2008, 9:14 PM We have an entity that inherits from another entity as described in the code snippet below. The specific field we are having trouble with is the editorInfo field. editorInfo needs to be optional because, as you would expect, a new entity has not been modified, so it has no editor information. The specific problem is that intermittently the editorInfo field will not be filled out even though the appropriate rows exist in the joined table. At times the join works perfectly, then, for the same entity and keys, it will apparently fail and the value of editorInfo will be NULL. Has anyone else seen this kind of issue? Is there something wrong with the way we have annotated the relationship? Thanks! - John @Entity @Table(name=MODIFICATION_TABLE) @Inheritance(strategy=InheritanceType.JOINED) public class TheEntityExtended extends TheEntity { private static final long serialVersionUID = (a number)L; @SuppressWarnings(unused) @OneToOne(fetch=FetchType.EAGER, optional=true) @JoinColumn(name=AUTHOR_KEY) public UserInfoEntity authorInfo; @SuppressWarnings(unused) @OneToOne(fetch=FetchType.EAGER, optional=true) @JoinColumn(name=DELETED_KEY) public UserInfoEntity deletorInfo; @SuppressWarnings(unused) @OneToOne(fetch=FetchType.EAGER, optional=true) @JoinColumn(name=EDITOR_KEY) public UserInfoEntity editorInfo; } -- View this message in context: http://n2.nabble.com/WebSphere-%40OneToOne-problem-tp1458838p1458838.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Native Query: Update fails with InvalidStateException
Hi, Stuart, The error message Cannot perform an update or delete operation on select query: Update FPA2.NW_OR_004_14702765 Set Cost=? Where PT_GRID_ID=?. suggests that openjpa thinks your native query is a select statement. The call to executeUpdate therefore can not be performed on a select statement. There are a couple of reasons why openjpa thinks your query is a select statement. The following is an example (note the result class, BasicA.class, is an input paramter to the createNativeQuery api). An executeUpdate on it results in the same error as you describe: Query q = em.createNativeQuery(UPDATE BasicA t set t.name= ? WHERE t.id = ?, BasicA.class); The query below takes out the result class and works just fine: Query q = em.createNativeQuery(UPDATE BasicA t set t.name= ? WHERE t.id = ?); Regards, Fay --- On Tue, 10/28/08, Stuart Bedoll [EMAIL PROTECTED] wrote: From: Stuart Bedoll [EMAIL PROTECTED] Subject: Re: Native Query: Update fails with InvalidStateException To: users@openjpa.apache.org Date: Tuesday, October 28, 2008, 1:06 PM What version of the IBM feature pack did you use. I am at: Name WebSphere Application Server Version 6.1 Feature Pack for EJB 3.0 Version 6.1.0.13 ID EJB3 Build Level f0747.05 Build Date 11/30/07 Installed Product Fay Wang [EMAIL PROTECTED] Fay Wang [EMAIL PROTECTED] 10/27/2008 10:10 AM Please respond to users@openjpa.apache.org To users@openjpa.apache.org cc Subject Re: Native Query: Update fails with InvalidStateException Hi, I could not reproduce this problem against DB2. Which database are you using? also,can you post your persistence.xml to see if there is any special setting? Fay --- On Mon, 10/27/08, sbedoll [EMAIL PROTECTED] wrote: From: sbedoll [EMAIL PROTECTED] Subject: Native Query: Update fails with InvalidStateException To: users@openjpa.apache.org Date: Monday, October 27, 2008, 6:37 AM I am using local transactions and get this error when executing a NativeQuery (query.executeUpdate) openjpa-1.0.1-r420667:592145 nonfatal user error org.apache.openjpa.persistence.InvalidStateException: Cannot perform an update or delete operation on select query: Update FPA2.NW_OR_004_14702765 Set Cost=? Where PT_GRID_ID=?. at org.apache.openjpa.persistence.QueryImpl.executeUpdate(QueryImpl.java:324) at fpa.fw.ds.jpadataadapter.JPADataSourceAdapter.executeNativeUpdate(JPADataSourceAdapter.java:815) I am using IBM JPA. Is there something I am missing ? -- View this message in context: http://n2.nabble.com/Native-Query%3A-Update-fails-with-InvalidStateException-tp1382362p1382362.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Native Query: Update fails with InvalidStateException
Hi, Stuart, The error message Cannot perform an update or delete operation on select query suggests that openjpa thinks your query is a select operation, and therefore when executeUpdate is called on this query, openjpa does not know how to update/delete on the select statement. There are a couple of reason why openjpa will think a query is a select statement. The following is one example: Query query = em.createNativeQuery(update BasicA set name = ? where id =?, BasicA.class); Note that the result class (BasicA.class) is provided as an extra input parameter to the createNativeQuery api. For this query object, if you call executeUpdate on it, you will get Cannot perform an update or delete operation on select query error. You might want to check your code to see exactly how the native query is created. Regards, Fay --- On Tue, 10/28/08, Stuart Bedoll [EMAIL PROTECTED] wrote: From: Stuart Bedoll [EMAIL PROTECTED] Subject: Re: Native Query: Update fails with InvalidStateException To: users@openjpa.apache.org Date: Tuesday, October 28, 2008, 1:06 PM What version of the IBM feature pack did you use. I am at: Name WebSphere Application Server Version 6.1 Feature Pack for EJB 3.0 Version 6.1.0.13 ID EJB3 Build Level f0747.05 Build Date 11/30/07 Installed Product Fay Wang [EMAIL PROTECTED] Fay Wang [EMAIL PROTECTED] 10/27/2008 10:10 AM Please respond to users@openjpa.apache.org To users@openjpa.apache.org cc Subject Re: Native Query: Update fails with InvalidStateException Hi, I could not reproduce this problem against DB2. Which database are you using? also,can you post your persistence.xml to see if there is any special setting? Fay --- On Mon, 10/27/08, sbedoll [EMAIL PROTECTED] wrote: From: sbedoll [EMAIL PROTECTED] Subject: Native Query: Update fails with InvalidStateException To: users@openjpa.apache.org Date: Monday, October 27, 2008, 6:37 AM I am using local transactions and get this error when executing a NativeQuery (query.executeUpdate) openjpa-1.0.1-r420667:592145 nonfatal user error org.apache.openjpa.persistence.InvalidStateException: Cannot perform an update or delete operation on select query: Update FPA2.NW_OR_004_14702765 Set Cost=? Where PT_GRID_ID=?. at org.apache.openjpa.persistence.QueryImpl.executeUpdate(QueryImpl.java:324) at fpa.fw.ds.jpadataadapter.JPADataSourceAdapter.executeNativeUpdate(JPADataSourceAdapter.java:815) I am using IBM JPA. Is there something I am missing ? -- View this message in context: http://n2.nabble.com/Native-Query%3A-Update-fails-with-InvalidStateException-tp1382362p1382362.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Native Query: Update fails with InvalidStateException
Hi, I could not reproduce this problem against DB2. Which database are you using? also,can you post your persistence.xml to see if there is any special setting? Fay --- On Mon, 10/27/08, sbedoll [EMAIL PROTECTED] wrote: From: sbedoll [EMAIL PROTECTED] Subject: Native Query: Update fails with InvalidStateException To: users@openjpa.apache.org Date: Monday, October 27, 2008, 6:37 AM I am using local transactions and get this error when executing a NativeQuery (query.executeUpdate) openjpa-1.0.1-r420667:592145 nonfatal user error org.apache.openjpa.persistence.InvalidStateException: Cannot perform an update or delete operation on select query: Update FPA2.NW_OR_004_14702765 Set Cost=? Where PT_GRID_ID=?. at org.apache.openjpa.persistence.QueryImpl.executeUpdate(QueryImpl.java:324) at fpa.fw.ds.jpadataadapter.JPADataSourceAdapter.executeNativeUpdate(JPADataSourceAdapter.java:815) I am using IBM JPA. Is there something I am missing ? -- View this message in context: http://n2.nabble.com/Native-Query%3A-Update-fails-with-InvalidStateException-tp1382362p1382362.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Exception in SQLBuffer.java on OpenJPA 1.3.0-SNAPSHOT
())) { setTblCdedes2(getTblCdedes2()); } } protected void synchChildRelationships(){ syncCollection(getTblTrkitms()); syncObject(getTblTrkdetcng()); } public Date getVluDte() { return vluDte; } public void setVluDte(Date vluDte) { this.vluDte = vluDte; } public String getFsbNme() { return fsbNme; } public void setFsbNme(String fsbNme) { this.fsbNme = fsbNme; } public String getFsbCde() { return fsbCde; } public void setFsbCde(String fsbCde) { this.fsbCde = fsbCde; } public String getXfrtypCde() { return xfrtypCde; } public void setXfrtypCde(String xfrtypCde) { this.xfrtypCde = xfrtypCde; } } Fay Wang wrote: Hi Enrico, I made up TblItmtyp and TblTrkdet and ran a test case with the code snippet you provided. It worked just fine. You mentioned that the test case works fine with 1.2.0. Can you provide the generated sql on 1.2.0? Regards, Fay -- View this message in context: http://n2.nabble.com/Exception-in-SQLBuffer.java-on-OpenJPA-1.3.0-SNAPSHOT-tp1141997p1300409.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Exception in SQLBuffer.java on OpenJPA 1.3.0-SNAPSHOT
The class TblTrkdet is also missing... --- On Fri, 10/3/08, Fay Wang [EMAIL PROTECTED] wrote: From: Fay Wang [EMAIL PROTECTED] Subject: Re: Exception in SQLBuffer.java on OpenJPA 1.3.0-SNAPSHOT To: users@openjpa.apache.org Date: Friday, October 3, 2008, 8:34 AM Hi Enrico, Could you also provide class TblItmtyp? Thanks! --- On Fri, 10/3/08, egoosen [EMAIL PROTECTED] wrote: From: egoosen [EMAIL PROTECTED] Subject: Exception in SQLBuffer.java on OpenJPA 1.3.0-SNAPSHOT To: users@openjpa.apache.org Date: Friday, October 3, 2008, 6:46 AM Hi, I'm getting the following exception when this code runs: public TblItmdes getTrackingItem(String itmCde){ TblItmdes tblItmdes = getTblItmdesDAO().findTblItmdesByItmCde(itmCde); tblItmdes.getTblTrklnks(); //-- lazy load throws exception return tblItmdes; } PS. It works fine in 1.1.0. Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.RangeCheck(ArrayList.java:546) at java.util.ArrayList.get(ArrayList.java:321) at org.apache.openjpa.jdbc.sql.SQLBuffer.setParameters(SQLBuffer.java:629) at org.apache.openjpa.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:529) at org.apache.openjpa.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:485) at org.apache.openjpa.jdbc.sql.SelectImpl.prepareStatement(SelectImpl.java:463) at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:379) at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:339) at org.apache.openjpa.jdbc.sql.LogicalUnion$UnionSelect.execute(LogicalUnion.java:420) at org.apache.openjpa.jdbc.sql.LogicalUnion.execute(LogicalUnion.java:230) at org.apache.openjpa.jdbc.sql.LogicalUnion.execute(LogicalUnion.java:220) at org.apache.openjpa.jdbc.meta.strats.StoreCollectionFieldStrategy.load(StoreCollectionFieldStrategy.java:603) at org.apache.openjpa.jdbc.meta.FieldMapping.load(FieldMapping.java:822) at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.load(JDBCStoreManager.java:626) at org.apache.openjpa.kernel.DelegatingStoreManager.load(DelegatingStoreManager.java:116) at org.apache.openjpa.kernel.ROPStoreManager.load(ROPStoreManager.java:78) at org.apache.openjpa.kernel.StateManagerImpl.loadFields(StateManagerImpl.java:2920) at org.apache.openjpa.kernel.StateManagerImpl.loadField(StateManagerImpl.java:2998) at org.apache.openjpa.kernel.StateManagerImpl.beforeAccessField(StateManagerImpl.java:1492) at org.apache.openjpa.kernel.StateManagerImpl.accessingField(StateManagerImpl.java:1477) at za.co.metcapri.model.ebstatus.TblItmdes.pcGettblTrklnks(TblItmdes.java) at za.co.metcapri.model.ebstatus.TblItmdes.getTblTrklnks(TblItmdes.java:77) at za.co.metcapri.status.business.AdminManagerBean.getTrackingItem(AdminManagerBean.java:84) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:299) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:139) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:54) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy41.getTrackingItem(Unknown Source) at za.co.metcapri.status.server.services.AdminServiceBean.getTrackingItemLinks(AdminServiceBean.java:61) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585
Re: Exception in SQLBuffer.java on OpenJPA 1.3.0-SNAPSHOT
Hi Enrico, I made up TblItmtyp and TblTrkdet and ran a test case with the code snippet you provided. It worked just fine. You mentioned that the test case works fine with 1.2.0. Can you provide the generated sql on 1.2.0? Regards, Fay --- On Fri, 10/3/08, egoosen [EMAIL PROTECTED] wrote: From: egoosen [EMAIL PROTECTED] Subject: Re: Exception in SQLBuffer.java on OpenJPA 1.3.0-SNAPSHOT To: users@openjpa.apache.org Date: Friday, October 3, 2008, 6:56 AM I just tested on 1.2.0 and it works fine there too. -- View this message in context: http://n2.nabble.com/Exception-in-SQLBuffer.java-on-OpenJPA-1.3.0-SNAPSHOT-tp1141997p1142020.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OpenJPA 1.2.0 Bug on FetchType.EAGER
Hi, I can reproduce this problem. Please open a JIRA for this problem. Thanks! -Fay --- On Fri, 9/19/08, egoosen [EMAIL PROTECTED] wrote: From: egoosen [EMAIL PROTECTED] Subject: OpenJPA 1.2.0 Bug on FetchType.EAGER To: users@openjpa.apache.org Date: Friday, September 19, 2008, 12:49 AM I'm experiencing a strange bug in 1.2.0, on an eager loaded one to many relationship. The first time I run the code, openJPA retrieves the parent entity and eager fetches the CORRECT child entities. The second time around, it fetches the parent entity and fetches the INCORRECT child entities (specifically, it fetches the child entities of the parent entity in the previous query). Here's the SQL to illustrate: First run: SELECT t0.AMDCTL_ID, t0.VRS_NBR, t0.AMDSEQ_CDE, t0.DPLORD_NBR, t0.FND_CDE, t0.RSL_DTE FROM EBSTATUS.TBL_AMDCTL t0 WHERE t0.FND_CDE = ? [params=(String) 001] SELECT t0.AMDCTL_ID, t1.AMDDES_ID, t1.VRS_NBR, t1.AMD_DES, t1.AMDCTL_ID, t1.EFC_DTE FROM EBSTATUS.TBL_AMDCTL t0 INNER JOIN EBSTATUS.TBL_AMDDES t1 ON t0.AMDCTL_ID = t1.AMDCTL_ID WHERE t0.FND_CDE = ? ORDER BY t0.AMDCTL_ID ASC [params=(String) 001] Second run: SELECT t0.AMDCTL_ID, t0.VRS_NBR, t0.AMDSEQ_CDE, t0.DPLORD_NBR, t0.FND_CDE, t0.RSL_DTE FROM EBSTATUS.TBL_AMDCTL t0 WHERE t0.FND_CDE = ? [params=(String) 0001001] SELECT t0.AMDCTL_ID, t1.AMDDES_ID, t1.VRS_NBR, t1.AMD_DES, t1.AMDCTL_ID, t1.EFC_DTE FROM EBSTATUS.TBL_AMDCTL t0 INNER JOIN EBSTATUS.TBL_AMDDES t1 ON t0.AMDCTL_ID = t1.AMDCTL_ID WHERE t0.FND_CDE = ? ORDER BY t0.AMDCTL_ID ASC [params=(String) 001] Somehow its caching the second query, even though I've turned off the DataCache and QueryCache. I've had to revert back to OpenJPA 1.1.0. Here's my mappings: TblAmdctl.java @OneToMany(mappedBy=tblAmdctl,fetch = FetchType.EAGER,cascade = { CascadeType.PERSIST,CascadeType.MERGE}) private CollectionTblAmddes tblAmddess = new ArrayListTblAmddes(); TblAmddes.java @ManyToOne(fetch = FetchType.LAZY,cascade = { CascadeType.PERSIST,CascadeType.MERGE }) @JoinColumns([EMAIL PROTECTED](name = AMDCTL_ID,referencedColumnName=AMDCTL_ID)}) @ForeignKey private TblAmdctl tblAmdctl; -- View this message in context: http://n2.nabble.com/OpenJPA-1.2.0-Bug-on-FetchType.EAGER-tp1100274p1100274.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: OpenJPA 1.2.0 Bug on FetchType.EAGER
Sorry, I spoke too soon. My test case actually runs fine. The following listings are my TblAmdCtl.java, TblAmdDes.java and TestQuerySQLCache. Could you attach your test case to reproduce this problem in the JIRA? Thanks! (1) TblAmdCtl.java @Entity public class TblAmdctl { @OneToMany(mappedBy=tblAmdctl,fetch = FetchType.EAGER,cascade = { CascadeType.PERSIST,CascadeType.MERGE}) private CollectionTblAmddes tblAmddess = new ArrayListTblAmddes(); @Id @Column(name=AMDCTL_ID) private int AMDCTL_ID; public void setId(int id) { this.AMDCTL_ID = id; } public int getId() { return AMDCTL_ID; } public Collection getTblAmddes() { return tblAmddess; } public void addTblAmddes(TblAmddes t) { tblAmddess.add(t); } } (2) TblAmddes.java @Entity public class TblAmddes { @ManyToOne(fetch = FetchType.LAZY,cascade = { CascadeType.PERSIST,CascadeType.MERGE }) @JoinColumns([EMAIL PROTECTED](name = AMDCTL_ID,referencedColumnName=AMDCTL_ID)}) @ForeignKey private TblAmdctl tblAmdctl; @Id private int id; public void setId(int id) { this.id = id; } public int getId() { return id; } public TblAmdctl getTblAmdctl() { return tblAmdctl; } public void setTblAmdctl(TblAmdctl t) { tblAmdctl = t; } } (3) test case: public class TestQuerySQLCache { public static void main (String[] args) { createObj(); findObj(); } public static void createObj() { EntityManager em = Persistence.createEntityManagerFactory(JpaDemo2). createEntityManager(); EntityTransaction tran = em.getTransaction(); TblAmdctl ctl1 = new TblAmdctl(); ctl1.setId(1); TblAmddes des1 = new TblAmddes(); des1.setId(1); des1.setTblAmdctl(ctl1); TblAmddes des2 = new TblAmddes(); des2.setId(2); des2.setTblAmdctl(ctl1); ctl1.addTblAmddes(des1); ctl1.addTblAmddes(des2); TblAmdctl ctl2 = new TblAmdctl(); ctl2.setId(2); TblAmddes des3 = new TblAmddes(); des3.setId(3); des3.setTblAmdctl(ctl2); TblAmddes des4 = new TblAmddes(); des4.setId(4); des4.setTblAmdctl(ctl2); ctl2.addTblAmddes(des3); ctl2.addTblAmddes(des4); tran.begin(); em.persist(ctl1); em.persist(ctl2); em.persist(des1); em.persist(des2); em.persist(des3); em.persist(des4); em.flush(); tran.commit(); } public static void findObj() { EntityManager em = Persistence.createEntityManagerFactory(JpaDemo2). createEntityManager(); EntityTransaction tran = em.getTransaction(); TblAmdctl ctl1 = em.find(TblAmdctl.class, 1); CollectionTblAmddes dess1 = ctl1.getTblAmddes(); for (TblAmddes des : dess1) System.out.println(des id = + des.getId()); TblAmdctl ctl2 = em.find(TblAmdctl.class, 2); CollectionTblAmddes dess2 = ctl2.getTblAmddes(); for (TblAmddes des : dess2) System.out.println(des id = + des.getId()); } } --- On Fri, 9/19/08, Fay Wang [EMAIL PROTECTED] wrote: From: Fay Wang [EMAIL PROTECTED] Subject: Re: OpenJPA 1.2.0 Bug on FetchType.EAGER To: users@openjpa.apache.org Date: Friday, September 19, 2008, 9:14 AM Hi, I can reproduce this problem. Please open a JIRA for this problem. Thanks! -Fay --- On Fri, 9/19/08, egoosen [EMAIL PROTECTED] wrote: From: egoosen [EMAIL PROTECTED] Subject: OpenJPA 1.2.0 Bug on FetchType.EAGER To: users@openjpa.apache.org Date: Friday, September 19, 2008, 12:49 AM I'm experiencing a strange bug in 1.2.0, on an eager loaded one to many relationship. The first time I run the code, openJPA retrieves the parent entity and eager fetches the CORRECT child entities. The second time around, it fetches the parent entity and fetches the INCORRECT child entities (specifically, it fetches the child entities of the parent entity in the previous query). Here's the SQL to illustrate: First run: SELECT t0.AMDCTL_ID, t0.VRS_NBR, t0.AMDSEQ_CDE, t0.DPLORD_NBR, t0.FND_CDE, t0.RSL_DTE FROM EBSTATUS.TBL_AMDCTL t0 WHERE t0.FND_CDE = ? [params=(String) 001] SELECT t0.AMDCTL_ID, t1.AMDDES_ID, t1.VRS_NBR, t1.AMD_DES, t1.AMDCTL_ID, t1.EFC_DTE FROM EBSTATUS.TBL_AMDCTL t0 INNER JOIN EBSTATUS.TBL_AMDDES t1 ON t0.AMDCTL_ID = t1.AMDCTL_ID WHERE t0.FND_CDE = ? ORDER BY t0.AMDCTL_ID
Re: Example of Enum mapping (fixed numbering)
Here is an example: @Entity public class EntityA { @Id private int id; @Enumerated( EnumType.ORDINAL ) private Measure measure; public Measure getMeasure() { return measure; } public void setMeasure(Measure measure) { this.measure = measure; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public enum Measure { M1 (M1, false), M2 (M2, false), M3 (M3, false), M4 (M4, false), M5 (M5, true); private String description; private Measure(String desc){ this.description=desc; } public String desc(){return this.description;} } --- On Wed, 9/17/08, Michael Vorburger [EMAIL PROTECTED] wrote: From: Michael Vorburger [EMAIL PROTECTED] Subject: Example of Enum mapping (fixed numbering) To: users@openjpa.apache.org Date: Wednesday, September 17, 2008, 8:29 AM Does anybody have a concrete example of how to map an enum with fixed ordinal numbering? I have a DB which has an numeric column where the existing values mean something. I want to map that to an Entity attribute of some enum type. Reading http://forums.oracle.com/forums/thread.jspa?threadID=658154 and http://appfuse.org/display/APF/Java+5+Enums+Persistence+with+Hibernate I realize standard JPA does NOT actually do this (shame! hopefully this will be considered in JPA 2.0). However using some kind of Custom Field Mapping / Value Handler / Field Strategy annotation (http://openjpa.apache.org/builds/latest/docs/manual/manual.html#ref_gui de_mapping_custom) this probably possible... any example handy? Thanks, Michael • 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: ArrayIndexOutOfBoundsException:0 at org.apache.openjpa.jdbc.sql.DBDictionary.getForeignKeyConstraintSQL(DBDictionary.java:3373)
Yes, you are right. This problem is caused by a relation field being annotated as a primary key and foreign key. You might want to apply the patch I put in JIRA-679. Before the patch: CREATE TABLE D (id VARCHAR(254) NOT NULL, a VARCHAR(254), C_CID VARCHAR(254), C_CM_CMID VARCHAR(254), C_CM_E_EID VARCHAR(254), PRIMARY KEY (id)) After the patch: CREATE TABLE D (id VARCHAR(254) NOT NULL, a VARCHAR(254), C_CID VARCHAR(254), C_CM_CMID VARCHAR(254), C_CM_E_EID VARCHAR(254), VC_VCID VARCHAR(254) NOT NULL, VC_VCS_E_EID VARCHAR(254) NOT NULL, VC_VCS_VCSID VARCHAR(254) NOT NULL, PRIMARY KEY (id, VC_VCID, VC_VCS_E_EID, VC_VCS_VCSID)) --- On Fri, 8/8/08, Gopalakrishnan U [EMAIL PROTECTED] wrote: From: Gopalakrishnan U [EMAIL PROTECTED] Subject: Re: ArrayIndexOutOfBoundsException:0 at org.apache.openjpa.jdbc.sql.DBDictionary.getForeignKeyConstraintSQL(DBDictionary.java:3373) To: users@openjpa.apache.org Date: Friday, August 8, 2008, 2:01 AM The SQL generated for creating OPENJPASAMPLE.D table is wrong. Here is the SQL generated for creating the D table CREATE TABLE OPENJPASAMPLE.D (id INTEGER NOT NULL, C_CID INTEGER, C_CM_CMID INTEGER, C_CM_E_EID INTEGER, PRIMARY KEY (id)). It is missing fields from VC -- D relation and corresponding PKs I think this is causing the problem when it is trying to generate the SQL for creating FK for the OPENJPASAMPLE.D table. Opened a JIRA for this issue https://issues.apache.org/jira/browse/OPENJPA-682. Gopal -- View this message in context: http://n2.nabble.com/ArrayIndexOutOfBoundsException%3A0-at-org.apache.openjpa.jdbc.sql.DBDictionary.getForeignKeyConstraintSQL%28DBDictionary.java%3A3373%29-tp668199p680224.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Cascade Delete Issue?
Hi, You might want to add @ElementDependent as shown below: @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = parent) @OrderBy(value = ordr) @ElementDependent private ListChild children = new ArrayListChild(); so that when you do: em.getTransaction().begin(); parent.removeChildren(); em.flush(); em.getTransaction().commit(); the children will be removed from the database. --- On Wed, 8/6/08, andiqo [EMAIL PROTECTED] wrote: From: andiqo [EMAIL PROTECTED] Subject: Cascade Delete Issue? To: users@openjpa.apache.org Date: Wednesday, August 6, 2008, 2:37 AM Hello, I have two entities PARENT CHILD defined below. I try to reset the Parent.children list, or remove the parent entity, but nothing happen in database for my children (I cant get my children anymore from Java code (parent.getChildren()), but they are still present in database even after a commit operation). Any idea? It sounds like a OpenJPA issue for me. Thanks a lot for our help. Regards, Nicolas P.S. Tried with openjpa 1.0.3 1.1.0 @Entity @Table(name = PARENT) public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = ID) private long id; @Version @Column(name = VERSION) private int version; @Basic @Column(name = NAME) private String name; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = parent) @OrderBy(value = ordr) private ListChild children = new ArrayListChild(); } @Entity @Table(name = CHILD) public class Child { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = ID) private long id; @Version @Column(name = VERSION) private int version; @Basic @Column(name = ORDR) private int ordr; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = PARENT_ID, nullable = false) private Parent parent; @Basic @Column(name = NAME) private String name; } -- View this message in context: http://n2.nabble.com/Cascade-Delete-Issue--tp675459p675459.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: How to apply creation timestamp with
I can reproduce this problem against DB2. It looks like that this problem is generic, independent of the backend. The jdbc trace shows: 7828 CustomerOrder TRACE [main] openjpa.jdbc.SQL - t 1090273532, conn 582492856 executing prepstmnt 1346129980 INSERT INTO EntityA (id, amt, creationts, name) VALUES (?, ?, ?, ?) [params=(int) 1, (double) 0.0, (null) null, (null) null]. Shouldn't Openjpa formulate the insert statement as: INSERT INTO EntityA (id, amt) VALUES(?,?) and exclude the columns from the insert statement where the values are null? -fay --- On Tue, 8/5/08, Marcel Ruff [EMAIL PROTECTED] wrote: From: Marcel Ruff [EMAIL PROTECTED] Subject: How to apply creation timestamp with To: users@openjpa.apache.org Date: Tuesday, August 5, 2008, 2:14 AM Hi, i need to set for Postgres 8.3.x on new table entry creation a timestamp and have tried this: @Column(name = creationts, columnDefinition=timestamp not null default current_timestamp) public java.sql.Timestamp getCreationTs() { return creationTs; } The dll applied to Postgres directly works fine and creates the timestamp during insert on the fly. Using openJpa i get: org.apache.openjpa.persistence.PersistenceException: ERROR: null value in column creationts violates not-null constraint what can i do? Thanks Marcel -- Marcel Ruff http://watchee.net
Re: How to apply creation timestamp with
Hi, Omitting the not null from column definition will make the test case work. However, the insert statement as shown below in the jdbc trace will insert null into the creationts column, and the current timestamp (default by db) will never get inserted into the table. Is this the expected behavior? 6609 CustomerOrder TRACE [main] openjpa.jdbc.SQL - t 1090273532, conn 907294228 executing prepstmnt 94897576 INSERT INTO EntityA (id, amt, creationts, name) VALUES (?, ?, ?, ?) [params=(int) 1, (double) 0.0, (null) null, (null) null] 6625 CustomerOrder TRACE [main] openjpa.jdbc.SQL - t 1090273532, conn 907294228 [16 ms] spent 6641 CustomerOrder TRACE [main] openjpa.jdbc.JDBC - t 1090273532, conn 907294228 [0 ms] commit --- On Tue, 8/5/08, Pinaki Poddar [EMAIL PROTECTED] wrote: From: Pinaki Poddar [EMAIL PROTECTED] Subject: Re: How to apply creation timestamp with To: users@openjpa.apache.org Date: Tuesday, August 5, 2008, 4:15 PM Hi, Omit 'not null' constraint from the column definition. @Column(name = creationts, columnDefinition=timestamp current_timestamp) -- View this message in context: http://n2.nabble.com/How-to-apply-creation-timestamp-with-tp673210p674789.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Query problem with open jpa 1.0.2
Hi, Please do the following: select j from job j -fay --- On Tue, 7/8/08, tao [EMAIL PROTECTED] wrote: From: tao [EMAIL PROTECTED] Subject: Query problem with open jpa 1.0.2 To: users@openjpa.apache.org Date: Tuesday, July 8, 2008, 3:30 PM Hi, I'm working on a project using openjpa 1.0.2. I got org.apache.openjpa.persistence.ArgumentException while executing a simple query today, wish someone can help me on this issue. Thanks The query I'm trying to execute is: select job from job j Moreover there is no problem for me to create a new job record. Three related persistence classes are defined as the following: @Table(name = job) @Entity(name = job) public class Job implements Serializable{ @Id @Column (name = job_id) @GeneratedValue(strategy = GenerationType.IDENTITY) private long jobId; @Column (name = job_name, length = 255, nullable = false) private String jobName; @Column private String status; @ManyToOne (optional = false) @JoinColumn(name = create_by, referencedColumnName = user_id) private User createUser; @Column (name = create_time) private Date createTime; @ManyToOne (optional = true) @JoinColumn(name = update_by, referencedColumnName = user_id) private User updateUser; @Column (name = update_time) private Date updateTime; @ManyToOne (optional = false, fetch = FetchType.EAGER) @JoinColumn(name = proj_lead_id, referencedColumnName = user_id) private User projectLead; @ManyToOne (optional = false, fetch = FetchType.EAGER) @JoinColumn(name = designer_id, referencedColumnName = user_id) private User designer; @Column (name = approve_by) private String approveBy; @Column (name = concept_date) private Date conceptDate; @Column (name = vendor_due_date) private Date vendorDueDate; @Column (name = release_date) private Date releaseDate; ... } @Entity(name = user) @Table(name = usr_user) public class User implements Serializable { private static final long serialVersionUID = 3L; @Id @Column (name = user_id) @GeneratedValue(strategy = GenerationType.IDENTITY) private long userId; @Column private String password; @Column (name = user_name, length = 20, nullable = false) private String userName; @Column (name = first_name, length = 32, nullable = false) private String firstName; @Column (name = last_name, length = 32, nullable = false) private String lastName; @Column (name = mid_name, length = 20, nullable = true) private String midName; @ManyToOne (optional = false, fetch = FetchType.EAGER) @JoinColumn(name = role_id, referencedColumnName = role_id) private Role role; ... } @Entity (name = role) @Table(name = role) public class Role { @Id @Column (name=role_id) @GeneratedValue(strategy = GenerationType.IDENTITY) private long roleId; @Column (name=role_name, length = 20, nullable = false) private String roleName; ... } and the exception details I got are javax.faces.FacesException: Error calling action method of component with id job-search-form:search-button at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:69) at javax.faces.component.UICommand.broadcast(UICommand.java:121) at javax.faces.component.UIViewRoot._broadcastForPhase(UIViewRoot.java:292) at javax.faces.component.UIViewRoot.process(UIViewRoot.java:209) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:117) at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32) at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103) at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:148) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:147) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at
Re: Bug in OpenJPA with cascade delete
Hi, My patch is for relationships annotated with foreign key on delete cascade. Can you provide a test case that fails for insert or update due to foreign key violation? -fay --- On Fri, 7/4/08, Beniamin Mazan [EMAIL PROTECTED] wrote: From: Beniamin Mazan [EMAIL PROTECTED] Subject: Re: Bug in OpenJPA with cascade delete To: users@openjpa.apache.org Date: Friday, July 4, 2008, 3:04 AM Sebastian Gauder wrote: Does this patch fix the whole SQL reordering problem, or does it just work for relationships annotated with Cascade? I still have problems à la insert or update on table customer violates foreign key constraint fk_address... Roger Keays schrieb: Roger Keays wrote: Sounds like issue 235, which I'm also stuck on: https://issues.apache.org/jira/browse/OPENJPA-235 Fay's patch posted to that issue fixed the problem for me. I've posted a binary at http://www.sunburnt.com.au/tmp/openjpa-1.1.0.jar You could try that version. I've just put 1.1.0 patch to my Geronimo 2.1 and it hasn't resolve my problem. The exception is still the same. - -- thanks Beniamin -- View this message in context: http://n2.nabble.com/Bug-in-OpenJPA-with-cascade-delete-tp219611p221034.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: Problem with foreign keys on DB and JPA delete
Hi, From the stack trace: ... org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flush(PreparedStatementManagerImpl.java:73) at org.apache.openjpa.jdbc.kernel.OperationOrderUpdateManager.flushPrimaryRow(OperationOrderUpdateManager.java:162) at org.apache.openjpa.jdbc.kernel.OperationOrderUpdateManager.flush(OperationOrderUpdateManager.java:89) ... it appears that you are using OperationOrderUpdateManager. My understanding is that for OperationOrderUpdateManager, application is responsible for the ordering of the delete operations. You might want to try ConstraintUpdateManager to see if it fixes your problem. -fay --- On Tue, 7/1/08, Beniamin Mazan [EMAIL PROTECTED] wrote: From: Beniamin Mazan [EMAIL PROTECTED] Subject: Problem with foreign keys on DB and JPA delete To: users@openjpa.apache.org Date: Tuesday, July 1, 2008, 5:01 PM I got foreign key on delete cascade constraint on my database for relation between Product and Subproduct CREATE TABLE product ( id character varying(36) PRIMARY KEY, ... ); CREATE TABLE voice_mail ( id character varying(36) PRIMARY KEY, flag_attribure boolean NOT NULL, . phone_id character varying(255) UNIQUE, FOREIGN KEY (phone_id) REFERENCES phone(id) ON UPDATE CASCADE ON DELETE CASCADE ); My Entities are in relation declared as: Within Product class @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = product) and within Subproduct class @OneToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER) @JoinColumn(name = product_id, unique = true, nullable = true) and persistence.xml properties properties property name=openjpa.Sequence value=class-table(Table=_SEQ_GENERATOR, UseAliases=true)/ property name=openjpa.jdbc.SynchronizeMappings value=buildSchema(SchemaAction=refresh) / property name=openjpa.jdbc.DBDictionary value=postgres/ property name=openjpa.Multithreaded value=true / property name=openjpa.TransactionMode value=managed / property name=openjpa.AutoDetach value=commit / property name=openjpa.RestoreState value=all / property name=openjpa.Optimistic value=true/ /properties 1. I got OptimistickLockException when I try to delete object of Product class. It tells that Subproduct was modified. 2. Using property name=openjpa.jdbc.SchemaFactory value=native(ForeignKeys=true)/ does not change anything 3. Using property name=openjpa.jdbc.MappingDefaults value=ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict/ changes stacktrace to: at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$CancelPreparedStatement.executeUpdate(JDBCStoreManager.java:1363) at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flushInternal(PreparedStatementManagerImpl.java:97) ... 72 more NestedThrowables: org.postgresql.util.PSQLException: ERROR: current transaction is aborted, commands ignored until end of transaction block at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:1548) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1316) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:191) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:452) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:351) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:305) at sun.reflect.GeneratedMethodAccessor597.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.postgresql.ds.jdbc23.AbstractJdbc23PooledConnection$StatementHandler.invoke(AbstractJdbc23PooledConnection.java:471) at $Proxy341.executeUpdate(Unknown Source) at org.tranql.connector.jdbc.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:103) at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:269) at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection$LoggingPreparedStatement.executeUpdate(LoggingConnectionDecorator.java:856) at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:269) at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:269) at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$CancelPreparedStatement.executeUpdate(JDBCStoreManager.java:1363) at
Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key
Hmmm. Here is my test case and it works fine. Four classes are listed: (1) TblPdtbnf0.java (2) TblPdtbnfId.java (3) TblScmpdt0.java (4) Test0.java You might still want to try it? :=)) -f (1) TblPdtbnf0.java package insert; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity @IdClass(TblPdtbnfId.class) public class TblPdtbnf0 { @Id @Column(name = PDTBNF_ID, nullable = false) private Integer pdtbnfId; @Id @Column(name = SCMPDT_ID, nullable = false) private Integer scmpdtId; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinColumn(name = XYZ_ID, referencedColumnName = SCMPDT_ID) private TblScmpdt0 tblScmpdt; public Integer getPdtbnfId() { return pdtbnfId; } public void setPdtbnfId(Integer pdtbnfId) { this.pdtbnfId = pdtbnfId; } public Integer getScmpdtId() { return scmpdtId; } public TblScmpdt0 getTblScmpdt() { return tblScmpdt; } public void setTblScmpdt(TblScmpdt0 tblScmpdt) { this.tblScmpdt = tblScmpdt; this.scmpdtId = tblScmpdt.getScmpdtId(); } } = (2)TblPdtbnfId.java package insert; import java.io.Serializable; public class TblPdtbnfId implements Serializable{ private Integer pdtbnfId; private Integer scmpdtId; public TblPdtbnfId(){} public TblPdtbnfId(Integer pdtbnfId, Integer scmpdtId) { this.pdtbnfId = pdtbnfId; this.scmpdtId = scmpdtId; } public Integer getScmpdtId() { return scmpdtId; } public Integer getPdtbnfId() { return pdtbnfId; } public boolean equals(Object o) { return (o instanceof TblPdtbnfId) pdtbnfId.intValue() == ((TblPdtbnfId)o).getPdtbnfId().intValue() scmpdtId.intValue() == ((TblPdtbnfId)o).getScmpdtId().intValue(); } public int hashCode() { int hc = 0; if (pdtbnfId != null) hc = hc + pdtbnfId.hashCode(); if (scmpdtId != null) hc = hc + scmpdtId.hashCode(); return hc; } } == (3)TblScmpdt0.java package insert; import java.util.ArrayList; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.TableGenerator; @Entity public class TblScmpdt0 { @TableGenerator(name=baseGenerator,schema=EBSTATUS,table=TBL_KEYGEN, pkColumnName=PRIMARY_KEY_COLUMN, valueColumnName=LAST_USED_ID, pkColumnValue=TBL_SCMPDT_ID,allocationSize=100) @Id @GeneratedValue(strategy=GenerationType.TABLE,generator=baseGenerator) @Column(name = SCMPDT_ID,nullable=false) private Integer scmpdtId; @OneToMany(fetch = FetchType.LAZY, mappedBy=tblScmpdt, cascade={CascadeType.MERGE,CascadeType.REMOVE, CascadeType.PERSIST}) private CollectionTblPdtbnf0 tblPdtbnfs = new ArrayListTblPdtbnf0(); private String admsysCde; private String fndCde; private String gccCde; public Collection getTblPdtbnfs() { return tblPdtbnfs; } public void setTblPdtbnfs(Collection tblPdtbnfs) { this.tblPdtbnfs = tblPdtbnfs; } public void addTblPdtbnf(TblPdtbnf0 tblPdtbnf) { tblPdtbnfs.add(tblPdtbnf); } public Integer getScmpdtId() { return scmpdtId; } public String getAdmsysCde() { return admsysCde; } public void setAdmsysCde(String admsysCde) { this.admsysCde = admsysCde; } public void setFndCde(String fndCde) { this.fndCde = fndCde; } public String getFndCde(){ return fndCde; } public void setGccCde(String gccCde){ this.gccCde = gccCde; } public String getGccCde() { return gccCde; } } (4) Test0.java: package insert; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Test0 { public static void main(String[] args) { try{
Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key
ok. I can reproduce your problem. Let me take a look. -f --- On Sat, 6/14/08, Enrico Goosen [EMAIL PROTECTED] wrote: From: Enrico Goosen [EMAIL PROTECTED] Subject: Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key To: users@openjpa.apache.org Date: Saturday, June 14, 2008, 5:46 AM Hi Fay, The primary key for TblScmpdt is database generated. Here's the mapping: @TableGenerator(name=baseGenerator,schema=EBSTATUS,table=TBL_KEYGEN,pkColumnName=PRIMARY_KEY_COLUMN ,valueColumnName=LAST_USED_ID,pkColumnValue=TBL_SCMPDT_ID,allocationSize=100) @Id @GeneratedValue(strategy=GenerationType.TABLE,generator=baseGenerator) @Column(name = SCMPDT_ID,nullable=false) private Integer scmpdtId; As I mentioned in my previous post, the code works (no exceptions), but its flawed because of the bug in JPA when performing a cascade persist on a OneToMany entity where the child (many) entity has a composite key. I should simply be able to do the following: TblScmpdt tblScmpdt = new TblScmpdt(); //new (non-persistent) parent entity //set fields on tblScmpdt ... TblPdtbnf tblPdtbnf = new TblPdtbnf(); //new (non-persistent) child entity //set fields on tblPdtbnf ... tblScmpdt.addTblpdtbnf(tblPdtbnf); //see method below, which sets the parent referrence on child //TblScmpdt method: public void addTblPdtbnf(TblPdtbnf tblPdtbnf) { tblPdtbnf.setTblScmpdt(this); //need to set both sides of bidirectional relationship getTblPdtbnfs().add(tblPdtbnf); } //Now I should be able to persist parent and cascade persist child automatically according to JPA docs tblScmpdt = em.merge(tblScmpdt); ...but unfortunately, the above doesn't work. I have to merge/persist the parent first then get the ID of the newly persisted parent and set it on the new child then add the child to the parent then merge the parent again. Tedious! Do you understand the problem? Regarding TblPdtbnfcde, this is a OneToOne reference on TblPdtbnf. TblPdtbnf's composite primary key is made up of TblPdtbnfcde.pdtbnfId and TblScmpdt.scmpdtId By the way, cascade persist works fine on my other OneToMany classes where there isn't a composite key. So this is definitely a bug. Enrico, What is the primary key field in the TblScmpdt entity? Did you set primary key for tblScmpdt before calling merge? I made an integer primary key field in TblScmpdt, and set the primary key to 1 in tblScmpdt before calling merge, and your test code works fine for me (I also omit TblPdtbnfcde in your test code for lack of detailed information). If you already set the primary key and still get the error, please specify more detail of your TblScmpdt class. -f -- View this message in context: http://www.nabble.com/%40OneToMany-%40ManyToOne%2C-Bidirectional%2C-Composite-Key-BUG-tp17801245p17839130.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key
Hi Ernico, The cause of the problem is not the composite primary key but the mapping of the primary key column and join column in the child table: (1) in the parent class TblScmpdt: the primary key: scmpdtId (the column: SCMPDT_ID) (2) in the child class the composite primary key: pdtbnfId (column: PDTBNF_ID) scmpdtId (column: SCMPDT_ID) the join column: SCMPDT_ID Please note that in this mapping, you have a primary key and the join value all mapped to the column SCMPDT_ID in the child table. In your test case: TblScmpdt tblScmpdt = new TblScmpdt(); (1) TblPdtbnf tblPdtbnf = new TblPdtbnf(); (2) TblScmpdt.addTblpdtbnf(tblPdtbnf); (3) Since you did not have the primary key set in the parent table (TblScmpdt ), openjpa will regard this entity as a new one, and perform persist() on it even though you call merge(). The problem is in the child entity. In statement (3), you establish the 1-many relationship between tblScmpdt and tblPdtbnf. The join value is therefore the primary key of tblScmpdt, which is automatically generated by openjpa via table generator. However, since you did not set the primary keys (pdtbnfId and scmpdtId, both are Integer class) for tblPdtbnf, they are null values (the default values). When both the null value of scmpdtId primary key and the non-null join value are set to column SCMPDT_ID, you got the following error message: Caused by: openjpa-1.0.0-r420667:568756 fatal user error org.apache.openjpa.persistence.InvalidStateException: Attempt to set column TBL_PDTBNF.SCMPDT_ID to two different values: (null)null, (class java.lang.Integer)700 This can occur when you fail to set both sides of a two-sided relation between objects, or when you map different fields to the same column, but you do not keep the values of these fields in synch. This scenario can not be distinguished from the following one which is obviously a user-error (note Statement (2.1)): TblScmpdt tblScmpdt = new TblScmpdt(); (1) TblPdtbnf tblPdtbnf = new TblPdtbnf(); (2) tblPdtbnf.setScmpdtId(null);(2.1) TblScmpdt.addTblpdtbnf(tblPdtbnf); (3) This problem can be fixed by not using the primary key column as the join column. Specifically, setting the join-column name to something other than SCMPDT_ID should solve this problem: @ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.MERGE) @JoinColumn(name = XX_ID,referencedColumnName=SCMPDT_ID) private TblScmpdt tblScmpdt; If you really want to use the primary key column as the join column, then don't let openjpa to automatically generate the primary key, so that you can explicitly set the primary keys of the child class the same as the join value. If you really want openjpa to automatically generate primary key, then you have to use the lousy way you described in your earlier email. Please let me know what you think. Thanks! -f --- On Sat, 6/14/08, Enrico Goosen [EMAIL PROTECTED] wrote: From: Enrico Goosen [EMAIL PROTECTED] Subject: Re: @OneToMany/@ManyToOne, Bidirectional, Composite Key To: users@openjpa.apache.org Date: Saturday, June 14, 2008, 5:46 AM Hi Fay, The primary key for TblScmpdt is database generated. Here's the mapping: @TableGenerator(name=baseGenerator,schema=EBSTATUS,table=TBL_KEYGEN,pkColumnName=PRIMARY_KEY_COLUMN ,valueColumnName=LAST_USED_ID,pkColumnValue=TBL_SCMPDT_ID,allocationSize=100) @Id @GeneratedValue(strategy=GenerationType.TABLE,generator=baseGenerator) @Column(name = SCMPDT_ID,nullable=false) private Integer scmpdtId; As I mentioned in my previous post, the code works (no exceptions), but its flawed because of the bug in JPA when performing a cascade persist on a OneToMany entity where the child (many) entity has a composite key. I should simply be able to do the following: TblScmpdt tblScmpdt = new TblScmpdt(); //new (non-persistent) parent entity //set fields on tblScmpdt ... TblPdtbnf tblPdtbnf = new TblPdtbnf(); //new (non-persistent) child entity //set fields on tblPdtbnf ... tblScmpdt.addTblpdtbnf(tblPdtbnf); //see method below, which sets the parent referrence on child //TblScmpdt method: public void addTblPdtbnf(TblPdtbnf tblPdtbnf) { tblPdtbnf.setTblScmpdt(this); //need to set both sides of bidirectional relationship getTblPdtbnfs().add(tblPdtbnf); } //Now I should be able to persist parent and cascade persist child automatically according to JPA docs tblScmpdt = em.merge(tblScmpdt); ...but unfortunately, the above doesn't work. I have to merge/persist the parent first then get the ID of the newly persisted parent and set it on the new child then add the child to the parent then merge the parent again. Tedious! Do you understand the problem? Regarding TblPdtbnfcde, this is a OneToOne reference on TblPdtbnf. TblPdtbnf's composite primary key is made up of TblPdtbnfcde.pdtbnfId and TblScmpdt.scmpdtId By the way, cascade persist works fine on
Re: How to PERSIST object without loading references?
Hi Enrico, Here is my example, and it runs fine: (1) EntityA.java: @Entity public class EntityA { @Column(name=A_ID) @Id private int id; private String name; @OneToOne(fetch = FetchType.LAZY) @JoinColumns([EMAIL PROTECTED](name=B_ID, referencedColumnName=B_ID, insertable=false,updatable=false)}) private EntityB entityB; ... omit getters and setters } (2) EntityB: @Entity public class EntityB { @Column(name=B_ID) @Id private int id; private String name; ... omit getters and setters } (3) the test case: em.getTransaction().begin(); EntityA a = new EntityA(); a.setName(1); a.setId(1); em.persist(a); em.getTransaction().commit(); Do you want to try my test case to see if it works? -f --- On Wed, 6/11/08, Enrico Goosen [EMAIL PROTECTED] wrote: From: Enrico Goosen [EMAIL PROTECTED] Subject: Re: How to PERSIST object without loading references? To: users@openjpa.apache.org Date: Wednesday, June 11, 2008, 11:44 AM I'm getting so frustrated with OpenJPA! I'm also experiencing the problem listed in previous reply, and once again, no response to that post. Here's some code to explain my problem: TblPdtbnf.java: @OneToOne(fetch = FetchType.LAZY) @JoinColumns([EMAIL PROTECTED](name =PDTBNF_ID,referencedColumnName=PDTBNF_ID,insertable=false,updatable=false)}) private TblPdtbnfcde tblPdtbnfcde; When I save a TblPdtbnf record, I get this error: ERRORJun 11 20:30:12 Encountered new object [EMAIL PROTECTED] in persistent field za.co.metcapri.model.ebstatus.TblPdtbnf.tblPdtbnfcde of managed object [EMAIL PROTECTED] during attach. However, this field does not allow cascade attach. You cannot attach a reference to a new object without cascading.; But I don't want to save the tblPdtbnfcde...didn't I make that clear by adding insertable=false!!! If I remove insertable=false, updatable=false...that doesn't help either. Do I have to set that field to null to save this record? There must be a better way. Is there anybody out there that knows the solution??? Anonimus wrote: Ognjen Blagojevic wrote: It must be a way to INSERT objects in the database without looking up for all the references, but I am not able to find it. My problem is similar as yours, with a single difference. I don't mind loading all the references because I need them in the program. But I don't know how to insert object and disable an attempt of inserting in related tables. If I put cascade = cascadeType.PERSIST, I get an exception (as you do). If I don't put cascade = cascadeType.PERSIST (which is logical), I get an exception. Since I'm new in JPA, I'm quite lost now. -- View this message in context: http://www.nabble.com/How-to-PERSIST-object-without-loading-references--tp16472647p17784459.html Sent from the OpenJPA Users mailing list archive at Nabble.com.
Re: ArgumentException
Hi Valentin, Did you enhance your entity class NavPoint before executing your query? --- On Thu, 5/29/08, Valentin BUERGEL [EMAIL PROTECTED] wrote: From: Valentin BUERGEL [EMAIL PROTECTED] Subject: ArgumentException To: users@openjpa.apache.org Date: Thursday, May 29, 2008, 6:54 AM Hi! I get a strange exception from time to time at start-up of my application. Sometimes the same code works without problem. What does the exception mean? I do not understand why NavPoint is not recognised as the error-message says that NavPoint is a known entity name? SCHWERWIEGEND [org.openide.util.RequestProcessor] openjpa-1.1.0-r422266:657916 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter SELECT x FROM NavPoint x WHERE x.typeNavPointType.SystemMountain AND x.typeNavPointType.SystemAirfield ORDER BY x.name. Error message: The name NavPoint is not a recognized entity or identifier. Perhaps you meant NavPoint, which is a close match. Known entity names: [NavPoint, NavPath] 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:1754) 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.datacache.QueryCacheStoreQuery.populateFromCompilation(QueryCacheStoreQuery.java:243) at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:657) at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:638) at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:604) at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:666) at org.apache.openjpa.kernel.QueryImpl.compile(QueryImpl.java:573) at org.apache.openjpa.persistence.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:892) at org.apache.openjpa.persistence.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:77) at ch.simtec.jpa.JpaBasicManager.createNamedQuery(JpaBasicManager.java:48) at ch.simtec.geo.server.DatabaseManager.fillAllUsr(DatabaseManager.java:47) at ch.simtec.geo.server.PointServer$3.run(PointServer.java:99) at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:561) at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:986) Thanks for any help, Valentin
RE: NPE at RelationToManyInverseKeyFieldStrategy when using mappedBy inverse
Hi Mike, Your super class EntityBase is annotated as @MappedSuperclass. Your Translatable class which inherits from EntityBase has inheritance strategy of TABLE_PER_CLASS. Since MappedSuperclass itself is not a persistence class and can not act in the capacity of an entity, it does not have a corresponding table in the database. I think this is why openjpa got confused and could not find foreign key between the parent class and the child class. When I removed Inheritance strategy annotation from Translatable class, your test case went through. Having said that, I think the NPE should be fixed and proper error message should be thrown. -Fay --- On Wed, 5/14/08, Michael Vorburger [EMAIL PROTECTED] wrote: From: Michael Vorburger [EMAIL PROTECTED] Subject: RE: NPE at RelationToManyInverseKeyFieldStrategy when using mappedBy inverse To: users@openjpa.apache.org, [EMAIL PROTECTED] Date: Wednesday, May 14, 2008, 2:55 AM https://issues.apache.org/jira/browse/OPENJPA-602 -Original Message- From: Michael Vorburger [mailto:[EMAIL PROTECTED] Sent: mercredi, 30. avril 2008 17:07 To: users@openjpa.apache.org; [EMAIL PROTECTED] Subject: NPE at RelationToManyInverseKeyFieldStrategy when using mappedBy inverse Hello, I'm running into an NPE in RelationToManyInverseKeyFieldStrategy (copy/pasted below) when using an OneToMany inverse relation with mappedBy and InheritanceType.TABLE_PER_CLASS in 1.1.0-SNAPSHOT... Test summary: A common abstract superclass Translatable which has a @OneToManySetTranslation, and many subclasses of that like e.g. a SomethingTranslatable, and many more. The idea is that mapping should lead to a Translation table holding the items for SomethingTranslatable and all other superclasses. Then SomethingTranslatable and many other tables (no physical Translatable table). There shouldn't be a join table for each SomethingTranslatable, as it's a OneToManySet, it doesn't make sense, so the owning side is a @ManyToOne in Translation back to Translatable. Granted a physical FK will not be possible in such a schema - accepted, but it should still be possible to map this? It works until I use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) on Translatable, with it - boum, NPE. I have a standalone example (test) demonstrating this that I can put into a JIRA if anybody wants to have a look (it doesn't make it through list, or spam filter). Work-around may be to use a an InheritanceType.JOINED on the Translatable, which avoids the NPE (tested); and which in this exaxmple only leads to a basically empty physical Translatable (but allows physical FK). In the real-world example this is based on though, where the Translatable has more attributes (e.g. a kind of shortDefaultTranslation and longDefaultTranslation), and the real SomethingTranslatable are more complex, this leads to a lot of joins across a table hiearchy which we'd like to avoid. Am I doing something wrong? Not possible? Bug? Open a JIRA? Thanks for any idea, hints, things to try, etc.! _ Michael Vorburger, Odyssey Financial Technologies ___ Exception in thread main java.lang.NullPointerException at org.apache.openjpa.jdbc.meta.strats.RelationToManyInverseKeyFieldStrateg y.map(RelationToManyInverseKeyFieldStrategy.java:136) at org.apache.openjpa.jdbc.meta.strats.RelationCollectionInverseKeyFieldStr ategy.map(RelationCollectionInverseKeyFieldStrategy.java:95) at org.apache.openjpa.jdbc.meta.FieldMapping.setStrategy(FieldMapping.java: 120) at org.apache.openjpa.jdbc.meta.RuntimeStrategyInstaller.installStrategy(Ru ntimeStrategyInstaller.java:80) at org.apache.openjpa.jdbc.meta.FieldMapping.resolveMapping(FieldMapping.ja va:438) at org.apache.openjpa.jdbc.meta.FieldMapping.resolve(FieldMapping.java:403) at org.apache.openjpa.jdbc.meta.ClassMapping.resolveMapping(ClassMapping.ja va:812) at org.apache.openjpa.meta.ClassMetaData.resolve(ClassMetaData.java:1626) at org.apache.openjpa.meta.MetaDataRepository.processBuffer(MetaDataReposit ory.java:717) at org.apache.openjpa.meta.MetaDataRepository.resolveMapping(MetaDataReposi tory.java:677) at org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.ja va:555) at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepositor y.java:308) at org.apache.openjpa.jdbc.meta.MappingRepository.getMapping(MappingReposit ory.java:284) at org.apache.openjpa.jdbc.meta.MappingTool.getMapping(MappingTool.java:676 ) at org.apache.openjpa.jdbc.meta.MappingTool.buildSchema(MappingTool.java:74 8) at org.apache.openjpa.jdbc.meta.MappingTool.run(MappingTool.java:646) at org.apache.openjpa.jdbc.meta.MappingTool.run(MappingTool.java:1072) at org.apache.openjpa.jdbc.meta.MappingTool.run(MappingTool.java:986) at atest.CreateDBTest.synchronizeDatabase(CreateDBTest.java:70) at