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]

Similar Messages

  • General JPA query question

    Hello world,
    I'm new to JPA 2.0 and there are few things I don't understand.
    BTW: I can't figure out the keywords to search for this question, so please pardon me if it's one of the most asked.
    Using the Preview, I've seen that alignment went straight to Hell, so I tried to make this as readable as I could using pipes in place of white spaces in the result sets.
    I have a couple of tables:
    CUST table (for customers):
    CUST_ID (pk, integer)
    CUST_NAME (varchar)
    ORD table (for orders):
    ORD_ID (pk, integer)
    ORD_STATUS (char) can be: N for new, S for shipped, D for delivered
    CUST_ID (fk, integer)
    The relationship is, of course, a "one to many" (every customer can place many orders).
    Content of the tables:
    CUST_ID|CUST_NAME
    1|elcaro
    2|tfosorcim
    3|elppa
    ORD_ID|ORD_STATUS|CUST_ID
    2|N|1
    3|N|1
    4|N|1
    5|S|1
    6|S|1
    7|D|1
    8|D|1
    9|D|1
    10|D|2
    11|N|2
    12|S|3
    13|S|3
    Here's how I annotated my classes:
    Customer.java:
    @Entity(name = "Customer")
    @Table(name = "CUST")
    public class Customer implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "CUST_ID")
    private Integer id;
    @Column(name = "CUST_NAME")
    private String name;
    @OneToMany(mappedBy = "customer")
    private List<Order> orders;
    // Default constructor, getters and setters (no annotations on these)
    Order.java:
    @Entity(name = "Order")
    @Table(name = "ORD")
    public class Order implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "ORD_ID")
    private Integer id;
    @Column(name = "ORD_STATUS")
    private Character status;
    @ManyToOne
    @JoinColumns
    @JoinColumn(name = "CUST_ID", referencedColumnName = "CUST_ID")
    private Customer customer;
    // Default constructor, getters and setters (no annotations on these)
    Everything works just fine, the following JPQL query yields the results I expected:
    select c from Customer c
    it returns three objects of type Customer, each of which contains the orders that belong to that customer.
    But now, I want to extract the list of customers that have orders in status 'N', along with the associated orders (only the status 'N' orders, of course).
    Back in the good ol' days I would have written an SQL query like this:
    select c.cust_id, c.cust_name, o.ord_id, o.ord_status
    from cust c
    inner join ord o on (o.cust_id = c.cust_id)
    where o.ord_status = 'N'
    and it would have returned the following result set:
    CUST_ID|CUST_NAME|ORD_ID|ORD_STATUS
    1|elcaro|2|N
    1|elcaro|3|N
    1|elcaro|4|N
    2|tfosorcim|11|N
    The following JPQL query, however, doesn't yield the expected results:
    select distinct c from Customer c join c.orders o where o.status = 'N'
    it returns the correct set of customers (customer 'elppa' doesn't have any status 'N' order and is correctly excluded), but each customer contains the full set of orders, regardless of the status.
    It seems that the 'where' clause is only evaluated to determine which set of customers has to be extracted and then the persistence provider starts to navigate the relationship to extract the full set of orders.
    Thinking a little about it, I must admit that it makes sense.
    I then tried out another JPQL query:
    select c, o from Customer c join c.orders o where o.status = 'N'
    this JPA query yields results that are similar to the ones produced by the previous SQL query: each result (4 results as expected) is a 2-object array, the first object is of type Customer and the second object is of type Order. But, again, the objects of type Customer contain the full set of related orders (as I expected, this time). Not to mention the fact that now the orders are not contained in the Customer objects, but are returned separately, just as in an SQL result set.
    Now the question is:
    Is it possible to write a JPA query that filters out, not only the customers that don't have an order in status 'N', but the related orders (fetched during relationship navigation) that are not in status 'N' as well?
    What I'd like to be able to get is a 2-customer result where each customer contains only its status 'N' orders.
    I read the Java EE 6 Tutorial and one of the examples (the Order Application) has a schema that is similar to mine, but I couldn't find a query like this (in the downloaded source code).
    Although I think the above is standard behavior, I use an Oracle Weblogic 12c server (through its Eclipse adapter) and the persistence provider appears to be EclipseLink.
    Thanks in advance.
    Best regards,
    Stefano
    Edited by: user11265230 on 17-apr-2012 14.11

    Hello,
    When returning an entity from JPQL, it gives you the entity as it is in the database. Your "select distinct c from Customer c join c.orders o where o.status = 'N'" is asking for all customers that have an order with a status of 'N', so that is what it gives you. There is no condition to filter anything on the relationship when building the Customer object in JPA - doing so would mean returning a managed entity that does not reflect what is in the database. This would affect other queries, since JPA requires that queries return the same instance of an entity regardless of the query that is used to bring it back. So a query using your "where o.status = 'N'" would cause conflicting results when used with a query using "where o.status = 'Y'". And these queries would make the EntityManager unable to determine what has changed on the returned objects.
    EclipseLink does have the ability to filter over relationships, it is just not available through standard JPA and I would strongly discourage it. Instead of querying for Customers, why not change the query to get Orders instead -
    "select o from Customer c join c.orders o where o.status = 'N'". Assuming Orders have a ManyToOne back reference to their Customer, this will mean you do not need to travers the Customer-> order relationship. If using
    "select c, o from Customer c join c.orders o where o.status = 'N'"
    I am not sure why you would use the orders from the returned customers instead of the orders returned in the results though.
    You could also return "select c.id, c.name, o.id, o.status from Customer c join c.orders o where o.status = 'N'" which is the equivalent of what you would get from the SQL you initially posted.
    Regards,
    Chris

  • Simple JPA - JSF question

    Welcome!
    I Have simple question regarding updating JPA entities from JSF application
    One option is to directly invoke entity manager code from JSF managed bean action, but in this case we must explicitly deal with transactions (and we don't get other EJB benefits).
    Other approach is to create EJB as a stateless session bean. And delegate all the operations on entities to the EJB. In this case container create transactions for us.
    Please correct me if I wrongly understand this topic.
    My key question is how to update entity bean, which I have persiteted earlier. I assume it's illegal to issue manager .find method in EJB class, return managed entity as an object to JSF backing been and then modify it. Normally entity bean should be managed, but in this case there is no transaction support in JSF backing bean and hence we cannot modify the object directly.
    I assume that correct way is to detach entity in EJB, pass this object to JSF backing bean. In this case entity will not be managed, then edit it in JSF and finally update in EJB by .merge method.
    I assume multi-user environment (currently I am using glassfish if it does matters)
    Best regards
    Pawel

    Thanks for responding r035198x (this place has some memorable usernames :) ).
    You were absolutely right about flagging me up for not catching the exception (at the time I didn't know how to handle exceptions as im still learning). I am now using:
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error deleting record: "+ex.getMessage()));and am now getting the following when pressing the delete button:
    Error deleting record: Internal Exception: java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'MBUSER' caused a violation of foreign key constraint 'USERPOST_OWNER_ID' for key (4). The statement has been rolled back. Error Code: -1 Call: DELETE FROM MBUSER WHERE (ID = ?) bind => [4] Query: DeleteAllQuery(name="messageboard.entity.MBUser.deleteUser" referenceClass=MBUser sql="DELETE FROM MBUSER WHERE (ID = ?)")
    This is probably getting out of the realm of JSF, but in case your interested I can delete a user which does not have any child posts or threads (this is a messageboard), but if that user owns any threads or posts then it shows the above error. At this stage I am guessing its because I am not deleting joined child objects which are in persistence, and therefore will not allow the parent to be deleted without first the children being deleted. I was hoping that the cascade tag in the @OneToMany annotation would do it for me, but that doesn't seem to be the case:
        @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
        private List<UserPost> ownedPosts = null;
        @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
        private List<UserThread> ownedThreads = null;Therefore I guess i'll have to construct a NamedQuery a bit more complicated than the current one im using. Still, at least im making progress :) Thanks...

  • 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 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.

  • 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 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

  • 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

  • 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

  • Newbie Question--EJB 3.0/JPA deployment to Sun AS 9.0 not working

    I am new to EJB 3.0 and JPA technologies, so please excuse me for asking such a rudimentary question.
    I am developing a simple Java EE application running on Sun Application Server version 9.0.01, buuild b02-p01. I used the windows installer to set everything up for the server. I am using JDK 1.6.0.02
    I am using Eclipse Europa to develop the application. I have an Enteripse application that includes a EJB project and a Web project. I am using ANT to build the application. In the Web project I have placed an index.html file to ensure I can hit the web application berfore I go any farther. The web project has two servlets. In one servlet, I called the Remote Interface for the EJB and performed some operation. This reference is made using annotations. The EJB project has developed several persistence classes and one EJB with a Remote interface. Everything seems to be building correctly. I have used annotations to handle the EJB and Entity portion of the EJB project.
    When I deploy the application to the application server, I see no errors in the server log. As a matter of fact, the log file states the ear deployed correctly. When I go look at the admin console, I am not seeing any errors either.
    In my my-ejb-jar file I do not include a sun-ejb-jar.xml and the war file does not include a sun-web.xml. The sun-application.xml is not in the ear file. The ear file has the application.xml, The sever is generating the ejb-jar.xml from the annotations and creating the JNDI tree. The war file has the web.xml file.
    When trying http://localhost:7182/MyWebContext/index.html for hitting the Web container using my IE 6.0 browser I receive this:
    I am not geeting any errors from this URL.
    Any suggestions would be greatly appreciated.
    Thank you for taking the time to read my post.
    Russ

    Check the property names for configuring TopLink's internal connection pool. All of the JDBC property names should be prefixed with toplink.
    Refer to the TopLink JPA extensions guide for more information.
    http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-extensions.html
    Doug

  • ADF and JPA  question

    I tried the example in 'Build a Web Application with JDev 10g Using EJB, JPA and JSF and it worked.
    This example is based on two tables. Now I have 6 tables. Tables 1,2 and 3 are joined to populate an ADF table form and tables 1,2,4,5 and 6 are joined to populate another ADF form.
    My question is: should I use JDev to generate all 6 entity EJBs or rather create two Oracle views for each of these joins and get JDev to generate EJB for each of these views?
    Also, how can I customize the annotated queries generated by JDev? I would like to have all the native SQLs to be in separate XML files. Should I use XML files generated by JDev or create a new XML file? Is there an example of how to do that?

    Hello,
    I read somewhere JPA supports external XML native SQL queries and apparently these queries override named queries in entity annotations. Assuming this is true, would that be the preffered way (both queries, 1-2-3 join and 1-2-4-5 join have one input parameter each so the database views would have to be parametrized in that case)? And how should I access these XML based queries from inside the code?
    Also, what queries are generated by JDev JPA when 6 tables are selected? Are all combinations based on foreign keys generated or just table (entity) and its directly related tables?
    Thanks,
    Sale

  • JPA Toplink OneToMany - ManyToOne Relation will not stored in DB

    Hi
    I am getting the error while inserting the data into Two tables by using the ManyToOne realation.
    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

    Hi Tolls,
    i have one doubt while using the JPA Toplink.
    In my table it have primary key with 2 columns menas composite key acting as a primary key.
    So how i have to declare these fields in POJO class
    and also how to represent these Class and primary key in ONe to One realtion or Many to one relation.
    @ManyToOne(optional=true,targetEntity=com.nexant.mdm.dal.eo.Capability.class)
    @JoinColumn(name="CapabilityID",nullable=false, insertable=true, updatable=false)
    private Capability capability;
    here Capabity is the POjo calss and CapabilityID is the primary key , if in place of CapabilityID i have 2 keys acting as a primary key.
    So how can i represent this?
    waiting for ur valuble response :)

  • Toplink question about JPA/EJB3

    Hi chers ;)
    When you create a new entity, an associantion has a "list" of associed item, like this:
    @OneToMany(cascade={CascadeType.PERSIST}, mappedBy = "trecho")
    private List<CidadeTrecho> cidadeTrechoList;
    When I call the method trecho.getCidadeTrechoList(), Toplink will do a simple automatic select in database to get all objects associated with this object (in that scene, will get all CidadeTrecho who's has a associatin with this trecho)
    Toplink fine's console will output things like this:
    TopLink Fine]: 2007.01.22 05:43:57.875--ServerSession(9261456)--Connection(28205253)--Thread(Thread[HTTPThreadGroup-5,5,HTTPThreadGroup])--SELECT IDCIDADETRECHO, ORDEM, CD_TRECHO, CD_PAIS, CD_ESTADO, CD_CIDADE FROM RODO_CIDADETRECHO WHERE (CD_TRECHO = ?)
         bind => [101]
    My questions is: Have a mode to change this select query to find the list of associations? I want change only a little thing, I want only add a "order by" statement at end of thist query.
    Anybody can help me?
    Reggards

    You can add an @OrderBy annotation to control the select.
    @OneToMany(cascade={CascadeType.PERSIST}, mappedBy = "trecho")
    @OrderBy("foo ASC")
    private List<CidadeTrecho> cidadeTrechoList;--Shaun                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Crucial question about Toplink Essentials JPA in OC4J 10.1.3.3

    Hi all!
    I'm developing an EJB 3.0 service which will be deployed to an OracleAS 10.1.3.3 and even after I've read lots of docs and articles, I still got an unanswered question:
    I know JPA leaves concurrent data access to the application's responsibility (or the vendor implementation's), that Oracle explicitly recommends using @Version to enable JPA's standard optimistic locking and also that Toplink Essentials JPA is OC4J's default persistence provider for EJB 3.0 modules. Considering this last important fact, what will be the default locking mode assumed by Toplink Essentials if I don't use @Version?
    Looking at Toplink Essentials JPA extensions doc preview for OC4J 11g (http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-extensions.html), I found that I can use @OptimisticLocking to define the locking policy when defining an entity and use a lock type that doesn't require me to define a @Version field. But that annotation doesn't exist in version 10.1.3.3. Is there another way to define locking policy and type (on global or per entity basis) in version 10.1.3.3?
    Any help will be really welcome!
    TIA,
    Eduardo.

    Quoting Mr. Doug Clarke:
    "Eduardo,
    The only way to ensure that concurrent writers to the database don't overwrite one another is to either lock optimistically or pessimistically (i.e.: SELECT ... FOR UPDATE). Both of these approaches are supported by Oracle TopLink as well as TopLink Essentials. If neither is used then no locking is applied and the last writer will succeed leaving the database in a potentially corrupted state. Also note that minimal writes are used so each thread only updates the columns it changes so the resulting state of the database could be a combination of the two concurrent writes. Users of JPA are strongly recommended to use optimistic locking to ensure concurrent writing scenarios do not produce unexpected result in their database.
    Our JPA implementation in 10.1.3.3 is TopLink Essentials which is the Open Source references implementation of JPA derived from Oracle TopLink developed in GlassFish. This edition of TopLink only has support for JPA's @Version annotation as you noted. This approach does require a dedicated column in the database table for comparison on write to detect changes made since this thread's version of the original data was read.
    In Oracle TopLink 11g we have implemented JPA 1.0 in our product. This means that full capabilities of TopLink are available through JPA along with some custom annotations to assist in configuring them. This includes the additional optimistic locking policies provided for schemas where adding version columns is not possible. These capabilities are not included in TopLink Essentials. Customers can access these capabilities in the 11gR1 technology previews as well as in the new Eclipse Persistence Services Project "EclipseLink" which is the full functionality of Oracle TopLink developed as an open source solution. Oracle TopLink 11g and its distribution of EclipseLink are not yet available in a supported release."

  • SOS!! Simple yes/no question about JPA...

    Hello,
    I have the following environment and requirements:
    -Tomcat 5.5 (no ejb container)
    -Latest version of Hibernate
    -JSF 1.1
    -A requirement to use JPA
    -I must use the query cache and the second-level cache
    My question is as follows:
    What is the best solution?
    Solution 1.
    ONE EntityManagerFactory stored in the ServletContext for use by all of my web app users generating MULTIPLE INSTANCES of EntityManagers. (would this allow me to use the query cache?)
    Solution 2.
    ONE EntityManagerFactory and ONE EntityManager stored in the ServletContext for use by all of my web app users.
    Thanks in advance,
    Julien.

    Regarding caching, what exactly are you referring to
    by "query cache"? Are you saying you
    plan to execute the same query multiple times but
    you'd like the underlying persistence manager
    to avoid trips to the actual database? Whether the
    query is executed by an actual database
    access or is fulfilled through some JVM-local cache
    is not controlled by the spec. Most implementations
    do allow for such caching but the behavior is
    persistence-provider specific.Yes. I am actually using hibernate behind the scenes as my persistence framework.
    I'd suggest looking at the presentation from last
    year's JavaOne called "Persistence In the
    Web Tier"
    http://developers.sun.com/learning/javaoneonline/2006/
    webtier/TS-1887.pdfI am going to have a look at that.
    Thanks again.
    Julien.

Maybe you are looking for

  • Create Windows 8 Installer for Y500

    I have a client that has asked me to help him with his new laptop.  He's ordered a Y500 and sperately ordered a 512GB SSD.  I need to install the SSD, then install / transfer his data and apps from another drive. Can I create Windows 8 USB install me

  • Sccm 2007 Management 6 - Deployments that contain an update list comes up blank.

    Hi Guys, I'm not sure what's going on completely here.  I'm trying to do my compliancy report for the month using the update list that was deployed for all servers.  I'm using the correct list, but when I run the report, it comes up with nothing foun

  • Mexico / ipad usage?

    Going to Mexico, Cabo, is there a "sim card" option like Europe (Italy, Vodafone - $.93/day)?

  • ZEN Stone Plus 4GB is terrible, I throw mine a

    I bought one, but it has problem charging its battery to the full. I use my PC usb port to charge it. Everytime it will charge up to just 0% of the battery and the led status indicate it is full and the player becomes very hot. I sent it for repair t

  • Applescript/automator

    I've just recently started messing with Automator, since the scirpts just hurt my brain, but is there a way that I can create a script/action and attach it to a folder so that whenever a file is placed therein, the (automator) action will be performe