JPA OneToMany bidirectional -- Entity deletion

I am having trouble deleting an entity part of a part-whole hierarchy and mapped as a OneToMany bidirectional relationship. For example:
public class A {
    @OneToMany(mappedBy="parent", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<A> children;
    @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
    @JoinColumn(name="PARENT_ID")
    private A parent;
}Instances of 'A' can, but do not HAVE to participate in this relationship. Therefore, a cascade on remove is not appropriate, because for any given instance of 'A', a parent and/or any of the children can exist independent of that instance.
So basically I want to remove an instance of 'A', and at the same time have it's child relationships updated -- basically pointing to a null parent.
What's the proper way to do this?
The first and most obvious way to me is:
    entityManager.remove(instanceOfA);But that results in the cryptic error: "deleted entity passed to persist".
The only way I've gotten this to work so far is to use two transactions. In the first, I simply break the relationships and merge the objects:
    Collection<A> children = instanceOfA.getChildren();
    instanceOfA.setChildren(null);
    for(A child : children) {
        child.setParent(null);
        entityManager.merge(child);
    entityManager.merge(instanceOfA);And in the second transaction:
    instanceOfA = entityManager.find(A.class, instanceOfA.getId());
    entityManager.remove(instanceOfA);This works, but feels very clunky.
What is the proper way to do this?
Thanks,
Justin

I am having trouble deleting an entity part of a part-whole hierarchy and mapped as a OneToMany bidirectional relationship. For example:
public class A {
    @OneToMany(mappedBy="parent", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<A> children;
    @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
    @JoinColumn(name="PARENT_ID")
    private A parent;
}Instances of 'A' can, but do not HAVE to participate in this relationship. Therefore, a cascade on remove is not appropriate, because for any given instance of 'A', a parent and/or any of the children can exist independent of that instance.
So basically I want to remove an instance of 'A', and at the same time have it's child relationships updated -- basically pointing to a null parent.
What's the proper way to do this?
The first and most obvious way to me is:
    entityManager.remove(instanceOfA);But that results in the cryptic error: "deleted entity passed to persist".
The only way I've gotten this to work so far is to use two transactions. In the first, I simply break the relationships and merge the objects:
    Collection<A> children = instanceOfA.getChildren();
    instanceOfA.setChildren(null);
    for(A child : children) {
        child.setParent(null);
        entityManager.merge(child);
    entityManager.merge(instanceOfA);And in the second transaction:
    instanceOfA = entityManager.find(A.class, instanceOfA.getId());
    entityManager.remove(instanceOfA);This works, but feels very clunky.
What is the proper way to do this?
Thanks,
Justin

Similar Messages

  • Deleting parent entity of oneToMany does not delete children first,

    I have two entities related with a bi-rdirectional OneToMany relationship. When I delete the parent, I want eclipseLink to automatically delete the child entities first before deleting the parent entity. I have implemented what I understand all the documents are telling me I should implement, but I can not get it working.
    When I try and delete the parent I get an SQLException as the foreign key constraint has been violated as there are child records for the parent I am trying to delete. It was my understanding, that if you have all the annotations correct on my Entities, then all i have to do is delete the parent and eclipseLink will delete the children first and therefore i should never get the SQL exception.
    Here is some snippets of my code.
    Entities
    @Entity(name = "PARENTS")
    public class ParentEntity {
         @Id
         @Column(name = "PARENT_ID", nullable = false)
         private String parentID;
         @Column(name = "DISPLAY_NAME", nullable = false)
         private String displayName;
         @OneToMany(mappedBy="parent", orphanRemoval=true, cascade=CascadeType.ALL)
         private Collection<ChildEntity> childEntities;     
    @Entity(name = "CHILDREN")
    @IdClass(ChildIdentifier.class)
    public class ChildEntity {
         @Id
         @Column(name="ITEM_ID", nullable=false)
         private String itemID;
         @Id
         @ManyToOne()
         @JoinColumn(name="PARENT_ID", nullable=false)
         private ParentEntity parent;
    public class ChildIdentifier implements Serializable {
         private String itemID;
    private String parent;
    Tables created from these entities
    PARENTS
    Name Null? Type
    PARENT_ID NOT NULL VARCHAR2(36)
    DISPLAY_NAME NOT NULL VARCHAR2(255)
    PrimaryKey = PARENT_ID
    CHILDREN
    Name Null? Type
    ITEM_ID NOT NULL VARCHAR2(36)
    PARENT_ID NOT NULL VARCHAR2(255)
    PrimaryKey = ITEM_ID,PARENT_ID
    ForeignKey = PARENTID = PARENTS.PARENT_ID
    Code to delete a parent
         public void deleteParent(String id)
              ParentEntity e= em.find(ParentEntity .class, id);
              if (e!= null)
                   em.remove(e);
    Exception seen
    javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.0.v20120119-r10715): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MYSCHEMA.CHILDREN_FK_P_PARENTS) violated - child record found
    Error Code: 2292
    Call: DELETE FROM PARENTS WHERE (PARENT_ID = ?)
    I have added eclipse logging entries in my persistence.xml to try and see what is going on
    <property name="eclipselink.logging.level" value="FINE"/>
    <property name="eclipselink.logging.parameters" value="true"/>
    And in my jdev console when running my test, i do not see any queries of CHILDREN before it tries to delete from PARENTS.
    Am I missing something really obvious?
    Thanks in advance.
    Edited by: smaslin on Feb 20, 2012 9:20 AM
    Edited by: smaslin on Feb 21, 2012 5:26 AM

    "optional=false" only affects DDL generation, not runtime JPA behavior. PrivateOwned is similar to orphanRemoval in that it should cause the removal of child entities when they are dereferenced from the parent (ie remove them from the parent's collection). Cascade remove or cascade all should be all you need, but PrivateOwned+orphanRemoval should still cause the collection to be removed, as long as there are entities within the Parent's list of children to remove.
    The only case where I can see this not occuring is if you have not been maintaining the bidirectional relationship. That is, if you have added Child entities and set a parent, but not updated the Parent's collection of children to reflect that change. A simple test is to refresh the parent before removal - call em.refresh(e); right before the em.remove(e);. If this works, then you will need to change your application so that when you add parents to a child you also add the child to the parent's list of children - JPA does not maintain relationships for you and not doing so will keep the cache inconsistent with what is in the database.
    Best Regards,
    Chris

  • JPA OneToMany mapping whit toplink...

    I have a problem when i want to map a OneToMany unidirectional relation using toplink. Toplink maps the relation as a ManyToMany relation instead?
    Code in a class called Car:
    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
    public List<Wheel> getWheels() { return wheels; }
    public void setWheels(List<Wheel> wheels) { this.wheels = wheels; }
    toplink output:
    [TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The target entity (reference) class for the one to many mapping element [public java.util.List entities.Car.getWheels()] is being defaulted to: class entities.Wheel.
    [TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The join table name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: CAR_WHEEL.
    [TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The source primary key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: CARID.
    [TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The source foreign key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: Car_CARID.
    [TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The target primary key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: WHEELID.
    [TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The target foreign key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: wheels_WHEELID.
    When i use @JoinColumn i get a message from toplink that says that it is not required when the relation is unidirectional so it is not possible to identify the foreign key..

    The JPA Spec does not allow unidirectional 1-m relationships without using a join table, they must always be bidirectional. You must define a 1-1 back-reference and use the "mapped-by" in the 1-m mapping referencing the 1-1.

  • Bidirectional entity access problem (EJB3)

    I made some tests with EJB3 entity beans.
    I have simple entity USERS, where is itself (FK-PK) relation PARENT_ID -> USER_ID.
    Appropriate part of persistent class Users is:
         @ManyToOne
         @JoinColumn(name = "PARENT_ID", referencedColumnName="USER_ID")
         public Users getUsers() {
              return this.users;
         }end servers side:
         @OneToMany(mappedBy="users", cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
         public Set<Users> getUserses() {
              return this.userses;
         }When I do something, specially call setUser(childInstance) to point the parent instance, on MenyToOne side of association it works.
    But when I try to do similar on OneToMany side, like calling:
    getUserses().add(childInstance)or
    getUserses().remove(childInstance)The changes are only transient and there's not saved into the database.
    Although the entity class has bidirectional annotations, it works like unidirectional.
    Thanks for some help
    KM

    In JPA you must always set both sides of the relationship.
    See,
    [http://en.wikibooks.org/wiki/Java_Persistence/Relationships]
    -- James : [http://www.eclipselink.org]

  • Problem of cycle and stackoverflow when using JPA @OneToMany mapping Tag

    Hello everyone!
    Description:
    We are using the tag @OneToMany to map a collection of objects in an entity. In the other side, we use the tag @ManyToOne to map the father.
    Our simple example for testing consist of the following entities:
    This is the class Child:
    @Entity
    @Table(name="TEST_CHILD")
    public class Child implements Serializable{
    @Id
    @Column(name="ID_CHILD")
    private Long id;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ID_FATHER", referencedColumnName="ID_FATHER")
    private Father father;
    and this is the Father class:
    @Entity
    @Table(name="TEST_FATHER")
    public class Father implements Serializable{
    @Id
    @Column(name="ID_FATHER")
    private Long id;
    @OneToMany(mappedBy="father", fetch=FetchType.EAGER)
    private List<Child> children;
    Problem:
    When a select over this entities is realized, we are getting the folling exception:
    The following Error is thrown by the VM [java.lang.StackOverflowError]. ErrorQueueHandler will just trace it. The caller component should take care to process it properly.
    java.lang.StackOverflowError
    at java.lang.Class.searchMethods(Class.java:2646)
    We've already used @OneToMany and @ManyToOne mapping in many other projects, and we've tried different parameters on the tags as well, but we still getting the exception. If applying fetch mode Lazy to the @OneToMany we had an detatched exception, cause ou the context. Anyways, we need and would like to use the EAGER loading mode.
    So what seems to happen is that the application runs into a cycle when loading the "father" attribute of Child, recreating the list collection within it.
    This same configuration works just fine in other implementations (i.e.: Hibernate JPA implementation), and many other examples over the web are not different of our implementation.
    Any suggestion of how we could solve this problem? Is this a standart behavior of mapping using Sap JPA?
    Evandro Pomatti
    Edited by: Evandro Pomatti on Dec 9, 2010 9:55 PM

    hi evandro,
    now I got same kind of error, how did you fix, pls help if you have remembered,
    hi all,
    I am getting folowing error in my JAVA portal system when executing webservices in WSnavigator.
    if anyone would have been faced this kind of error pls help me.
    The following Error is thrown by the VM [java.lang.StackOverflowError]. ErrorQueueHandler will just trace it. The caller component should take care to process i
    t properly.
    completere error log
    #2.#2014 04 27 23:52:42:197#0-500#Warning#com.sap.engine.core.thread.impl3.ErrorQueueHandler#
    com.sap.ASJ.krn_thd.000025#BC-JAS-COR#kernel.sda#C0000AF060EF002D000001A901AA0076###com.sap.engine.core.thread.impl3.ErrorQueueHandler#Guest#0##9586B2DBCCBD11E3
    A75E0000033325C2#9586b2dbccbd11e3a75e0000033325c2#9586b2dbccbd11e3a75e0000033325c2#0#Thread[ErrorQueueWatchDog,5,main]#Plain##
    The following Error is thrown by the VM [java.lang.StackOverflowError]. ErrorQueueHandler will just trace it. The caller component should take care to process i
    t properly.
    java.lang.StackOverflowError
            at java.security.AccessController.doPrivileged(Native Method)
            at java.io.FilePermission.init(FilePermission.java:183)
            at java.io.FilePermission.<init>(FilePermission.java:249)
            at sun.net.www.protocol.file.FileURLConnection.getPermission(FileURLConnection.java:198)
            at sun.security.provider.PolicyFile.canonicalizeCodebase(PolicyFile.java:1784)
            at sun.security.provider.PolicyFile.access$700(PolicyFile.java:264)
            at sun.security.provider.PolicyFile$7.run(PolicyFile.java:1247)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.security.provider.PolicyFile.getPermissions(PolicyFile.java:1243)
            at sun.security.provider.PolicyFile.getPermissions(PolicyFile.java:1190)
            at com.sap.engine.services.security.jacc.provider.PolicyImpl.implies(PolicyImpl.java:71)
            at com.sap.security.core.UmePolicy.implies(UmePolicy.java:696)
            at com.sap.security.core.role.jacc.JACCPolicy.implies(JACCPolicy.java:367)
            at java.security.ProtectionDomain.implies(ProtectionDomain.java:222)
            at java.security.AccessControlContext.checkPermission(AccessControlContext.java:354)
            at java.security.AccessController.checkPermission(AccessController.java:549)
            at com.sap.engine.services.keystore.impl.security.CodeBasedSecurityConnector.checkPermissions_readEntry(CodeBasedSecurityConnector.java:542)
    and also find heap log info
    -----------  H E A P   C H E C K  -----------
    Suspension of other threads succeeded.
    6 Java thread local allocation buffers currently in use.
    Scanning young generation space 314368K,   1% used [0x0a00020000000000, 0x0a00020000334838, 0x0a00020013300000)
    Scanning young generation space 157184K,   0% used [0x0a00020013300000, 0x0a00020013300000, 0x0a0002001cc80000)
    Scanning young generation space 157184K,   0% used [0x0a0002001cc80000, 0x0a0002001cc80000, 0x0a00020026600000)
    Scanning old generation space 2516992K,  21% used [0x0a00020026600000, 0x0a000200c0000000)
    Scanning permanent generation space 409600K,  99% used [0x0a000200c0000000, 0x0a000200d9000000)
    Checked the complete java heap.
    ---  N O   H E A P   C O R R U P T I O N  ---
    -----------  R E G I S T E R   R E G I O N S  -----------
    Register pc points to 0x09000000332ef3a8, which is not a known memory location
    Register lr points to 0x09000000332ef388, which is not a known memory location
    Register ctr points to 0x0900000033421bc0, which is not a known memory location
    Register r0 points to 0x0000000000000000, which is not a known memory location
    Register r1 points into the stack of JavaThread "HTTP Worker [@1753615133]" [_thread_in_vm (_call_back), id=25193, stack(0x000000011a5ef888,0x000000011a6ef888)]
    Dump of memory region around register r1 at 0x000000011a6e2a70
       0x000000011a6e29f0 00 00 00 01 1A 6E 2A 70 00 00 00 00 00 00 00 15 [.....n*p........]
       0x000000011a6e2a00 09 00 00 00 33 63 12 DC 09 00 10 00 A6 6A F9 60 [....3c.......j.`]
       0x000000011a6e2a10 00 00 00 00 12 4C 35 C0 0A 00 01 00 16 3D 60 78 [.....L5......=`x]
       0x000000011a6e2a20 09 00 00 00 33 FB 54 98 00 00 00 00 33 F4 90 28 [....3.T.....3..(]
       0x000000011a6e2a30 09 00 10 00 A6 4D 98 10 00 00 00 01 1A 6E 2A E8 [.....M.......n*.]
       0x000000011a6e2a40 00 00 00 00 00 00 00 00 00 00 00 00 15 A8 00 69 [...............i]
       0x000000011a6e2a50 00 00 00 00 15 A8 00 69 09 00 00 00 33 F4 90 38 [.......i....3..8]
       0x000000011a6e2a60 00 00 00 00 00 00 01 08 00 00 00 00 00 00 00 00 [................]
    => 0x000000011a6e2a70 00 00 00 01 1A 6E 2B 60 00 00 00 00 00 00 00 08 [.....n+`........]
    Register r2 points to 0x09001000a66af960, which is not a known memory location
    Register r3 points to 0x00000001188fa130, which is not a known memory location
    Register r4 points to 0x0a000100163d6098, which is not a known memory location
    Register r5 points to 0x0900000033f49038, which is not a known memory location
    Register r6 points to 0x0000000000000108, which is not a known memory location
    Register r7 points to 0x09001000a648c308, which is not a known memory location
    Register r8 points to 0x09001000a64cf2b4, which is not a known memory location
    Register r9 points to 0x0000000000000000, which is not a known memory location
    Register r10 points to 0x0000000000000000, which is not a known memory location
    Register r11 points to 0x0000000000000000, which is not a known memory location
    Register r12 points to 0x09000000332ef388, which is not a known memory location
    Register r13 points into the stack of JavaThread "HTTP Worker [@2116488621]" [_thread_in_native (_at_safepoint), id=25450, stack(0x000000011a6f4888,0x000000011a
    7f4888)]
    [error occurred during error reporting (dumping memory regions for register values), id 0xb
    Exception details: SIGSEGV at pc=0
    Problematic frame: v  ~StubRoutines::SafeFetch32 (sp=0x000000011a6e1240) (pc=0x0a00010000067b58)]
    hs_err_pid26214604.log: END

  • JPA @OneToMany Question

    Hello, there.
    How can I set OneToMany relationship in JPA, when child's identity(uniqueness) needs parent's primary key?
    Every books that I have only talk about the @PrimaryKeyJoinColumn with OneToOne mapping.
    Every books that I have only talk about the @OneToMany mapping with non-identifying relationships.
    Every google pages has no exception.
    @Entity public class Parent implements Serializable {
        @Id public int id;
        @OneToMany public Collection<Child> child;
    @Entity public class Child implements Serializable {
        @Id public int child_id;
        @ManyToOne Parent parent; // NOT FK, BUT PK ?????????????
    }

    This is something that JPA 1.0 does not handle too well. Hopefully JPA 2.0 will be easier.
    Basically you need to duplicate the id field and use a @PrimaryKeyJoinColumn. But some JPA providers have alternatives.
    See,
    [http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_Relationships]
    The OneToOne would be a ManyToOne for your example, but mainly the same.
    -- James : [http://www.eclipselink.org]

  • JPA query by entity/object ?

    I am trying to write an abstract API which dynamically assigns any Entity Class that needs to be persisted and retrieved using the Entity Manager.
    Saving into the database is not a problem, I just do entityManager.save(Class) and it works for any class that needs to be persisted.
    However, when querying for the object based upon the attributes, I want to avoid naming particular attributes and want to use the Entity class's attributes against itself for querying.
    For example, the client program will say something like this to query by name and age of a Person:
    -------calling (client) program: ---
    Person p = << get from UI, not saved yet, no Id but has all other attributes like name and age etc. >>
    List<Person> persons = dao.getAllThatMatch(p);
    --- end client Program --
    --- DAO class ---
    List<T> getAllThatMatch(T t) {  //note that expectation is that returned is a list of Object which is the same as the querying object
    List<T> entityList = em.someFinderMethod(t);
    //the someFinderMethod method should automatically query for all Person objects that match the attributes provided by the object of Person supplied as criteria
    //NOTE: there is no attribute mentioned extensively like name, age etc.
    return entityList ;
    -- end DAO class --
    Edited by: user7626479 on Feb 6, 2013 3:55 PM
    Edited by: user7626479 on Feb 6, 2013 3:55 PM

    Query by example is not included in the JPA standard, but it is possible to do with EclipseLink.
    See http://wiki.eclipse.org/EclipseLink/Examples/JPA/ORMQueries#Query_By_Example
    for how to use query by example with native EclipseLink queries. To execute a native query through JPA, you will need to call createQuery(DatabaseQuery query) on the org.eclipse.persistence.jpa;JpaEntityManager obtained from the javax.persistence.EntityManager instance by calling getDelegate() or unwrap.
    Best Regards,
    Chris

  • JPA OneToMany - ManyToOne Relation will not stored in DB

    Hi,
    I have the following problem:
    I have two tables:
    Logon
    -username
    -password
    -company_id
    Company
    -Name
    So Company has a OneToMany Relation to Logon and Logon a ManyToOne to company
    I have created the following Entity classes:
    class Logon{
        @ManyToOne()
        @JoinColumn(name = "COMPANY_ID",insertable=false, updatable=false)
        private Company company;
    class Company{
        @OneToMany(mappedBy="company", cascade=CascadeType.ALL)
        private Collection<Logon> logons = new Vector<Logon>();
    }And here is the code to insert the data.
            Logon logon = new Logon();
            Company company = new Company();
            logon.setCompany(company);
            company.addLogon(logon);
            EntityTransaction trans = em.getTransaction();
            trans.begin()
            em.persist(logon);
            em.persist(company);
            trans.commit();After that code I have an entry in table Logon and an entry in table Company.
    But the field company_id in table logon is always set to 0 and not to the company's id.
    The tables where not created from the entities. I have to work with an existing MySQL DB.
    Does someone has an idea?
    regards
    Gerald

    hi
    i am using 2 tables. In parent table i am giving
    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER,mappedBy="meterInfo")
    @JoinColumn(name="METERID")
    private List<MeterSub> meterSubs=null;
    subtable i am giving
    @ManyToOne(optional=false,targetEntity=com.nexant.mdm.dto.MeterInfoDTO.class)
    @JoinColumn(name="METERID",nullable=false, insertable=false, updatable=false)
    private MeterInfoDTO meterInfo;
    i am inserting the data by using the test class like this:
    MeterInfoDTO mi = new MeterInfoDTO();
    mi.setMeterID(4);
    MeterSub ms = new MeterSub();
    ms.setMeterInfo(mi);
    ms.setMeterData("meterData12");
    ms.setMeterSubPk("103");
    //ms.setMeterID(2);
    List<MeterSub> set = new ArrayList<MeterSub>();
    set.add(ms);
    mi.setMeterSubs(set);
    mi.setMeterName("Sample Meter NAme");
    mi.setMeterTimeZone("TZ");
    Last i am saving the data.
    while inserting the data its giving the following error:
    ORA-02291: integrity constraint (SYSTEM.SYS_C0010451) violated - parent key not found
    Error Code: 2291
    Call: INSERT INTO METERSUB (METERSUBPK, METERDATA, METERID) VALUES (?, ?, ?)
    means its not taking METERID from parent and its giving 0. thats why the error coming like this.
    Can any please help me to resolve this
    Thanks
    Shannu

  • 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

  • JPA and logging entity changes

    Good day!
    I need to log all entity property changes in scope of current transaction in j2ee application. I use Glassfish and JPA. Is there any way to do this?

    Filippo Tenaglia wrote:
    Hi all,
    I have a "simple" question:
    Should I create a class to manage entity manager and entity manager factory on JPA2?That question is far from complete, as the answer to this one is "depends on what you want to do!"
    Why do I ask that? Because I read on J2EE tutorial:
    With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction.
    To obtain an EntityManager instance, inject the entity manager into the application component:
    @PersistenceContext
    EntityManager em;
    Given this information...
    I'm using JSF2, JPA2, JTA and Glassfish3.1 on the NetBeans 7.0.1.That answer to your question is "NO", because you have a container available to you that can do the work (Glassfish). It makes no sense using Glassfish and then purposely ignoring the features it has to offer.
    Lets get back to basics: you are doing something wrong here. You have to figure out what, you can only do that if you keep studying and getting a more complete understanding. If you are having trouble realizing that, perhaps you should start over without the help of any wizard at all; wizards are only useful when you are already experienced, right now the fact that code is generated is hindering you a lot because you will have a strong impulse to believe there can be no mistake; unfortunately there is no such safety net. The fact that you used the word "weird" is enough proof of this by the way. There is nothing weird here, just a mistake being made that has to be corrected.
    And for the future: what IDE (Netbeans in your case) you use to develop really makes absolutely no difference at all. What is more interesting is which version of Java your are using, which can likely be Java 6 or Java 7 nowadays.

  • SelectBooleanCheckbox  and  entity deletion in DB

    Hi,
    In HtmlDataTable i am displaying entities from DB , and i am associating a checkBox to each entity(dynamic for n nuber of entities), when user select on a check box that corresponding entity i have to capture in Backing bean to make deletion.
    There is no relation ship between checkbox and entity displayed in data table( i can't associate coz im getting Data Layer from another person). is there any way to do this .

    im getting this excetion when doing like u said in jsf page
    javax.servlet.ServletException: javax.servlet.jsp.JspException: java.lang.IllegalArgumentException: argument type mismatch
    before my data table
    <h:dataTable id="my_docs" value="#{ManageDocument.listOfDocuments}" binding="#{ManageDocument.markedForDeletion}" var="myDocItem" bgcolor="silver">
             <h:column>
                <f:facet name="header"> <h:outputText value="Select" />
                </f:facet>
                <h:selectBooleanCheckbox>
                </h:selectBooleanCheckbox>
             </h:column>
             <h:column>
                <f:facet name="header">
                 <h:outputText value="File Name" style="font-size:smaller;width:150px;" />
               </f:facet>
               <h:outputText value="#{myDocItem.fileName}" />
             </h:column>
             <h:column>
              <f:facet name="header">
                <h:outputText value="File Size" style="font-size:smaller;width:150px" />
              </f:facet>
              <h:outputText value="#{myDocItem.fileSize}" />
             </h:column>
             <h:column>
              <f:facet name="header">
                <h:outputText value="Date Uploaded" style="font-size:smaller;width:150px"/>
              </f:facet>
                <h:outputText value="#{myDocItem.dateFileUploaded}" />
             </h:column>
          </h:dataTable>after ur suggesion
    <h:dataTable id="my_docs" value="#{ManageDocument.listOfDocuments}" binding="#{ManageDocument.markedForDeletion}" var="myDocItem" bgcolor="silver">
             <h:column>
                <f:facet name="header"> <h:outputText value="Select" />
                </f:facet>
                <h:selectBooleanCheckbox binding="#{uidocument.selected}">
                </h:selectBooleanCheckbox>
             </h:column>
             <h:column>
                <f:facet name="header">
                 <h:outputText value="File Name" style="font-size:smaller;width:150px;" />
               </f:facet>
               <h:outputText value="#{myDocItem.fileName}" />
             </h:column>
             <h:column>
              <f:facet name="header">
                <h:outputText value="File Size" style="font-size:smaller;width:150px" />
              </f:facet>
              <h:outputText value="#{myDocItem.fileSize}" />
             </h:column>
             <h:column>
              <f:facet name="header">
                <h:outputText value="Date Uploaded" style="font-size:smaller;width:150px"/>
              </f:facet>
                <h:outputText value="#{myDocItem.dateFileUploaded}" />
             </h:column>
          </h:dataTable>and in backing table the Binding with HtmlDataTable.
    before ur suggesion my dataTable value attribute is value="#{ManageDocument.listOfDocuments}" ,
    which arrayList of Documents
    after ur suggesion it is arrayList of MyDcouments

  • How to set JPA when related entity do not want to CASCADE

    Here is the case: weblogic 11g, EcliplseLink
    in orm.xml, there is one snippet about the relationship(many to many) for two entities.
    <many-to-many name="supportedHostTypes"
                        target-entity="com.gogog.server.lamp.model.impl.collection.HostTypeEntity"
                        fetch="EAGER">
                        <join-table name="HOST_COMPATIBILITY">
                             <join-column name="Model_ID" />
                             <inverse-join-column name="HOST_TYPE_ID" />
                        </join-table>
    </many-to-many>
    Because i do not set the cascade attributes, when i run Junit test, there is an error: During synchronization a new object was found through a relationship that was not marked cascade PERSIST:[email protected]b.
    Actually, for target table HostType, i have the pre-loaded test data for this table. It does not need to insert it any more. If i set cascade.all attributes, of course, there will be integrity error happens.
    This snippet can work in glassfish with toplink, and now i need to migrate to weblogic, and the error above happens.
    Could any one has some idea how to config it for this case, thanks.

    Hello,
    This error will occur if the existence check for the HostTypeEntity is returning false. The existence check is explained at:
    http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#How_to_Use_the_.40ExistenceChecking_Annotation
    It states that by default, tje existence check is set to check the database implying that the HostTypeEntity with that identity doesn't exist in the database. Some questions if you are sure it does exist; what is the Entities id, what version of EclipseLink are you using and have you set any of the existence checking options anywhere?
    Things to try would be explicitely setting the check_database option or reading in and using the managed instance as the reference instead.
    Best Regards,
    Chris

  • Using JPA Entity-Objects defined in other EJB-Development Component

    Hello Community,
    I'm working on a Java-Application on NW CE 7.1, using JEE5 Beans in the Business-Logic-Layer and WebDynpro/Java in the UI-Layer.
    I designed a Bean for working with data, stored in a database-table of the system-database.
    For that addtionally i created a class, representing the Entity-Object, in the same Development-Component of Type EJB 3.0.
    It looks like this:
    @NamedQueries ({
         @NamedQuery (name="findAllSdCust", query="SELECT c from SdCust c ORDER BY c.kdnr"),
         @NamedQuery (name="findSdCustByKdnr", query="SELECT c from SdCust c WHERE c.kdnr = :kdnr"),
         @NamedQuery (name="findSdCustByIlnnr", query="SELECT c from SdCust c WHERE c.ilnnr = :ilnnr")
    @Entity
    @Table(name="ZKALL_SD_CUST")
    public class SdCust implements Serializable {
         @Id
         @TableGenerator (name="idGenerator", table="ZKALL_ID_GEN", pkColumnName="GEN_KEY", valueColumnName="GEN_VALUE", initialValue=100)
         @GeneratedValue (strategy=GenerationType.TABLE, generator="idGenerator")
         private long id;
         private String name;
         private String lname;
         private String kdnr;
         private String ilnnr;
         private long connid;
         private long cnt;
         @Version
         private long version;
          Constructor, Getter and Setter methods follow here
    The corresponding bean looks like this
    @Stateless(name="SdCustBean")
    public class SdCustBean implements SdCustLocal {
         @PersistenceContext (unitName="xyz")
         private EntityManager em;
         public SdCust getSdCustByKdnr (String kdnr)
              SdCust result = new SdCust();
              // List<Manufacturer> resultList = new ArrayList<Manufacturer>();
              Query  myQuery = em.createNamedQuery("findSdCustByKdnr");
              myQuery.setParameter("kdnr", kdnr);
              result = (SdCust) myQuery.getSingleResult();
              return result;
         public void setEM (EntityManager iem)
              em = iem;
           // other methods .....
    After that i created a new Development-Component of Enterprise Application-Type and added above DC to this EAR-DC. I also supplied the nessecary descriptor-files/Enries in EJB-DC and EAR-DC.
    When now using this bean from WebDynpro with the Web-Dypro EJB-Model-Import everything works fine.
    The bean returns the desired object(s).
    But now i created a new DC of type EBJ 3.0
    This DC contains a Message Driven Bean. That MDB is a Job-Bean which i want to schedule. That  Bean uses JRA to connect to an SAP-Abap-System to read some Data and should use JPA to insert/upate/delete the read data in the Database. This should work as a simple replication for my application.
    I assigned that EJB-DC containing the MDB to a new EAR-DC together with job-definition-xml and the neccessary entries in deployment-descriptors.
    After deploying i see the corresponding job-defition in the NW scheduler using the administrator-views.
    I'm also able to schedule the job and it executes fine. Connecting to SAP-Abap System also works fine using JRA.
    But JPA does not work!!!!!
    I created an dependency from my EAR-DC containing the Job EJB-DC and to the EJB-DC containing the Entity-Class.
    I tried three diferent things to get i running, but all of them failed.
    1.)
    The part  looks like:
    public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
      @EJB SdCustBean mybean;
       public void onJob(JobContext ctx) throws Exception {
            SdCust sdCust = mybean.getSdCustByKdnr (mykdnr);
    Compiles fine. But this fails because the Data is stored in the system-database. The exception says, that i have to use a datasource which supports 2-Phase commit. I know, that i could possibly solve this problem by annotation the Method getSdCustByKdnr with the Annotation for the Transaction-Manager to use REQUIRES_NEW Transaction. But i dont want to generally annotate my methods this way.
    2.)
    This part looks like this
    public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
    @PersistenceContext (unitName="xyz")
    private EntityManager em;
       public void onJob(JobContext ctx) throws Exception {
         SdCust cust = new SdCust();
         Query  myQuery = em.createQuery("SELECT c from SdCust c WHERE c.kdnr = :kdnr");
         myQuery.setParameter("kdnr", dbkdnr);
         cust = (SdCust) myQuery.getSingleResult();
    This also results in a runtime-exception because the entity-Manager cant resolve SdCust from the Query as an Object. The Exception is:
    java.lang.IllegalArgumentException: line 1: Abstract Schema Type 'SdCust' doesn't exist
    SELECT c from SdCust c WHERE c.kdnr = :kdnr
    3.) and last try so far:
    public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
    @PersistenceContext (unitName="xyz")
    private EntityManager em;
       public void onJob(JobContext ctx) throws Exception {
         SdCustBean custBean = new SdCustBean();
         custBean.setEM(em);
         SdCust cust = custBean.getSdCustByKdnr(kdnr);
    In this example i use the Bean from the beginning not as a bean itself but as a normal class. that class has an addtional Method setEM to set the Entity-Manager (which is injected when using the class as a bean)
    In that way i got the exception, that the named Query "findSdCustByKdnr" cannot be found by the entity-manager.
    It seems to me, that i can access the class, but that all annotations belonging to JPA for that class are not recognized.
    Does anybody can give me a hint to solve this problem? Did i forgot something important?
    best regards
    matthias hayk
    Edited by: Matthias Hayk on Feb 5, 2009 9:38 AM

    I was already on wright trace.
    My class "SdCust" was not recognized by the Entity-Manager as an Entity-Class.
    This relies on the storage of the entity-class and where the Entity-Manager looks for entity-classes.
    By default it seems to look for all classes in the same jar file. thats the reason why everything works fine when the using bean and the entity-class are in the same project.
    In my last case, the using bean is in another  development-component and so also in anohter jar file. in this case the entity-manager must be told where to find entity-classes.
    this is done in the persistence.xml file.
    i added the line
    <jar-file>xxx.yyy.com~mdata_beans.jar</jar-file>
    underneath the <persistence-unit>-tag.
    This works.
    regards
    Matthias Hayk

  • More on JPa delete

    have some time today, so try JPA anagin I get delete by use NativeQuery
    but it suppose have two other ways
    option one
    I hard code it and I get
    1)Query query=em.createQuery(" delete FROM student p WHERE p.userId =1570");
    I get Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
    the student is a parent table , in normal sql I can't delete from the children table , but if I delete from the parent table all relate records in child just go , why I can't use this ideal in JPa??
    option two
    public class StudentFormService {
    protected EntityManager em;
    public StudentFormService(EntityManager em) {
    this.em = em;
    public void removeStudent(int id) {
    Student emp = findStudent(id);
    if (emp != null) {
    em.remove(emp);
    public Student findStudent(int userId) {
    return em.find(student.class, userId);
    then in my servlet How should I call the remove in servlet
    I have
    Student SD =studentDBO.findStudent(deleteId);
    em.getTransaction().begin();
    SD=studentDBO.removeStudent(deleteId);*/
    not ideal how to continue

    Thank you for the reply,
    just have little time come back here ! I get the *.NullPointerException*
    Student SD=studentDBO.findStudent(deleteId);
    I checked
    String temp=Click.substring(2,position); //ok
    int deleteId = Integer.parseInt(temp);//ok
    // In Student class I have
    public class StudentFormService {
    private EntityManager em;
    public StudentFormService(EntityManagerFactory emf) throws Exception {
    em =emf.createEntityManager();
    public void removeStudent(int id) {
    Student emp = findStudent(id);
    if (emp != null) {
    em.remove(emp);
    public Student findStudent(int userId) {
    return em.find(Student.class, userId);
    What I miss??
    by the way the cascade between my table is work .
    Thank You!
    The .NullPointerException Point to*
    Student SD=studentDBO.findStudent(deleteId);
    Edited by: Hjava on Jan 10, 2011 5:42 PM
    Edited by: Hjava on Jan 10, 2011 5:43 PM

  • 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

Maybe you are looking for