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.

Similar Messages

  • JPA lazy loading with Firebirdsql

    I'm trying to use FetchType.Lazy in @OneToOne associations, with a firebirdsql database.
    Toplink JPA generates the sql query as follow:
    SELECT FIELD1, FIELD2, _TOPLINK_FIELD3_VH, ... FROM TABLE.....
    This select gets this error msg:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060829)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: org.firebirdsql.jdbc.FBSQLException: Exception. nullError Code: 0
    (it can't find the TOPLINKFIELD3_VH field)
    Is this an issue related to firebirdsql support on Toplink?
    Or is it a issue related to firebirdsql JDBC driver/database?

    Don't double post. I've removed the thread you started 3 hrs 16 minutes after this one with the identically same question.
    db

  • JPA - lazy loading for LOB field

    Hi all,
    JPA 1.0 specification mandates that all JPA-compliant implementation support lazy loading for certain kind of entity field.
    For LOB fields lazy loading is OPTIONAL.
    I am experiencing odd runtime behaviors on my custom software which would point to this feature not being supported.
    Can anyone please tell me if SAP JPA 1.0 implementation on NW CE 711 implements this feature or not?
    Thanks in advance
    Regards
    Vincenzo

    Hi Vincenco,
    I am sure that this is the same as with single-valued relationships (@OneToOne, @ManyToOne): Lazy loading would require bytecode manipulation/generation, so SAP JPA does not support it in 7.20 (and of course not in 7.11)
    See tulsi jiddimani's elaborate answer here: Re: JPA: Documentation on LazyLoad.
    In 7.30 enhancements, you really can find lazy loading support for single-valued relationships with getReference.
    http://help.sap.com/saphelp_nw73/helpdata/en/68/f676ef36094f4381467a308a98fd2a/content.htm
    but @Lob and @Basic is not mentioned.
    If you need lazy loading in 7.11, you have two alternatives:
    1. Put the Lob fields into separate entities, work around the missing feature in SAP JPA with ugly @OneToMany - Relations
    2. Use another persistence provider like EclipseLink, read Sabine Heider's blogs about integrattion of EclipseLink in SAP NetWeaver and static bytecode weaving for lazy loading. /people/sabine.heider/blog
    Regards
    Rolf

  • Toplink JPA LAZY loading in Java SE works without javaagent?

    hi there,
    I tought that mappings like
    @JoinColumn(name = "join_col_name")
    @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    private RelatedObject relObj;
    with TopLink JPA in Java SE environment works ONLY with the
    -javaagent:toplink-essentials-agent.jar
    JVM parameter?
    the strange thing is: I did 2 test runs, with and without the java agent parameter. I also could see that in the first case the weaver is working, in the second the property "toplink.weaving=false" is printed to the console BUT if I access the LAZY mapped attribute of the object instance it works in both cases - I expected a NullPointerEx. in the case without the javaagent.
    Is there anything I missed?
    Hans

    Chris,
    thank for for the tip about verifying lazy or eager fetching. The results are interesting - or better: confusing - to me:
    I have built a test project with 3 entities:
    Entity A hast @OneToMany to Entity B and
    Entity B has ManyToONe to Entity C
    A <-- B --> C
    ALL relations are marked with FetchType.LAZY in all directions.
    When I simply run the test project via main()-method out of eclipse, WITHTOUT specifycing a -javaagent parameter in the run dialog, I can confirm using your test case that the realtion IS LAZILY FETCHED.
    So, I do not really know how this should work without the javaagent.
    You mentioned statically weaved classed - is this the default case when no agent is present, how is it done? Toplink logging says that weaving is NOT active:
    ServerSession(16821027)--Thread(Thread[main,5,main])--property=toplink.weaving; value=false
    so how can the lazy loading work then?
    regards,
    Hans

  • Yet Another Thread Question

    Double-Checked Locking is used as an efficient method for implementing lazy initialisation in a multithreaded environment. Nevertheless some people think that it's a dangerous method. I would like to hear (read) your opinions.
    TIA

    Double-Checked Locking is used as an efficient method
    for implementing lazy initialisation in a
    multithreaded environment. Nevertheless some people
    think that it's a dangerous method. I would like to
    hear (read) your opinions.It is not dangerous as long as the whole team only uses acessors and never directly accesses the attributes. It depends on the programmer's discipline.

  • Toplink 9045 Migration Issue

    Hi,
    I am currently migrating my application from WLS7.0 and Toplink903 to WLS8.1sp3 and Toplink9045.
    I am getting the folowing error when i am trying to generate EAR file using weblogic.ejbc
    [java] Local Exception Stack:
    [java] Exception [TOPLINK-14025] (OracleAS TopLink - 10g (9.0.4.5) (Build 040930)): oracle.toplink.ejb.De
    ploymentException
    [java] Exception Description: An error occurred while getting mapping during the code generation : [Excep
    tion [TOPLINK-178] (OracleAS TopLink - 10g (9.0.4.5) (Build 040930)): oracle.toplink.exceptions.DescriptorExce
    ption
    [java] Exception Description: Cannot find mapping for attribute [trade] in entity bean [com.fanniemae.mf.
    jj.persistence.closedTrade.ClosedTradeBean]. The attribute must mapped.]
    [java] Internal Exception: Exception [TOPLINK-178] (OracleAS TopLink - 10g (9.0.4.5) (Build 040930)): ora
    cle.toplink.exceptions.DescriptorException
    [java] Exception Description: Cannot find mapping for attribute [trade] in entity bean [com.fanniemae.mf.
    jj.persistence.closedTrade.ClosedTradeBean]. The attribute must mapped.
    [java] at oracle.toplink.ejb.DeploymentException.errorGetMappingFromAttribute(DeploymentException.jav
    a:91)
    [java] at oracle.toplink.internal.ejb.cmp.codegen.CmpCodeGenPlatform.getMappingFromAttributeName(CmpC
    odeGenPlatform.java:553)
    [java] at oracle.toplink.internal.ejb.cmp.codegen.CmpCodeGenPlatform.getIndirectionPolicy(CmpCodeGenP
    latform.java:579)
    [java] at oracle.toplink.internal.ejb.cmp.codegen.CmpCodeGenPlatform.createGetMethod(CmpCodeGenPlatfo
    rm.java:320)
    [java] at oracle.toplink.internal.ejb.cmp.codegen.CmpCodeGenPlatform.addContainerManagedAttributesAnd
    Methods(CmpCodeGenPlatform.java:140)
    [java] at oracle.toplink.internal.ejb.cmp.codegen.CmpCodeGenPlatform.generateConcreteClass(CmpCodeGen
    Platform.java:454)
    [java] at oracle.toplink.internal.ejb.cmp.codegen.ConcreteClassGenerator.generateConcreteClass(Concre
    teClassGenerator.java:26)
    [java] at oracle.toplink.internal.ejb.cmp.wls.WlsCMPCodeGenerator.codeGenSubclass(WlsCMPCodeGenerator
    .java:56)
    [java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    [java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    [java] at java.lang.reflect.Method.invoke(Method.java:324)
    [java] at weblogic.utils.compiler.CodeGenerator.processAt(CodeGenerator.java:648)
    [java] at weblogic.utils.compiler.CodeGenerator.parse(CodeGenerator.java:587)
    [java] at weblogic.utils.compiler.CodeGenerator.parse(CodeGenerator.java:519)
    [java] at weblogic.utils.compiler.CodeGenerator.generateCode(CodeGenerator.java:336)
    [java] at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java:238)
    [java] at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java:197)
    [java] at weblogic.ejb20.ejbc.EJB20CMPCompiler.generatePersistenceSources(EJB20CMPCompiler.java:88)
    [java] at weblogic.ejb20.ejbc.EJBCompiler.doCompile(EJBCompiler.java:245)
    [java] at weblogic.ejb20.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:476)
    [java] at weblogic.ejb20.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:397)
    [java] at weblogic.ejbc20.runBody(ejbc20.java:517)
    [java] at weblogic.utils.compiler.Tool.run(Tool.java:146)
    [java] at weblogic.utils.compiler.Tool.run(Tool.java:103)
    [java] at weblogic.ejbc.main(ejbc.java:29)
    I am using all the latest jar's and did't understand why i am getting this error. If any one had got the same type of errors please let me know how to solve this issue.
    Thank you.

    First are you using JPA and a persistence.xml with TopLink (TopLink Essentials was the JPA provider I believe) or are you using native TopLink with a sesssions.xml?  WIthout entity changes to support lazy relationships (such as weaving if using JPA) lazy relationships will only work for collection mappings - but these are already set to default to lazy,  If it is JPA, you can configure your entity mappings to be Lazy through annotations or an orm.xml file and let weaving work on your entities, while if using Sessions.xml, you need to make changes to the entities themselves to support lazy relationships as well as set the mappings to be lazy.  This is called indirection in TopLink, and is described here: Understanding Relationship Mappings
    If you are using JPA and a persistence.xml, the migration to EclipseLink should be fairly easy.  See https://wiki.eclipse.org/EclipseLink/Examples/JPA/Migration/TopLinkEssentials for details
    Otherwise it may require package renaming and ensuring that the project was not using deprecated classes, but still should not be too complex.  Migrating from Native TopLink | EclipseLink 2.4.x Understanding EclipseLink has instructions and details.
    If this is not enough to go on, please give more details on what you have. 
    Best Regards,
    Chris

  • TopLink 10g Cascading Issue

    How can I make the default read behavior of each Entity set to **lazyloading** in TopLink 10g?
    We're using TopLink 10g in an application which is being used by 1000s of customers everyday. I'm also looking to find a good and safe way to migrate from TopLink 10g as there are very few stuffs available about TopLink 10g and those who were using it already migrated to EclipseLink/JPA or TopLink 11g-12g. We also have to do the same, but that will be a long-term goal. Please share your experiences regarding migration from TopLink (10g).
    Although, for now, we need to fix a problem (which would be a quick-fix instead of migrate from TopLink 10g). The problem is; One of the TopLink Entity read also getting (querying) all of its associates (child Entities) which is causing too many unnecessary queries to the database. However, we solved this problem by using `ObjectCopyingPolicy`:
        ObjectCopyingPolicy objCopyingPolicy = new ObjectCopyingPolicy();
        objCopyingPolicy.setShouldResetPrimaryKey(false);
        objCopyingPolicy.cascadePrivateParts();
        someEntity = (SomeEntity) getTopLinkTemplate().copy(getTopLinkTemplate().readById(SomeEntity.class, new Long(someId)), objCopyingPolicy);
    The aforementioned code snippet is one of the resolution to solve such a problem. But, we'd like to solve this problem by configuration (persistence.xml etc.). There is nothing in the documentation, neither I found anything by googling it.
    Please let me know if you would require more details to answer this question.
    Good Day!

    First are you using JPA and a persistence.xml with TopLink (TopLink Essentials was the JPA provider I believe) or are you using native TopLink with a sesssions.xml?  WIthout entity changes to support lazy relationships (such as weaving if using JPA) lazy relationships will only work for collection mappings - but these are already set to default to lazy,  If it is JPA, you can configure your entity mappings to be Lazy through annotations or an orm.xml file and let weaving work on your entities, while if using Sessions.xml, you need to make changes to the entities themselves to support lazy relationships as well as set the mappings to be lazy.  This is called indirection in TopLink, and is described here: Understanding Relationship Mappings
    If you are using JPA and a persistence.xml, the migration to EclipseLink should be fairly easy.  See https://wiki.eclipse.org/EclipseLink/Examples/JPA/Migration/TopLinkEssentials for details
    Otherwise it may require package renaming and ensuring that the project was not using deprecated classes, but still should not be too complex.  Migrating from Native TopLink | EclipseLink 2.4.x Understanding EclipseLink has instructions and details.
    If this is not enough to go on, please give more details on what you have. 
    Best Regards,
    Chris

  • Role assignment did not work during migration

    We just finished a QA migration from EP60 to NW04 SPS14.
    Everything went OK with the exception of the following:
    Users who had customer defined roles assigned in the source system (EP60) did not get the roles assigned in the target system.(NW04) For example, if I had a few out of the box SAP roles assigned to a user in the source system, they were assigned to that user in the migrated NW04 system. The customer assinged roles did not get attached to the same users users.
    Has anybody run into similar findings ???

    Some more info.
    We may have figured out that during the migration the NW portal inititaed a connection to our LDAP server and failed. We have MSADS with a multi LDAP configuration and have configured SSL for the connection to LDAP.
    Any Ideas ???
    I pulled this out of the trace file:
    #1.5#005056B171CC00560000000C00000FE8000405C779F98BF4#1132254209877#/System/Security##com.sap.engine.services.keystore#Administrator#389####d73f3750579c11da8ea8005056b171cc#SAPEngine_Application_Thread[impl:3]_28##0#0#Warning#1#com.sap.engine.services.keystore#Java###Source: java.lang.NullPointerException; Description: ; Consequences: ; Countermeasures:##
    #1.5#005056B171CC00610000000600000FE8000405C779FA37A6#1132254209924#/System/Security##com.sap.engine.services.keystore#Administrator#389####d73f3750579c11da8ea8005056b171cc#SAPEngine_Application_Thread[impl:3]_32##0#0#Warning#1#com.sap.engine.services.keystore#Java###Source: java.lang.NullPointerException; Description: ; Consequences: ; Countermeasures:##
    #1.5#005056B171CC001D00000001000011D0000405C7DA2B657E#1132255823810#/System/Security/Usermanagement##com.sap.security.core.persistence#######SAPEngine_System_Thread[impl:5]_23##0#0#Fatal#1#com.sap.security.core.persistence#Java###No connection to the ldap server, recheck configuration or availability of directory server##
    #1.5#005056B171CC001D00000004000011D0000405C7DA2B6F70#1132255823810#/System/Security/Usermanagement##com.sap.security.core.persistence#######SAPEngine_System_Thread[impl:5]_23##0#0#Fatal#1#com.sap.security.core.persistence#Java###Server not available,recheck configuration or availability of directory server##
    #1.5#005056B171CC001D00000007000011D0000405C7DA2B7443#1132255823810#/System/Security/Usermanagement##com.sap.security.core.persistence#######SAPEngine_System_Thread[impl:5]_23##0#0#Fatal#1#com.sap.security.core.persistence#Java###Initialisation of a connection pool failed for UACC please check the configuration or availability of the directory server##
    #1.5#005056B171CC001D00000009000011D0000405C7DA2B78C2#1132255823810#/System/Security/Usermanagement##com.sap.security.core.persistence#######SAPEngine_System_Thread[impl:5]_23##0#0#Fatal#1#com.sap.security.core.persistence#Java###Please recheck the LDAP configuration Initialisation of connection pool failed for UACC
         poolname qadc2.app.csa-group.qa:636_UACC
         java.naming.factory.initial= com.sun.jndi.ldap.LdapCtxFactory
         java.naming.security.principal= cn=epqadm2,ou=PortalUsers,dc=app,dc=csa-group,dc=qa
         java.naming.ldap.version= 3
         connection_pool_name= qadc2.app.csa-group.qa:636_UACC
         java.naming.provider.url= ldap://qadc2.app.csa-group.qa:636/ou%3DPortalUsers%2Cdc%3Dapp%2Cdc%3Dcsa-group%2Cdc%3Dqa
         java.naming.security.protocol= ssl
         java.naming.ldap.factory.socket= com.sap.security.ssl.SSLSocketFactory
         java.naming.security.authentication= simple
         java.naming.security.credentials= ******
         [EXCEPTION: no connection to the ldap server:null]##
    #1.5#005056B171CC001D0000000D000011D0000405C7DA2B8C9E#1132255823810#/System/Security/Usermanagement##com.sap.security.core.persistence#######SAPEngine_System_Thread[impl:5]_23##0#0#Error#1#com.sap.security.core.persistence#Java###DataSource : Initialisation of connection manager failed, due to SSL configuration lazy initialisation#1#CORP_LDAP2#

  • LazyLoading: dump with basic operation

    Hi all,
    I have two JPA entities: Company and Employee
    Company is in a @OneToMany relationship with Employee
    Employee is in a @ManyToOnw relationship with Company and owns the relationship
    I have marked Employee's side as eager and Company side as lazy
    I have developed a simple ejb which does something like this:
    public void retrieveCompany(String id){
    Company cmp = em.find(Company.class, id);
    If I invoke this ejb from a WDJ or another EJB I get an odd error on lazy loading
    Caused by: java.lang.ClassCastException
    at java.lang.Class.cast(Class.java:2951)
    at com.sap.engine.services.orpersistence.core.StoreManager.createLazyRelation(StoreManager.java:238)
    at com.sap.engine.services.orpersistence.core.StoreManager.loadMultipleToManyRelationships(StoreManager.java:1349)
    at com.sap.engine.services.orpersistence.core.StoreManager.processEntityInfos(StoreManager.java:1148)
    at com.sap.engine.services.orpersistence.core.StoreManager.loadOrRefreshFromDB(StoreManager.java:226)
    at com.sap.engine.services.orpersistence.core.StoreManager.loadEntityOrRefreshExisting(StoreManager.java:180)
    at com.sap.engine.services.orpersistence.core.PersistenceContextImpl.loadEntityFromConnection(PersistenceContextImpl.java:247)
    at com.sap.engine.services.orpersistence.core.PersistenceContextImpl.loadEntity(PersistenceContextImpl.java:262)
    at com.sap.engine.services.orpersistence.core.PersistenceContextImpl.find0(PersistenceContextImpl.java:191)
    at com.sap.engine.services.orpersistence.core.PersistenceContextImpl.find(PersistenceContextImpl.java:175)
    at com.sap.engine.services.orpersistence.core.MonitoredPersistenceContextImpl.find(MonitoredPersistenceContextImpl.java:246)
    at com.sap.engine.services.orpersistence.entitymanager.EntityManagerImpl.find(EntityManagerImpl.java:129)
    at com.sap.engine.services.orpersistence.entitymanager.EntityManagerHandleImpl.find(EntityManagerHandleImpl.java:42)
    at com.sap.engine.services.orpersistence.container.EntityManagerProxy.find(EntityManagerProxy.java:82)
    This error is solved if I set Company's side of the relationship as EAGER, but this is not acceptable to me.
    Can anyone please advice?
    Thanks, regards
    Vincenzo

    hi all,
    I found out what was missing:
    As per JPA specifications relationships must be modeled using
    Collection, Set, List, Map
    AND NOTHING ELSE
    you must not use ArrayList or whatever even though they implement those interfaces.
    However, I would like to use this thread to define the final truth about SAP JPA lazy loading behavior:
    In my WDJ model I call an EJB method which returns an entity which has a oneToMany relationship marked as lazy
    The returned entity is detached and if nothing is specified you will get an "entity is detached" dump.
    So: if you want your collection loaded from db, in your EJB you might use something like
    myEntity.getMyCollection().size();
    in this way I have checked that all the items in the collection are loaded and returned.
    if you don't want you collection loaded you must use somethink like:
    myEntity.setMyCollection(null);
    So that it will kill the proxy which has been loaded in place of the actual collection object.
    Please comment and report your experience, this is fundamental for everyone using SAP JPA implementation
    Thanks, regards
    Vincenzo

  • Preloading dynamically created objects

    Hi,
    I have some Object I would like to create on runtime, but it initialization takes some time. So normally I would code something like
    Class SimpleFoo
    private BigObject bO = new bO("parameters here");
    BigObject getBigObject()
    return bO;
    }but now I have a lot (say around 30 in the total class, which is more complicated) of them, so it would be something like
    Class MessyFoo
    private BigObject bOprime = new bO("prime parameters here");
    private BigObject bOeven = new bO("even parameters here");
    BigObject getBigObject(int i)
    if (isPrime(i))
    return bOprime;
    else if (isEven(i))
      return bOeven;
    }which gets really messy. I'd rather code
    Class CleanLookingFoo
    BigObject getBigObject(int i)
      if (isPrime(i))
       return new bO("prime parameters here");
      else if (isEven(i))
        return new bO("even parameters here");
    }but then I miss the caching and initialization advantages. What is the best way to build this? So far my best option is to pre-process the CleanLookingFoo and make a MessyFoo out of it, and then pass it through to the Java compiler, which probably isn't the best solution.

    The usual pattern is to use a synchronization mechanism and a lazy initialiser. The simplest mechanism is to use a holder class with a static field, since it won't get initialised until it's first used:
    public class LazyBigObjects {
         static class BigObject {
              BigObject (String params) {
                   System.out.println(params);
         static class PrimeBigObjectHolder {
              static final BigObject INSTANCE = new BigObject("prime parameters here");
         static class EvenBigObjectHolder {
              static final BigObject INSTANCE = new BigObject("even parameters here");
         public static BigObject getBigObject(int i) {
              System.out.println("getBigObject called with " + i);
              switch (i) {
                   case 0: {
                        return PrimeBigObjectHolder.INSTANCE;
                   case 1: {
                        return EvenBigObjectHolder.INSTANCE;
                   default:
                        throw new IllegalArgumentException(i + " out of range.");
         public static void main (String...args) {
                 getBigObject(0);
              getBigObject(1);
    }Output:
    getBigObject called with 0
    prime parameters here
    getBigObject called with 1
    even parameters here
    The JVM handles synchronisation issues of class initialisation, so you don't need to do anything about that.

  • Hard to get the idea

    to write an applet to compute the Grade Point Average (GPA) for a list of subject taken with in the semister
    the grade is obtained based on the following table
    LETTER GRADE NUMERIC GRADE
    A 4
    B 3
    C 2
    D 1
    F 0
    for example a student take 3 subjects in a semister
    SUBJECT LETTER GRADE NUMERIC GRADE CREDIT UNIT
    subject 1 A 4 5
    subject 2 D 1 3
    subject 3 c 2 4
    then GPA = (4*5+1*3+2*4)/(5+3+4) = 2.58
    The number of credit unit is equivalent to the number of contact hours in a week. to compute the GPA of the semister:
    GPA = (numGrade1*creditUnit1+numGrade2*creditunit2+numGrade3*dreditunit3)/(total credits )
    where ,numGrade1,numGrade2 and numGrade3 are the numeric grades of subject1 ,Subject2 and Subject3 respectively.
    total credit is the total number of credit units taken in teh semister.
    i have to use layout manager , graphical components and two methods convGrade() and calcGPA() to convert the letter grade input to its numeric grade equivalence and compute the GPA respectively.
    i have to add three text fields to enter letter grades of 3 subjects
    and 3textfields to enter credit unit of 3 subject and their respective label (Enter grade of subject 1,Enter credit unit of Subject1...) and to add a button to compute GPA , at last label "your GPA for the semister is ----"
    please reply me urgently

    try this simple programm (due to time it is without error handling and
    comfort - but it will do) - just copy it to a file named GradeView:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class GradeView extends JFrame {
         // change these texts to you favourites
         public static final String TX_SUBJECT1 = "Subject1:";
         public static final String TX_SUBJECT2 = "Subject2:";
         public static final String TX_SUBJECT3 = "Subject3:";
         public static final String TX_HEADER1 = "Subject";
         public static final String TX_HEADER2 = "Grade";
         public static final String TX_HEADER3 = "Credit Unit";
         public static final String TX_GPA = "Your GPA for the semister is ";
         // the textFields for grades
         private JTextField txGradeSubject1;
         private JTextField txGradeSubject2;
         private JTextField txGradeSubject3;          
         // the text fields for CREDIT UNIT
         private JTextField txCuSubject1;
         private JTextField txCuSubject2;
         private JTextField txCuSubject3;          
         // the button
         private JButton btCompute = new JButton("Compute GPA");
         private JLabel computedLabel = new JLabel("");
         public GradeView(){
              super("Grade Point Average");
              initView();
         private void initView(){
              // add labels and fields
              JPanel entryPane = new JPanel();
              // we add a table structure
              entryPane.setLayout(new GridLayout(0,3));
              // add headers
              entryPane.add(new JLabel(TX_HEADER1));
              entryPane.add(new JLabel(TX_HEADER2));
              entryPane.add(new JLabel(TX_HEADER3));
              // and fields
              entryPane.add(new JLabel(TX_SUBJECT1));
              entryPane.add(getTxGradeSubject1());
              entryPane.add(getTxCuSubject1());
              entryPane.add(new JLabel(TX_SUBJECT2));
              entryPane.add(getTxGradeSubject2());
              entryPane.add(getTxCuSubject2());
              entryPane.add(new JLabel(TX_SUBJECT3));
              entryPane.add(getTxGradeSubject3());
              entryPane.add(getTxCuSubject3());
              // now add all to the frame
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(entryPane, BorderLayout.CENTER);
              getContentPane().add(btCompute, BorderLayout.SOUTH);
              getContentPane().add(computedLabel, BorderLayout.NORTH);
              // add a Listener to the button
              btCompute.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent arg0) {
                        calcGPA() ;
         public static void main(String[] args) {
              GradeView view = new GradeView();
              view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              view.setResizable(false);
              view.setSize(250, 150);
              view.setVisible(true);
         // here the gpa is calcutaed from the values entered
         private void calcGPA(){
              // read the values from the textFields
              int grade1 = convertGrade(getTxGradeSubject1().getText());
              int grade2 = convertGrade(getTxGradeSubject2().getText());
              int grade3 = convertGrade(getTxGradeSubject3().getText());
              int cu1 = getIntText(getTxCuSubject1());
              int cu2 = getIntText(getTxCuSubject2());          
              int cu3 = getIntText(getTxCuSubject3());
              // compute the gpa - we need a double
              double gpa = ((double)grade1*cu1 + grade2*cu2 + grade3*cu3)/(cu1+cu2+cu3);
              // update our label
              computedLabel.setText(TX_GPA + gpa);          
         private int getIntText(JTextField field){
              int ret = 0;
              if(field != null){
                   try{
                        ret = Integer.parseInt(field.getText());
                   catch(NumberFormatException exc){
                        // may add error handling here
              return ret;
         private int convertGrade(String value){
              // anything not entered
              if(value==null || value.trim().length()!=1){
                   // may add error handling here
                   return 0;
              char chValue = value.charAt(0);
              if(chValue<'A' || chValue>'F'){
                   // may add error handling here
                   return 0;
    // this will return 0 for 'F', 1 for 'E' and so on
              return (int)(-chValue+'F');
         // the fields use lazy initialisation
         * @return
         private JTextField getTxGradeSubject1() {
              if(txGradeSubject1 == null){
                   txGradeSubject1 = new JTextField(1);
              return txGradeSubject1;
         * @return
         private JTextField getTxGradeSubject2() {
              if(txGradeSubject2 == null){
                   txGradeSubject2 = new JTextField(1);
              return txGradeSubject2;
         * @return
         private JTextField getTxGradeSubject3() {
              if(txGradeSubject3 == null){
                   txGradeSubject3 = new JTextField(1);
              return txGradeSubject3;
         * @return
         private JTextField getTxCuSubject1() {
              if(txCuSubject1 == null){
                   txCuSubject1 = new JTextField(1);
              return txCuSubject1;
         * @return
         private JTextField getTxCuSubject2() {
              if(txCuSubject2 == null){
                   txCuSubject2 = new JTextField(1);
              return txCuSubject2;
         * @return
         private JTextField getTxCuSubject3() {
              if(txCuSubject3 == null){
                   txCuSubject3 = new JTextField(1);
              return txCuSubject3;

  • SAP JPA and lazy loading

    Dear experts,
      I have a WD application with EJB model. I have faced strange JPA exception (I am using SAP JPA implementation).
      This is 2 Entities with relationship
    @Entity
    @Table( schema = "dbo", name = "class")
    public class ClassEntity {
      private Long id;
            @Id
         @Column(name="id")
         @GeneratedValue(strategy= GenerationType.IDENTITY)
        public Long getId() {
              return id;
         public void setId(Long id) {
              this.id = id;
    private Collection<ClassAttributeEntity> classAttributesById;
        @OneToMany(mappedBy = "classByClassId", fetch=FetchType.LAZY)
        public Collection<ClassAttributeEntity> getClassAttributesById() {
            return classAttributesById;
        public void setClassAttributesById(Collection<ClassAttributeEntity> classAttributesById) {
            this.classAttributesById = classAttributesById;
    @Entity
    @Table( schema = "dbo", name = "class_attribute")
    public class ClassAttributeEntity{
    private Long id;
            @Id
         @Column(name="id")
         @GeneratedValue(strategy= GenerationType.IDENTITY)
        public Long getId() {
              return id;
         public void setId(Long id) {
              this.id = id;
        private ClassEntity classByClassId;
        @ManyToOne
        @JoinColumn(name = "class_id", referencedColumnName = "id")
        public ClassEntity getClassByClassId() {
            return classByClassId;
        public void setClassByClassId(ClassEntity classByClassId) {
            this.classByClassId = classByClassId;
      I want to execute JPQL query
    "SELECT c FROM ClassEntity c"
    ; But I get this exception:
    javax.persistence.PersistenceException: The relationship >>classAttributesById<< of entity {test.ClassEntity(id=1686)}cannot be loaded because the entity is detached
      I can overcome it using EAGER loading -
    @OneToMany(mappedBy = "classByClassId", fetch=FetchType.EAGER)
    , but I really dont need ClassAttributes in this situation! I have many thousands of classes and eager loading provides extremly poor perfomance. What can I do with this problem?
      Thanks in advance for any advice.

    Hi Andrey,
    I assume you are getting the exception if you atempt to access "classAttributesById" ouside the transaction, in which you executed the query, i.e. after the persistence context, in which the query has been executed is closed.
    You have got to make sure that all entities you need to access are read as long as the persistence context executing the query is still open.
    How to address this depends a bit on whether you need to access all related entites or only some.
    If you need to access the relationship "classAttributesById" for only some instances of "ClassEntity", you could for example call size() on "classAttributesById" for these selected instances of "ClassEntity" (within the same transaction/persistence context".
    If you need to access all related entities, theoretically, fetchType = EAGER would be the right choice. However, as you have observed, SAP JPA can't handle this efficiently at the time beeing. Therefore,
    I'd rather suggest that you firstly load all related attributes with a query
    "SELECT ca FROM ClassAttributeEntity ca"
    and secondly load the "ClassEntity"s
    "SELECT c FROM ClassEntity c"
    this should execute efficiently.
    Sorry for the inconvenience.
    -Adrian

  • How to configure lazy/eager loading for each JPA query

    Hi!
    I have extensive EJB model (entities with many child entities, entities with association to other large (many fields, BLOBs including) entities, and so on) and I would like for each JPA query configure what properties or associated entities (actually - in arbitrary depth) of selected entities should be fetched.
    E.g. for one query I would like to fetch only Order (and no data of associated entities), but for other queries I would like to fetch Order, Order.Customer, Order.ShippingAddress.ZipCode and nothing else ( e.g. if there is Ordere.Route, Order.Billing and other associations, then I would like not to waste resources for fetching them). In both case the select clause of query can include only Order, but the results should be different - i.e. - there is no associated data in the first case and there are some associated data the second case.
    I know that one solution is to declare all associations as lazy and then - after reading the result of query - do some touching for retrieving the associated data:
    String check = order.Customer.toString();
    check = order.ShippingAddess.ZipCode.toString();
    But I see 2 problems with this: 1) it is not nice (resources are wasted for simply touching associated entities); 2) I assume that each "touch" operation generates other query to database that could be executed together with the original query. So - it would be nice to configure JPA query somehow to let it know which associations will be required from the result and which not.
    What is the best practice?
    I found, that JBoss server has lazy-loading-group configuration, but - I guess - it is JBoss specific:
    http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/4.2/html/Server_Configuration_Guide/Loading_Process-Lazy_loading_Process.html
    besides - it is XML and it would be more pretty if query configuration could be done with annotations!

    JPQL has a "fetch" construct in which you can force a lazy element to be fetched using a query - I must note that I have had unexpected results with it in the past but that was using an old version of Hibernate and I wasn't very experienced with JPA yet.
    http://docs.oracle.com/cd/E15051_01/wls/docs103/kodo/full/html/ejb3_langref.html#ejb3_langref_fetch_joins

  • JPA :: fetching data :: eager Vs lazy

    Using JPA ( with underlying provider as Hibernate )
    This fetch mode is defined in the association annotation itself
    @OneToMany(mappedBy="user",cascade=CascadeType.ALL,fetch=FetchType.EAGER)public Set getAddress() {This means that in the client that makes use of this code is stuck
    The behaviour is fixed .
    Istnt that a disadvantage ?
    Can I not change it dynamically based on what client wants ?
    There very well could be scenarios that for a user A I only have 2-3 records as addresses and for User B I have 100 records as addresses
    I want to do a eager load of data for User A and a lazy load for user B .
    Thanks ,
    ~satish

    satish_marathe wrote:
    Using JPA ( with underlying provider as Hibernate )
    This fetch mode is defined in the association annotation itself
    Can I not change it dynamically based on what client wants ?
    There very well could be scenarios that for a user A I only have 2-3 records as addresses and for User B I have 100 records as addresses
    I want to do a eager load of data for User A and a lazy load for user B .
    If you know the number of records for user A and B, at least comparatively, you can choose to load lazily or eagerly.
    Use EJB QL and fetch join instead of annotation to define fetch type. Depending on the user, you can form your
    query dynamically with or without fetch join. When you use fetch join, relationships are loaded eagerly.
    Having said that, I must say this does not look like a good design.

  • Toplink - JPA ignores lazy fetchtype , when it should NOT

    I'm using Blaze Data Services (The open sourced component of LiveCycle Data Service) , as well as Spring.
    Basically, I have concluded that even while closing the entity manager within the DAO, calls to get a collection on an object after the service layer has returned result in toplink trying to find the objects, vs finding null (or indirect list).
    This is only supposed to happen while the Entity Manager is open, correct?
    Here's a basic overview of my model
    public class Store {
    // ManyToMany
    // Lazy
    Collection<Catalog> catalogs;
    public class Catalog {
    // many to many
    // lazy
    Collection<Category> categories;
    public class Category {
    // many to many
    // lazy
    Collection<Product> products;
    public class Product {
    // here's the kicker
    Collection<Category> categories; // the categories this product is in
    I run into major problems when BlazeDS begins to serialize the beans, in that my lazy mappings are ignored, and tons of SQL statements begin to fire. In fact, the cyclic relationships cause the parent objects to be built as children of their children, for instance, a Product causes Categories to be built yet again, then Products, and it results in a heap space overflow.
    Basically, the only way I was able to work was by removing the mappings entirely.
    If I'm going to do this, I may as well not even use toplink. :-/
    Thanks in advance for any help!

    Also, the relationships I am talking about are not OnetoOne, or ManyToOne. I am not using toplink-agent, but the relationships I am having problems with are ManyToMany.
    DAO Method
    ....public Collection<Store> findAll()
    ........EntityManager em = emf.createEntityManager();
    ........try
    ............Query query = em.createNamedQuery("findStores");
    ............return query.getResultList();
    ........finally
    ............em.close();
    Bean definition
    @Entity
    public class Store implements Serializable
    ....@Id
    ....@GeneratedValue(strategy=GenerationType.SEQUENCE,
    ........................generator="mySeq")
    ....@SequenceGenerator(name="mySeq",
    ........................sequenceName="my_SEQ",
    ........................allocationSize=1)
    ....private long id;
    ....@Column(name="DESCRIPTION")
    ....private String description;
    ....@Column(name="SHORT_DESCRIPTION")
    ....private String shortDescription;
    ....@Column(name="LAST_UPDATE_USER")
    ....private String lastUpdateUser;
    ....@Embedded
    ....private TriggerAttributes triggerAttributes;
    ....@Column(name="NAME")
    ....private String name;
    ....@ManyToMany(fetch = FetchType.LAZY)
    ....@JoinTable(name="STORECATALOG",
    ................joinColumns = @JoinColumn(name = "STORE_UID"),
    ................inverseJoinColumns={@JoinColumn(name="CATALOG_UID")})
    ....private Collection<Catalog> catalogCollection;

Maybe you are looking for

  • Help required in building OBIEE Report

    Hi, Can anyone help me to below OBIEE issues as I am very new to this field. 1. The requirement is to create one Oracle Apps Projects OBIEE report which was previously in discoverer. The discoverer report has 6 worksheet and many custom folders and m

  • Toshiba 32DT1U Problem

    Good evening, I've had the TV since April of 2011 and it's always been at least reasonable.  I've had a few problems trying to set up little things but all have worked out fine eventually. This problem ties in with wanting to use an aftermarket speak

  • Catch KeyDown events for modifier keys

    I need to be able to tell when a user presses or releases the CTRL key for my application, but I can't get KeyListeners to work and the key bindings only appear to work with releasing the key. I also have key bindings for CTRL key combinations (like

  • Foreign currency revaluation not reversed

    Hello, We have a situation where we run FAGL_FC_VAL, the reversal check is marked, and all postings and reversals happen successfully for all accounts, except for one. For this account, the posting is ok, but the reversal entry does not occur. Does a

  • SmartForms002 Error when activating uploaded form

    When I create a smartform with an address element in our pre-dev env, download it and then upload it into our Dev environments, it syntax checks fine but I get a SmartForms002 Error ... Internal Error (Illegal structure of data storage).   It is fine