EclipseLink - oneToMany in lazy + join fetch

Hi,
I have a little problem with use a "join fetch".
How use join fetch with @OneToMany lazy relations ?
I have two objetcs : Object A has a list of objects B.
A
@oneToMany (Lazy relation)
List<B> listB
Now, I want load these 2 objects.
I write a jpql like "select a from A a left join fetch a.listB where a.id=?"
The sql generated is fine, I see the join between table A and B.
BUT, when I try to access listB (outside session), I have a lazy exception.
Why ?
If (inside session) I access to listB, it's ok (with no more sql).
So, I have wrote a method like that :
public A findA(lond id){
Query q = createQuery(select a from A a left join fetch a.listB where a.id=id");
A = q.getSingleResult();
A.getListB().size() -> to initialize relation (but non sql generated)
return A;
Someone has an idea ?
Thanks for your responses.

Hi,
In fact my method findA... is inside a stateless bean.
Outside session means that I call my method by a client application like that :
Service service= (Service )context.lookup("xxxxx");
A = service.findA();
A.getListB().size;
Exception is
Exception [EclipseLink-7242] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: An attempt was made to traverse a relationship using indirection that had a null Session. This often occurs when an entity with an uninstantiated LAZY relationship is serialized and that lazy relationship is traversed after serialization. To avoid this issue, instantiate the LAZY relationship prior to serialization.
For the version of eclipseLink, it's an ejb deployed on embedded weblogic with jdeveloper Studio Edition Version 11.1.1.3.0.
It's JPA 1.0.
Thanks for your response.
Hope this help.
Nicolas
Edited by: 865770 on 15-juin-2011 8:12

Similar Messages

  • JPQL LEFT JOIN FETCH Results in NPE when DescriptorCustomizer in Place

    I have a unidirectional one-to-many mapping between the following two entities:
    @Entity
    @Table(name="INVC_CNTRL")
    public class InvoiceControl implements Serializable {
        @Id
        @Column(name="INVC_CNTRL_ID")
        private Long invoiceControlId = null;
        @OneToMany(fetch = FetchType.LAZY)
        private List userDefineds;
    @Entity
    @Table(name="USER_DEFINED")
    public class UserDefined implements Serializable {
        @Column(name="USER_DEFINED_TABLE")
        private java.lang.String userDefinedTable;
        @Column(name="USER_DEFINED_FK")
        private long userDefinedForeignKey;
    I wrote the following DescriptorCustomizer to address a constant JoinColumn value:
            ManyToManyMapping mapping = (ManyToManyMapping) descriptor.getMappingForAttributeName("userDefineds");
            if (null != mapping) {
                String tableName = descriptor.getTableName();
                String primaryKey = descriptor.getPrimaryKeyFields().get(0).getName();
                ExpressionBuilder builder = new ExpressionBuilder(mapping.getReferenceClass());
                mapping.setSelectionCriteria(builder.getField("USER_DEFINED_FK").equal(builder.getParameter(primaryKey))
                    .and(builder.getField("USER_DEFINED_TABLE").equal(tableName)));
    This works as expected with JPQL "select a from InvoiceControl a join fetch a.userDefineds" but when I change the "join fetch" to "left join fetch", I get the following NPE:
    Caused by: java.lang.NullPointerException
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.appendFromClauseForOuterJoin(SQLSelectStatement.java:403)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.appendFromClauseToWriter(SQLSelectStatement.java:521)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.printSQL(SQLSelectStatement.java:1679)
         at org.eclipse.persistence.internal.databaseaccess.DatabasePlatform.printSQLSelectStatement(DatabasePlatform.java:3178)
         at org.eclipse.persistence.platform.database.OraclePlatform.printSQLSelectStatement(OraclePlatform.java:932)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.buildCall(SQLSelectStatement.java:782)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.buildCall(SQLSelectStatement.java:792)
         at org.eclipse.persistence.descriptors.ClassDescriptor.buildCallFromStatement(ClassDescriptor.java:813)
         at org.eclipse.persistence.internal.queries.StatementQueryMechanism.setCallFromStatement(StatementQueryMechanism.java:390)
         at org.eclipse.persistence.internal.queries.StatementQueryMechanism.prepareSelectAllRows(StatementQueryMechanism.java:315)
         at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareSelectAllRows(ExpressionQueryMechanism.java:1721)
         at org.eclipse.persistence.queries.ReadAllQuery.prepareSelectAllRows(ReadAllQuery.java:813)
         at org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:744)
         at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:661)
         ... 8 more
    Inspecting the 2.5.1 source, this suggests relationAlias is null.
    I've tried a number of things to no avail. If I disable the DescriptorCustomizor and instead add a @JoinColumn on the OneToMany defining half of the join, it works. Of course the result is incorrect because it's failing to discriminate by the table name.
    Is this a bug or am I making another JPA noob mistake?
    Thanks.

    I was able to get similar behaviour doing similar JPQL. I have entered a bug in TopLink Essentials. 2465.
    I did note that having the objects in memory made a significant difference (< .5 seconds for 1000 objects, each with 2 in the 1:M).

  • EclipseLink Direct Map with Joining mapping issue

    Hi EclipseLink Team,
    We encountered an issue to map an attribute as Direct Map with Join Fetch enabled in EclipseLink Workbench 1.1.1 (Build v20090430-r4097).
    Basically, we have the following data model:
    SESSION
    SESS_NO (PK),
    PARAM_SESS
    SESS_NO (FK) (PK),
    PARAM_NAME (PK),
    PARAM_VALUE
    Then we have Session.java persistent entity associated with SESSION table. This class contains Map attribute sessionParameters which we map as Direct Map with PARAM_SESS.PARAM_NAME as key and PARAM_SESS.PARAM_VALUE as value (referenced by PARAM_SESS.SESS_NO = SESSION.SESS_NO).
    The described mapping works fine without Joining enabled (both for Lazy and Eager Loading).
    But we have cases when we want to get parameters for a number of sessions. And disabling of Joining leads to a number of performed SELECT SQL queries (both for Lazy and Eager Loading) those are bad for performance.
    So we have chosen the Eager Loading and set the Join Fetch option to Outer. Then we have got the following:
    I see in the log the only SQL query performed: SELECT DISTINCT t0.SESS_NO, …, t1.PARAM_VALUE, t1.PARAM_NAME FROM {oj SESSION t0 LEFT OUTER JOIN PARAM_SESS t1 ON (t1.SESS_NO = t0.SESS_NO)}. This is pretty good for us. This query returns exactly what we expect when executing on the database. But the Map attribute for every session is populated incorrectly: Maps are empty (not corresponding to available relational data).
    Could you please let us know if this is a bug, or kind of known issue or we made something wrong? Some hints and proposals would be very helpful and appreciated.
    I should mention that for now we want to map all of this for read only purpose.
    Thanks.
    Best Regards,
    Alexey Elisawetski

    James,
    I've tried both 1.2 release and 2.0 (v20091121-r5847) but received the same result - empty Map.
    Moreover, for both versions the following string was absent in deployed XML file:
    +<direct-key-field table="PARAM_SESS" name="PARAM_NAME" xsi:type="column"/>+
    Therefore, on application initialization I have got an exception: org.eclipse.persistence.exceptions.DescriptorException with message This descriptor contains a mapping with a DirectMapMapping and no key field set.
    So I was forced to add the line manually.
    This seems buggy to me...
    Regards,
    Alexey

  • EJB Issue with return empty children in join fetch query

    I'm a newbie and still trying to learn all of the facets of EJB 3.0 (and other backend capabilities) however could not find this issue anywhere resolved.
    I have a recursive table which has a 0,1-n relationship with itself. In this case, I want to query for all objects and fetch the resulting children.
    To do this I have written the following query:
    select o from Node o inner join fetch o.childrenNodeList order by o.nodeorder
    If my database has the following entries:
    Parent
    Child
    Grandchild
    The above query will get all 3 and allow me to access the list of children through getChildrenNodeList, however, for Grandchild this returns "An attempt was made to traverse a relationship using indirection that had a null Session...." for Parent and Child however it works like it should and gets the fetched rows.
    Is there a way for me to either:
    1. Modify the query so that the getChildrenNodeList will return a 0 sized array (so I can test for no children)
    2. Modify the getter such that I can check that the parent really has no children and not some issue with the query
    Thanks for any help,
    Kris

    fixed

  • JPA OnetoMany  QUERY LEFT JOIN BUG

    Using JPA in JDev 10.1.3.1.0.3984
    Database: Firebird 1.51LI-V1.5.3.4870 Firebird 1.5/tcp
    Driver: Jaybird JCA/JDBC driver Version: 2.1
    TopLink, version: Oracle TopLink Essentials - 2006.8 (Build 060829)
    If I use normal JOIN it works.
    On LEFT JOIN I get a {oj [/b] before the table name and a [b]} at the end.
    public class Cliente{
        @OneToMany(mappedBy = "cliente")
        @JoinColumn(name = "CDCLIENTE", referencedColumnName = "CDCLIENTEREQUISITANTE")
        private List<Requisicao> requisicoes;
    public class Requisicao
        @ManyToOne
        @JoinColumn(name = "CDCLIENTEREQUISITANTE", referencedColumnName = "CDCLIENTE")
        private Cliente cliente;
    EntityManager em = getEntityManager();
    String sql = "SELECT c FROM Cliente c LEFT JOIN c.requisicoes req";
    Query q = em.createQuery(sql);
    List rs = q.getResultList();Result SQL:
    SELECT DISTINCT t0. <OMITTED> FROM {oj [/b]CLIENTE t0 LEFT OUTER JOIN REQUISICAO t1 ON (t1.CDCLIENTEREQUISITANTE = t0.CDCLIENTE)[b]}

    You cannot define an ON clause with Criteria, nor JPQL.
    Perhaps you can reword the query to avoid needing an ON clause.
    What is the query you want to do (in english)?
    Can you just use an OR in the where clause?
    There is a enhancement request to have ON clause support added, please vote for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
    James : http://www.eclipselink.org

  • JPQL: FETCH and navigate through a @OneToMany relationship at the same time

    Hello!
    I have three entities A-->B-->C, where the arrows denote @OneToMany relationships. I would like to form a query that returns A objects and prefetches all associated B and C objects. Is this achievable in JPQL?
    My failed attempts were (I'm using EclipseLink):
    1.
    SELECT a FROM A a LEFT JOIN FETCH a.b LEFT JOIN FETCH a.b.c WHERE condition;
    This fails with an error: "cannot navigate collection valued association field "
    2.
    SELECT a FROM A a LEFT JOIN FETCH a.b AS b LEFT JOIN FETCH b.c WHERE condition;
    This fails with "syntax error at [AS]"
    3.
    SELECT a FROM A a LEFT JOIN FETCH a.b LEFT JOIN a.b AS b LEFT JOIN FETCH b.c WHERE condition;
    This query succeeds, but does not prefetch the C objects.

    OK, the answer is negative - it is not supported in JPQL.
    But it should be achievable with EclipseLink-specific @QueryHint LEFT_FETCH
    http://www.eclipse.org/eclipselink/api/1.1/org/eclipse/persistence/config/QueryHints.html#LEFT_FETCH
    Unfortunately I get an exception when I use those hints, but that is probably an EclipseLink problem.
    java.lang.IllegalArgumentException: fromIndex(18) > toIndex(12)
         at org.eclipse.persistence.internal.helper.NonSynchronizedSubVector.<init>(NonSynchronizedSubVector.java:32)
         at org.eclipse.persistence.mappings.ForeignReferenceMapping.trimRowForJoin(ForeignReferenceMapping.java:1685)
         at org.eclipse.persistence.mappings.ForeignReferenceMapping.trimRowForJoin(ForeignReferenceMapping.java:1657)
         at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternalWithJoin(OneToOneMapping.java:1523)
         at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1532)
         ...

  • Fetch join with Native SQL Query?

    Hello all,
    I am using the J2EE 5.0 persistence api with the SUN appserver v9. As the java persistence api does not yet support spatial queries ("... where contains(polygon, point)") I have to use native SQL queries for that purpose.
    Now my question is how can I "join fetch" my ManyToOne-related entities when using a native SQL query? Is this somehow possible using the SqlResultSetMapping annotation?

    Never mind - the problem was to do with not specifying a class when creating the native query.

  • Lazy loading, EntityManager and concurrency.

    I need advice which strategy to use with lazy loading.
    My project is based on Spring, Struts 2 and Hibernate JPA. I have enough OneToMany and ManyToMany relationships and it's reasonable to use lazy loading. It seems very convenient to load data in Struts Actions with OpenEntityManagerInViewFilter in such way like:
    Style style = user.getStyle()
    But to avoid LazyLoadException I have to use:
    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    Unfortunately, EntityManager in this case becomes not thread-safe, according to Spring docs: "+Extended EntityManagers are not thread-safe, hence they must not be used in concurrently accessed beans (which Spring-managed singletons usually are).+" EXTENDED means that EntityManager is shared in user session and my EntityManager is injected in singleton services.
    I've found this issue when tried to make quick sequential page reloading which call some selects and got:
    java.sql.SQLException: You can't operate on a closed Statement!!!
    What's the best practice in this situation:
    1. Try synchronize session access to EntityManager by myself or put each user database requests in separate queue (something terrible I suppose).
    2. Use HQL queries with join fetch to preload data for access outside of transaction (maybe overhead).
    3. Or something else???
    And why we need EXTENDED context if it's so unreliable??
    Thanks for help!

    Hi
    Do you have the link to the "lazy loading content"?
    I can't find a proper way to do it.
    Thanks

  • How do I join with native SQL?

    I'm just starting to dip my toes in Toplink/Eclipselink using jDeveloper 11g. I've got a database schema that looks like this:
    Organization > Site > Program / MhProgram
    Every program and MhProgram has a site_id, and every site has an organization_id.
    The POJO objects wizards seems to have set the relationships up correctly and I'm able to pull out Organization objects that have siteCollections and the sites have programCollections and MhProgramCollections. The part where I'm having trouble is pulling out organizations the way I'd like to.
    I'm querying them with this SQL:
    select o.*
    from organization o,
    site s,
    program p
    where o.organization_id = s.organization_id
    and s.site_id = p.site_id
    and s.site_number = 1
    and p.program_name = "Test Name"
    The problem seems to be that Toplink isn't actually recognizing that I want to do these joins. Its grabbing an organization and then doing SQL to separately get each site, then each program. During this process SQL like s.site_number = 1 is ignored. This leaves me with siteCollections and programCollections that are just raw unfiltered rows. I've tried the same with JPQL and I'm having no luck there either.
    Am I missing something with the Native SQL support?
    Edited by: user519677 on May 5, 2009 5:32 AM

    The code is below. Its just a test client until I can get it working. When I put the word FETCH beside the INNER JOIN in the JPQL I get the following exception:
    Exception Description: Syntax error parsing the query [select o from Organization o INNER JOIN FETCH o.siteCollection s where s.siteNumber = 1 ], line 1, column 63: syntax error at [s].
    Internal Exception: MismatchedTokenException(66!=-1)
    Code:
    Project project = XMLProjectReader.read("META-INF/tlMap.xml", Thread.currentThread().getContextClassLoader());
    DatabaseSession session = project.createDatabaseSession();
    session.shouldLogMessages();
    session.login();
    session.setLogLevel(org.eclipse.persistence.logging.SessionLog.FINE);
    ReadAllQuery query = new ReadAllQuery(Organization.class);
    String EJBQuery = "select o from Organization o " +
    "INNER JOIN o.siteCollection s " +
    "where s.siteNumber = 1 ";
    query.setEJBQLString(EJBQuery);
    Collection<Organization> results = (Collection<Organization>) session.executeQuery(query);
    Edited by: user519677 on May 5, 2009 6:31 AM

  • EJBQL joining entity problem

    Dear all,
    I have written the following EJBQL:
    select o from Commitment o join o.invoiceStat i where o.companyCode = 'HKC' and o.item = 'ABCD01' and i.year = 2008
    The entity class is as follows:
    public class Commitment implements Serializable {
    @Column(name="commitment_amt",nullable = false)
    private Double commitmentAmt;
    @Id
    @Column(name="item_code",nullable = false)
    private String item;
    @Id
    @Column(name="institution_code",nullable = false)
    private String companyCode;
    @OneToMany(mappedBy = "commitment")
    private List<InvoiceStatistic> invoiceStat;
    I join the invoiceStat in the EJBQL and also I need to filter, ie. i.year = 2008,
    but maybe because of invoiceStat is a OneToMany List Object, the EJBQL didn't filter using i.year=2008.
    How could I filter the OneToMany ? Please help
    Thanks.

    from Commitment c
    left join fetch c.invoiceStat s
    where s.year = 2008
    something like that?

  • OneToMany relation over composite PK query error

    We have two classes with composite PK's on both sides. The classes are related via OneToMany relation (and ManyToOne vice versa). The mapping basically works, but if a simple query is issued like
    "select stp from Teilstp stp"
    we get the strange error message "Exception Description: The parameter name [tstnr2] in the query's selection criteria does not match any parameter name defined in the query." Query: ReadAllQuery(lager.model.Teillgp)
    As there are no parameters defined in the query above, this seems to be some kind of internal TopLink JPA error.
    We are unsure whether our mapping is the problem or if the error could be caused by a TopLink JPA bug? Please have a look at the code snippets below and verify the mappings!
    regards,
    Hans
    @IdClass(TeilstpPK.class)
    @Entity
    @Table(name = "teilstp", schema = "jws")
    public class Teilstp {
         @Id
         private String tstnr1;
         @Id
         private String tstnr2;
         @Id
         private String tstnr3;
         @Id
         private String tstnr4;
         @Id
         private String tstnr5;
         @Basic
         @Column(name = "tsmeh")
         private String tsmeh;
         @Basic
         @Column(name = "tsdekp")
         private Double tsdekp;
         @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy="stp")
         private Set<Teillgp> lgps;
    @IdClass(TeillgpPK.class)
    @Entity
    @Table(schema = "jws")
    public class Teillgp {
         @Id
         private String tltnr1;
         @Id
         private String tltnr2;
         @Id
         private String tltnr3;
         @Id
         private String tltnr4;
         @Id
         private String tltnr5;
         @Id
         private Long tllgnr;
         @Basic
         private Double tllgbs;
         @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
         @JoinColumns( {
                   @JoinColumn(name = "tltnr1", referencedColumnName = "tstnr1"),
                   @JoinColumn(name = "tltnr2", referencedColumnName = "tstnr2"),
                   @JoinColumn(name = "tltnr3", referencedColumnName = "tstnr3"),
                   @JoinColumn(name = "tltnr4", referencedColumnName = "tstnr4"),
                   @JoinColumn(name = "tltnr5", referencedColumnName = "tstnr5") })
         private Teilstp stp;
    The PrimaryKey @IdClasses are just plain pojo's with hashCode and equals implemented.
    Invoking Teilstp.getLgps() fails with:
    [TopLink Warning]: 2007.06.11 03:48:50.640--ServerSession(11582167)--Exception [TOPLINK-6094] (Oracle TopLink Essentials - 2.0 (Build b38-rc (03/07/2007))): oracle.toplink.essentials.exceptions.QueryException
    Exception Description: The parameter name [tstnr2] in the query's selection criteria does not match any parameter name defined in the query.
    Query: ReadAllQuery(lager.model.Teillgp)
    Any ideas?

    I have this same error, except mine occurs when I make use of the @OneToMany Set.
    This problem seems to be related to connecting Entity Relationships (Specifically ManyToOne) to Id fields.
    (And I have the most recent version as of June 2007)
    (Also, I know this post is five years old, but it was the sole result on Google)
    I bet your stack trace looks somewhat like this:
         oracle.toplink.essentials.exceptions.QueryException.parameterNameMismatch(QueryException.java:983)
         oracle.toplink.essentials.internal.expressions.ParameterExpression.getValue(ParameterExpression.java:231)
         oracle.toplink.essentials.internal.databaseaccess.DatabaseCall.translate(DatabaseCall.java:837)
         oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
         oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:215)
         oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:286)
         oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:616)
         oracle.toplink.essentials.internal.queryframework.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2417)
         oracle.toplink.essentials.internal.queryframework.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2395)
         oracle.toplink.essentials.queryframework.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:339)
         oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:725)
         oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:629)
         oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:693)
         oracle.toplink.essentials.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:1831)
         oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:953)
         oracle.toplink.essentials.internal.indirection.QueryBasedValueHolder.instantiate(QueryBasedValueHolder.java:102)
         oracle.toplink.essentials.internal.indirection.QueryBasedValueHolder.instantiate(QueryBasedValueHolder.java:92)
         oracle.toplink.essentials.internal.indirection.DatabaseValueHolder.getValue(DatabaseValueHolder.java:106)
         oracle.toplink.essentials.internal.indirection.UnitOfWorkValueHolder.instantiateImpl(UnitOfWorkValueHolder.java:176)
         oracle.toplink.essentials.internal.indirection.UnitOfWorkValueHolder.instantiate(UnitOfWorkValueHolder.java:248)
         oracle.toplink.essentials.internal.indirection.DatabaseValueHolder.getValue(DatabaseValueHolder.java:106)
         oracle.toplink.essentials.indirection.IndirectSet.buildDelegate(IndirectSet.java:194)
         oracle.toplink.essentials.indirection.IndirectSet.getDelegate(IndirectSet.java:309)
         oracle.toplink.essentials.indirection.IndirectSet$1.<init>(IndirectSet.java:360)
         oracle.toplink.essentials.indirection.IndirectSet.iterator(IndirectSet.java:359)

  • One To One Batch fetching on the non-owning side

    Hi there
    we are using EclipseLink on a ejb applicatiion and we are going into prod in 3 weeks.
    This is the situation: we have a table on which we are not making inserts, updates or deletes (this is a "deal" we have with the integration team) . We should any updates to this entity in separate tables (application tables).
    In this case, the entity UnitAvail has a @OneToOne relationship with UniAvailApp. Beign UnitAvailApp the owning side of the @OneToOne relationship. At database level, the primary key of UnitAvailApp is a foreign key to UnitAvail.
    Something I noticed is that as EclipseLink (or JPA) is not eable to set Foreign Keys as Primary Keys, the workaorund in the IDE´s reverse engineering is to let UnitAvailApp have an @Id of type BigDecimal and a @OneToOne to UnitAvail (non-updatable, non-inseratable, non-nullable), both the @Id and the @OneToOne refering to the same db column.
    We can not assume that for each UnitAvail there is going to be a UnitAvailApp. As there will only be created if needed.
    There are 20.000 UnitAvail´s and I wan´t to retrieve eagerly all the related UnitAvailApp for those who have it (5.000 at the moment).
    If I do Select ua From UnitAvail ua EclipseLink will write a SELECT query to UnitAvailApp table for each UnitAvail entity, i.e. 20.000 select queries. (waiting for the orm is as ridiculous as looking at the eclipselink logs)
    If I set the hint "eclipselink.fetch-join" "ua.unitAvailApp" I will not retrieve all the entities of UnitAvail, but just those which have a UnitAvailApp, i.e. 5.000
    If I set the hint "eclipselink.batch" "ua.unitAvailApp" It simply doesnt happen ( i believe this is because UnitAvail is not the owning side of the relationship)
    If we could have left-fetch-join, this would solve our problem
    The database (integration) team have done the database schema, and from there we reverse engineer the tables with the IDE in order to get our Entity Classes. As I am sure you can understand, the database team is not very keen to redesign the database schema according to ORM necessities or "holes". As there will be further applications that are going to access this same database (not necessary JAVA apps and not necessary ORM).
    So, Is there a way that EclipseLink can retrieve both UnitAvail and their corresponding UnitAvailApp (for those having one) in batch or using a left join whithout thousands of select clauses? Is there a way to tell EclipseLink to do all persistence fetching in batch?? (I believe you can do this with Hibernate)
    These are the two entities.
    @Entity
    @Table(name = "UNIT_AVAIL", uniqueConstraints = {@UniqueConstraint(columnNames = {"UNIT_AVAIL_KEY"})})
    public class UnitAvail implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "UNIT_AVAIL_ID", nullable = false, precision = 22)
    private BigDecimal unitAvailId;
    @Basic(optional = false)
    @Column(name = "UNIT_AVAIL_KEY", nullable = false)
    private int unitAvailKey;
    @Basic(optional = false)
    @Column(name = "START_DATE", nullable = false)
    @Temporal(TemporalType.DATE)
    private Date startDate;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "unitAvail")
    private UnitAvailApp unitAvailApp;
    @Entity
    @Table(name = "UNIT_AVAIL_APP")
    public class UnitAvailApp implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "UNIT_AVAIL_ID", nullable = false, precision = 22)
    private BigDecimal unitAvailId;
    @JoinColumn(name = "UNIT_AVAIL_ID", referencedColumnName = "UNIT_AVAIL_ID", nullable = false, insertable = false, updatable = false)
    @OneToOne(optional = false)
    private UnitAvail unitAvail;
    @Column(name = "CAF_CONCUR_FLAG", length = 1)
    private String cafConcurFlag;
    @Column(name = "COMB_UNIT_CO_ALLOC_FLAG", length = 1)
    private String combUnitCoAllocFlag;
    @Column(name = "AVAIL_REC_ALLOC_FLAG", length = 1)
    private String availRecAllocFlag;
    Thank you in advance,
    Pablo.
    Edited by: user8813560 on Oct 11, 2009 12:06 AM
    Edited by: user8813560 on 11/10/2009 18:46

    Batch reading the relationship should work. You should get one query for the source objects and one query for all of the source objects related objects. Perhaps include your query and SQL.
    Also what version are you using?
    You can also use join-fetch, JPQL only allows join-fetch to one level (although JPA 2.0/EclipseLink 1.2 may support this). You can use the EclipseLink hint, "eclipselink.left-join-fetch" to join multiple levels (added in EL 1.1 I think).
    James : http://www.eclipselink.org : http://en.wikibooks.org/wiki/Java_Persistence

  • Can't Persist Child of @OneToMany

    Have parent Entity that can be persisted just fine.
    However, when I attach children to it that have been declared as OneToMany I get an exception. I've never had a problem with this issue before, have plenty of related tables that work just fine.
    I can query what's there just fine so I know the relationship works.
    If it matters, all this is being done with remote static bean facades.
    Help would be appreciated.
    snippet:
    @Entity
    @SequenceGenerator(name = "alm_sequence", sequenceName = "alm_seq")
    @Table( name = "ALM", schema = "MCMPGE", uniqueConstraints = {})
    public class Alm implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
         public Long almPk;
         public Set<AlmRecord> almRecords = new HashSet<AlmRecord>( 0);
    @OneToMany( cascade = { CascadeType.ALL}, fetch = FetchType.LAZY, mappedBy = "alm")
         public Set<AlmRecord> getAlmRecords() {
              return this.almRecords;
         public void setAlmRecords( Set<AlmRecord> almRecords) {
              this.almRecords = almRecords;
    @Entity
    @SequenceGenerator(name = "alm_record_sequence", sequenceName = "alm_record_seq")
    @Table( name = "ALM_RECORD", schema = "MCMPGE", uniqueConstraints = {})
    public class AlmRecord implements java.io.Serializable {
         private static final long serialVersionUID = 1L;
         public Long almRecordPk;
         public Alm alm;
         @ManyToOne( cascade = {}, fetch = FetchType.LAZY)
         @JoinColumn( name = "ALM_FK", unique = false, nullable = true, insertable = true, updatable = true)
         public Alm getAlm() {
              return this.alm;
         public void setAlm( Alm alm) {
              this.alm = alm;
    Exception:
    May 15, 2008 2:04:41 PM oracle.j2ee.rmi.RMIMessages EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER
    WARNING: Exception returned by remote server: {0}
    javax.ejb.EJBException: Exception [TOPLINK-99] (Oracle TopLink Essentials - 2.0 (Build b41-beta2 (03/30/2007))): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: The method [_toplink_getalm_vh] on the object [com.navsys.dal.AlmRecord] triggered an exception.
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.NullPointerException
    Mapping: oracle.toplink.essentials.mappings.OneToOneMapping[alm]
    Descriptor: RelationalDescriptor(com.navsys.dal.AlmRecord --> [DatabaseTable(MCMPGE.ALM_RECORD)]); nested exception is:
         Exception [TOPLINK-99] (Oracle TopLink Essentials - 2.0 (Build b41-beta2 (03/30/2007))): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: The method [_toplink_getalm_vh] on the object [com.navsys.dal.AlmRecord] triggered an exception.
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.NullPointerException
    Mapping: oracle.toplink.essentials.mappings.OneToOneMapping[alm]
    Descriptor: RelationalDescriptor(com.navsys.dal.AlmRecord --> [DatabaseTable(MCMPGE.ALM_RECORD)]); nested exception is: oracle.oc4j.rmi.OracleRemoteException: Exception [TOPLINK-99] (Oracle TopLink Essentials - 2.0 (Build b41-beta2 (03/30/2007))): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: The method [_toplink_getalm_vh] on the object [com.navsys.dal.AlmRecord] triggered an exception.
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.NullPointerException
    Mapping: oracle.toplink.essentials.mappings.OneToOneMapping[alm]
    Descriptor: RelationalDescriptor(com.navsys.dal.AlmRecord --> [DatabaseTable(MCMPGE.ALM_RECORD)]); nested exception is:
         Exception [TOPLINK-99] (Oracle TopLink Essentials - 2.0 (Build b41-beta2 (03/30/2007))): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: The method [_toplink_getalm_vh] on the object [com.navsys.dal.AlmRecord] triggered an exception.
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.NullPointerException
    oracle.oc4j.rmi.OracleRemoteException: Exception [TOPLINK-99] (Oracle TopLink Essentials - 2.0 (Build b41-beta2 (03/30/2007))): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: The method [_toplink_getalm_vh] on the object [com.navsys.dal.AlmRecord] triggered an exception.
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.NullPointerException
    Mapping: oracle.toplink.essentials.mappings.OneToOneMapping[alm]
    Descriptor: RelationalDescriptor(com.navsys.dal.AlmRecord --> [DatabaseTable(MCMPGE.ALM_RECORD)])
         at com.evermind.server.ejb.EJBUtils.getUserException(EJBUtils.java:346)
         at com.evermind.server.ejb.interceptor.system.AbstractTxInterceptor.convertAndHandleMethodException(AbstractTxInterceptor.java:75)
         at com.evermind.server.ejb.interceptor.system.TxRequiredInterceptor.invoke(TxRequiredInterceptor.java:52)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
         at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
         at com.evermind.server.ejb.InvocationContextPool.invoke(InvocationContextPool.java:55)
         at com.evermind.server.ejb.StatelessSessionEJBObject.OC4J_invokeMethod(StatelessSessionEJBObject.java:87)
         at AlmFacade_RemoteProxy_5jopb7j.update(Unknown Source)
         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 com.evermind.server.rmi.RmiMethodCall.run(RmiMethodCall.java:53)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:595)

    There was a bug for a particular case when the weaved valueholder was not present, and I don't recall exactly what it was, but you might start by upgrading to the latest essentials build to make sure you are not hitting that one case. If you are still encountering the same problem then we can find out more about what you are doing differently that causes this to happen, and if it has to do with the serialization of the entity.

  • JPA - Lazy Initialisation

    Hi All,
    I hope this isn't a repeat question. I have looked, and google'd, this question for sometime. I am just looking for guidance on the best approach.
    The Problem:
    I have an entity which has 2 Collections which represent a Many-to-Many relationship with 2 other entities. Now I have them both set to be lazily fetched, as I don't require that information all the time.
    Question:
    However in the instances I do want that information, what is the best approach to get them loaded. ?
    From Research:
    I have seen various ways of getting these collections loaded, one being the "EntityManager in View" design pattern, but with my beliefs leaning toward the pure computer science side, it just doesn't feel right. Another is to have a facade that calls on those collections, forcing Hibernate to populate them.
    E.g.
    @Transactional
    public MyEntity getMyEntity(Long id) {
       // Call to underlying service method
       MyEntity rtn = service.getMyEntity(id);
       // Force Hibernate to load the collections
       rtn.getCollection1().size();
       rtn.getCollection2().size();
       return rtn;
    }Again, I don't feel comfortable with this. Maybe I am being overly pure and missing something glaringly obvious, this may not even be a problem at all and I have over-complicated things.
    Would be great if someone else offered their insight into this problem.
    Kind Regards to All
    Cookie

    I'm not exactly sure because I tend to just trigger the lazy fetch by "tickling" the collection in the very rare situations where I need to do that. But I do believe you can force fetch the collection even if it is lazy by creating a HQL query in which you manually join fetch it. I would look into the "JOIN FETCH" and "LEFT JOIN FETCH" HQL constructions for a possible solution to your question.

  • Couldn't persist OneToMany JoinColumn/JoinTable (Unidir) using TopLink JPA

    Hi All,
    I am having a lot of difficulty deploying a OneToMany Unidirectional (Zipcode) record which consist of multiple Zipnames using TopLink on Glassfish v2r2, JDK1.6.0_06, MySQL 5.0, Netbeans 6.1 and Windows XP platform.
    Below are the relevant EJBs snippets:
    Zipcode class
    @Entity
    @Table(name="ZIPCODE")
    public class Zipcode implements Serializable {
    @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
    @JoinColumn(name="ZIPCODE_ID")    
                 or
        @JoinTable(name="ZIPCODE_ZIPNAME",          
                   joinColumns={@JoinColumn(name="ZIPCODE_ID")},
                   inverseJoinColumns={@JoinColumn(name="ZIPNAME_ID")})
        private Collection<Zipname> zipnames = new ArrayList<Zipname>();
        public Collection<Zipname> getNames()
         return zipnames;
        public void setZipnames(Collection<Zipname> zipnames)
         this.zipnames = zipnames;
    Zipname class does not maintain relationship back to Zipcode.
    public class ZipcodeApplicationClient {
    @PersistenceContext(unitName="GeographicalDB-PU")
    private static EntityManager manager;
        public ZipcodeApplicationClient() {
        public static void main(String[] args) {
            try {
                Zipcode zipcode_1 = new Zipcode();
                zipcode_1.setcode(9001);
                Zipname zipname_1 = new Zipname();
                zipname_1.setName("Harbour Cove");
                zipcode_1.getNames().add(zipname_1);
                // Can add one Zipname record with JoinTable but not JoinColumn
                Zipname zipname_2 = new Zipname();
                zipname_2.setName("Wonderland");
                zipcode_1.getNames().add(zipname_2);
                manager.persist(zipcode_1);   // line 45
    The same deployment error message below was generated from both JoinColumn and JoinTable methods:
    run-deploy:
    run-display-browser:
    run-ac:
    Copying 1 file to C:\Documents and Settings\Jack\GeographicalBean\dist
    Caught an unexpected exception!
    java.lang.NullPointerException
            at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:45)
            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 com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:266)
            at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:449)
            at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:259)
            at com.sun.enterprise.appclient.Main.main(Main.java:200)
    run-InvestmentBean-app-client:The JoinColumn method would not work for one Zipname record. On the other hand, JoinTable approach would allow us to add a single Zipname record without error out.
    Q1. Can you confirm whether TopLink JPA 1.0 (Glassfish v2r2) support OneToMany JoinColumn Unidirectional at all?
    Q2. Does TopLink JPA 1.0 (Glassfish v2r2) support OneToMany JoinTable Unidirectional? If so, what is the cause of this issue? Otherwise, please make appropriate recommendation steps to take.
    This question has been posted on http://forums.sun.com/thread.jspa?threadID=5330670&tstart=0 and http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=78&t=004489&p=1 earlier in the hope a quicker response.
    Your guidance would be very much appreciated.
    Many thanks,
    Jack

    Hi,
    Below are some more error output from the OneToMany JoinTable Unidirectional approach:
    pre-run-deploy:
    Initial deploying InvestmentBean to C:\Documents and Settings\abc\InvestmentBean\dist\gfdeploy
    Completed initial distribution of InvestmentBean
    Start registering the project's server resources
    Finished registering server resources
    moduleID=InvestmentBean
    deployment started : 0%
    deployment finished : 100%
    Deploying application in domain completed successfully
    Trying to create reference for application in target server completed successfully
    Trying to start application in target server completed successfully
    WARNING:
    JDO76614: Deployment encountered SQL Exceptions:
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPCODE (ID INTEGER NOT NULL, DIALING_CODE VARCHAR(255), TIME_ZONE VARCHAR(255), CODE INTEGER, NEAREST_AIRPORT VARCHAR(255), LONGITUDE VARCHAR(255), NEAREST_TRAIN_STATION VARCHAR(255), NEAREST_URBAN_CENTRE VARCHAR(255), HOTELS VARCHAR(255), LATITUDE VARCHAR(255), NEARBY_FEATURES VARCHAR(255), COUNCIL VARCHAR(255), LOCALITY VARCHAR(255), PRIMARY KEY (ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipcode' already exists
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPCODE_ZIPNAME (ZIPCODE_ID INTEGER NOT NULL, ZIPNAME_ID INTEGER NOT NULL, PRIMARY KEY (ZIPCODE_ID, ZIPNAME_ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipcode_zipname' already exists
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPNAME (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipname' already exists
    JDO76609: Got SQLException executing statement "ALTER TABLE ZIPCODE_ZIPNAME ADD CONSTRAINT FK_ZIPCODE_ZIPNAME_ZIPCODE_ID FOREIGN KEY (ZIPCODE_ID) REFERENCES ZIPCODE (ID)": java.sql.SQLException: Can't create table '.\geographicaldb\#sql-434_4.frm' (errno: 121)
    JDO76609: Got SQLException executing statement "ALTER TABLE ZIPCODE_ZIPNAME ADD CONSTRAINT FK_ZIPCODE_ZIPNAME_ZIPNAME_ID FOREIGN KEY (ZIPNAME_ID) REFERENCES ZIPNAME (ID)": java.sql.SQLException: Can't create table '.\geographicaldb\#sql-434_4.frm' (errno: 121)Enable of InvestmentBean in target server completed successfully
    Enable of application in all targets completed successfully
    All operations completed successfully
    post-run-deploy:
    run-deploy:
    run-display-browser:
    run-ac:
    Copying 1 file to C:\Documents and Settings\Jack\GeographicalBean\dist
    Caught an unexpected exception!
    java.lang.NullPointerException
    at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:45)
    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 com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:266)
    at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:449)
    at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:259)
    at com.sun.enterprise.appclient.Main.main(Main.java:200)
    run-GeographicalBean-app-client:
    run:
    I would like to correct an earleir comment where I stated that this method did work when adding a single Zipname record. This is no true.
    Thanks,
    Jack

Maybe you are looking for

  • Errors when Installing CS6 10.8

    HI, When I try installing CS6 Master Collection on an 10.8.5 Machine I am receiving the below log full of error messages. I have tried uninstalling and reinstalling the program, Have also tried removing the preferences through the Adobe cc cleaner. I

  • What is the Diff bet partner functions and business partner?

    Hi friends what is the Diff bet partner functions and business partner Regards Abirath

  • ESC key does not work when Photoshop CS4 is opened

    Hi everyone! It seems that everytime my Photoshop CS4 is opened, my ESC key ceases to function. When I close the PS, it starts to function again. Running Windows 7 64-bit. I've tried cleaning my registry and reloading PS. Not that critical, but it go

  • Runtime Error when cancelling license request

    I'm getting the following error when cancelling a license request.  The main difference between my application and the sample applications is that the root Flex Application is mx:Application, rather than mx:WindowedApplication, but I can't figure out

  • User Exit for COR6 Update required..

    Dear Experts, I am supposed to add a logic along with a pop up window in COR6 when the user clicks on "Partial Confirmation" Button in COR6.  My problem is that field name for the "Partial Confirmation" Button in COR6 is CORUF-TEILR. And the value is