Onetomany manytoone bidrectional mapping

How do I accomplish this;
Here is my code. I have both a onetoone where 1 telephone number is mandatory for 1 customer.
But the customer can have many telephone numbers other than the mandatory one.
Customer.java
package testonetoone;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
@Entity
@NamedQueries( { @NamedQuery(name = "Customer.findAll", query = "select o from Customer o") })
public class Customer implements Serializable {
@Id
@Column(name = "CUSTOMER_ID", nullable = false)
@GeneratedValue(generator = "CustomerSeq")
@SequenceGenerator(name = "CustomerSeq", sequenceName = "ISATS.CUSTOMER_SEQ", allocationSize = 1)
private BigDecimal customerId;
@Column(name = "CUSTOMER_NAME", length = 20)
private String customerName;
// @Column(name="PHONES_ID", nullable = false)
// private String phonesId;
@OneToOne(optional = false, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "PHONES_ID", unique = true, nullable = false, updatable = false)
private Phones telephoneNumber;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "customerTelephones", orphanRemoval = true, fetch = FetchType.EAGER)
// @JoinColumn(name = "PHONES_ID", unique = true, nullable = false, updatable = false)
private Collection<Phones> telephoneNumbersList = new ArrayList<Phones>();
public Customer() {
public BigDecimal getCustomerId() {
return customerId;
public void setCustomerId(BigDecimal customerId) {
this.customerId = customerId;
public String getCustomerName() {
return customerName;
public void setCustomerName(String customerName) {
this.customerName = customerName;
public void setTelephoneNumber(Phones telephoneNumber) {
this.telephoneNumber = telephoneNumber;
public Phones getTelephoneNumber() {
return telephoneNumber;
public void setTelephoneNumbersList(Collection<Phones> telephoneNumbersList) {
this.telephoneNumbersList = telephoneNumbersList;
public Collection<Phones> getTelephoneNumbersList() {
return telephoneNumbersList;
Phones.java
package testonetoone;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
@Entity
@NamedQueries( { @NamedQuery(name = "Phones.findAll", query = "select o from Phones o") })
public class Phones implements Serializable {
// @Column(name = "CUSTOMER_ID")
// private BigDecimal customerId;
@Id
@Column(name = "PHONES_ID", nullable = false)
@GeneratedValue(generator = "PhonesSeq")
@SequenceGenerator(name = "PhonesSeq", sequenceName = "ISATS.PHONES_SEQ", allocationSize = 1)
private BigDecimal phonesId;
@Column(name = "PHONE_NUMBER", length = 20)
private String phoneNumber;
@OneToOne(optional = false, cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "telephoneNumber")
// @JoinColumn(name = "CUSTOMER_ID", unique = true, nullable = false, insertable = false, updatable = false)
private Customer customer;
@ManyToOne(optional = false,cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "CUSTOMER_ID", nullable = false)
private Customer customerTelephones;
public Phones() {
// public BigDecimal getCustomerId() {
// return customerId;
// public void setCustomerId(BigDecimal customerId) {
// this.customerId = customerId;
public BigDecimal getPhonesId() {
return phonesId;
public void setPhonesId(BigDecimal phonesId) {
this.phonesId = phonesId;
public String getPhoneNumber() {
return phoneNumber;
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
public void setCustomer(Customer customer) {
this.customer = customer;
// @JoinColumn(name = "CUSTOMER_ID", unique = true, nullable = false, insertable = false, updatable = false)
public Customer getCustomer() {
return customer;
public void setCustomerTelephones(Customer customerTelephones) {
this.customerTelephones = customerTelephones;
public Customer getCustomerTelephones() {
return customerTelephones;
testonetoone.java
package testonetoone;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
public class TestOneToOne {
public TestOneToOne() {
super();
public static void main(String[] args) {
TestOneToOne testOneToOne = new TestOneToOne();
EntityManager em = null;
em = Persistence.createEntityManagerFactory("TestOneToOne", new java.util.HashMap()).createEntityManager();
// 1) Create customer, create phones, set add mapping
// EntityManager em = emf.createEntityManager();
Phones p = new Phones();
p.setPhoneNumber("5716120001");
Customer c = new Customer();
c.setCustomerName("Toyota");
p.setCustomer(c);
c.setTelephoneNumber(p);
Phones p2 = new Phones();
p2.setPhoneNumber("5716120002");
List<Phones> telephoneNumbersList = new ArrayList<Phones>();
telephoneNumbersList.add(p2);
p2.setCustomer(c);
c.setTelephoneNumbersList(telephoneNumbersList);
// Query query = em.createQuery("SELECT e FROM CUSTOMER e");
// List<Customer> list = (List<Customer>) query.getResultList();
// System.out.println(list);
// query= em.createQuery("SELECT d FROM PHONES d");
// List<Phones> dlist = (List<Phones>) query.getResultList();
// System.out.println(dlist);
try {
em.getTransaction().begin();
em.persist(c);
em.flush();
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}

This is not a bidirectional relationship (well, the OneToMany and ManyToOne form one), it is a circular reference. I am not sure how you can possibly do this in the database without making one of the foreign key fields nullable, or delaying constraint checking until the transaction completes.
Which ever relationship you make nullable will have to be set after the persist calls are flushed to the database. If you are able to delay constraint checking in the database, this isn't neccessary.
Best Regards,
Chris

Similar Messages

  • Querying tables mapped by oneToMany, manyToOne

    Hi,
    I have two classes, customers and customerinfo, both mapped to a database. There is a cust_id field in customers which is a primary key and a cust_id field in customerinfo which is a foreign key referencing the cust_id in customers.
    Relevant code in each class is as follows:
    Customers Class:
    @Id
    @Column(name = "cust_id", nullable = false)
    private Integer custId;
    @Column(name = "code", nullable = false)
    private String code;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "custId")
    private java.util.List <NewDBTest.Persistence.CustomerInfo> customerInfoList;
    public Integer getCustId() {
    return this.custId;
    public void setCustId(Integer custId) {
    this.custId = custId;
    public java.util.List <NewDBTest.Persistence.CustomerInfo> getCustomerInfoList() {
    return this.customerInfoList;
    public void setCustomerInfoList(java.util.List <NewDBTest.Persistence.CustomerInfo> customerInfoList) {
    this.customerInfoList = customerInfoList;
    etc ....
    CustomerInfo Class:
    @Column(name = "FullName")
    private String fullName;
    @JoinColumn(name = "cust_id", referencedColumnName = "cust_id")
    @ManyToOne
    private Customers custId;
    etc....
    I create a query as follows and get back an instance of the Customers class
    List<Customers> cust = em.createQuery("select c from Customers c where c.custId = :custId").setParameter("custId", 1).getResultList();
    Then calling the following method returns a list of every row in customerinfo where customer.cust_id=customerinfo.cust_id as expected
    List <CustomersInfo> custInfo = cust.get(0).getCustomersInfoList();
    So what i want to know is, is there a way of changing the default select statement that is used when calling getCustomersInfoList() to receive a subset of the rows based on values of other fields in customerinfo?
    apologies for the length of the post

    Hi,
    the customerinfo table contains a timestamped record for each update to the table so would contain multiple entries for the one customer. What i was looking to do was to retrieve just the relevant instance from customerinfo using the available methods without having to rewrite the sql statements (ie by passing a date and time into the method and getting back the most recent entry that would have existed at that time). I was hoping there might have been a way of altering the criteria used by editing the tags or something similar
    Is there a way of retrieving the statement that calling getCustomersInfoList() in this example uses?
    It looks like regular jpql might be the way to go

  • JPA: @ManyToOne legacy mapping using @JoinTable

    Dear JEE experts,
    I have a tough legacy mapping problem. There are two entities Pac and BasePac where each Pac has a BasePac field which is to be queried from the other entity table. The association is definied in a third table pac_component which has a Pac and a BasePac field among several others. I think the schema is a bit weird and I would have defined it differently, but I cannot change it because other applications using the database must not be changed.
    My code looks like this:
    @javax.persistence.Entity(name="Pacs")
    @javax.persistence.Table(name="packet")
    @javax.persistence.SequenceGenerator(name="PacsSeqGen", sequenceName="packet_packet_id_seq")
    public class Pac
         implements java.io.Serializable
        // virtual attribute basePac
        @javax.persistence.ManyToOne(fetch=EAGER, optional=true) // optional should be default anyway
        @javax.persistence.JoinTable(
             name="packet_component",
             [email protected](name="packet_id"),
             [email protected](name="basepacket_id") )
        private BasePac basePac;
        public BasePac getBasePac() { return basePac; }
        public void setBasePac( BasePac basePac ) { this.basePac = basePac; }
    @javax.persistence.Entity(name="BasePacs")
    @javax.persistence.Table(name="basepacket")
    @javax.persistence.SequenceGenerator(name="BasePacsSeqGen", sequenceName="basepacket_basepacket_id_seq")
    public class BasePac
         implements java.io.Serializable
    { ... }The Entity for pac_component does not appear so far and afaik it does not matter.
    When I now create a Pac instance and persist it, JPA (with Hibernate) always wants to create a link object:
    insert into pac_component (basepacket_id, packet_id) values (?, ?)Where the ? for basepacket_id is null. But this is not a valid row for pac_component, thus I will get a ConstaintViolationException.
    My question is: Why does it create this row at all? The association is marked optional!
    My solution might be to make the field PacBase within Pac transient and access it only through a pacComponents field, which is a @OneToMany but every assiciated PacComponent entity refers to the same BasePac. Anyway, I wonder why JPA or Hibernate wants to create such a row at all.
    ... MIchael

    I wouldn't focus too much on wanting to solve this through JPA. What you have here is a 'problem' which you will run into in many forms - your business requirements do not map directly to the data layer. This simply means that you need some business logic to make the translation. For example if this were for a web layer I would implement a specialized bean which can take different entities and then provide an alternative view on the data, optionally by generating it.
    If 'calculated' data is closely tied to the database layer and less to the business layer then you could of course choose to fix it through the database itself - by creating a view and mapping an entity to that. That is especially useful if you need the same data in multiple aspects of the application framework and not only in the Java code (think of reporting and analysis for example), but it has other considerations like performance.

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

  • 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

  • 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

  • Problem in map a OneToOne relationship

    If I have a entity name e1 which has a OneToOne relationshp with another entity named e2.
    e1 has two column: workflow and step
    e2 also has the two columns: workflow and step. but these two columns are not the e2's primaryKey.
    how can i use e1,getE2() to get the e2 entity.
    Must the two columns to be the primatyKey in a OneToOne relationship?

    also I have another problem in OneToMany
    [class test.pojo.Testworkflow] should not have @JoinColumn(s) specified. In the case where the @OneToMany is not mapped by another entity (that is, it is the owning side and is uni-directional), it should specify (optional through defaulting) a @JoinTable.
    but it seems like that jpa specification allow to mapp a uni-directional OneToMany
    relationship

  • OneToMany Unidirectional strange behavior ?

    I am implementing hibernate with JPA annotations and trying to do a very simple thing but seeing very different behavior in oracleAS.
    I have an Order object which has many OrderLineItems and i want a unidirectional relationship NOT A BIDIRECTIONAL.
    When i try the following code with a main method, it does work perfectly fine, but the same code when deploying to Oracle Application server in a session bean it fails with the following exception
    Exception Description: @OneToMany for attribute name [orderLineItemsList] in entity class [class com.thoughtclicks.domains.Orders] should not have @JoinColumn(s) specified. In the case where the @OneToMany is not mapped by another entity (that is, it is the owning side and is uni-directional), it should specify (optional through defaulting) a @JoinTable.
    Below is the defination of Order Object: and as it is unidirection there is no code for order in orderlineitems
    @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
    @JoinColumn(name="ORD_ID")
    public List<OrderLineItems> getOrderLineItemsList() {
    return orderLineItemsList;
    Does anybody know what can be the issue with the oracle as deployment ?
    Message was edited by:
    rahul_juneja

    Guys,
    Any Clues about this ?
    Thanks,
    Rahul

  • OneToMany - unidirectional,  how to...

    I have an a pre-existing database that uses natural keys. Simplified problem:
    Database (I do not have a join table nor am I allowed to create one):
    (One side, has many phones, name of table is person)
    PERSON_ID INT
    NAME CHAR(30)
    ADDRESS CHAR(30)
    SSN CHAR(9)
    (Many Side, name of table is phone)
    PHONE_ID int
    PHONE CHAR(30)
    SSN CHAR(9)
    How do I code the one to many? I am assuming that the many side does not need any annotation.
    ------- JPA Entity----
    @Entity
    public class Person implements java.io.Serializable{
    Bla Bla... assume all fields are here...
    The lines below are what I am confused about...
    @OneToMany(cascade={CascadeType.ALL})
    @JoinColumn(name="SSN")
    private Collection<Phone> phoneList = new ArrayList<Phone>();
    Obviously this cannot work because I never tell it how to relate the SSN between Phone and Person. Can I only do this by creating a Join table? When I try something similiar to this in my application I get the error:
    "Exception Description: @OneToMany for attribute name [wfrStagingStorageServiceList] in entity class [class model.gov.hhs.samhsa.model.Facilities] should not have @JoinColumn(s) specified. In the case where the @OneToMany is not mapped by another entity (that is, it is the owning side and is uni-directional), it should specify (optional through defaulting) a @JoinTable.
         at oracle.toplink.essentials.exceptions.ValidationException.uniDirectionalOneToManyHasJoinColumnAnnotations(ValidationException.java:1208)"
    How do you handle the relation for one to many with natural keys?

    I'm not sure what you are referring to by OneToMany defaults. The JPA spec is clear that a unidirectional OneToMany defaults to using a join table, and EclipseLink does this. Perhaps be more specific, and give an example.
    In general JPA 1.0 has several optional features, some are implemented in EclipseLink and some are not. As well the spec has several unspecified or uncertain features and behavoir, and some not supported, but possible features. EclipseLink also supports a large set of features beyond the spec. EclipseLink 1.1 has also begun work on JPA 2.0 and has several new features including unidirectional OneToMany's. If there is a specific feature you desire in EclipseLink, whether or not it is specified by the spec please log an enhancement request in Bugzilla and vote for the feature.
    There is an existing entry in Bugzilla that mentions table per class inheritance, if you need this feature please vote for the bug,
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=232134
    James : http://www.eclipselink.org

  • Joins and Outer joins

    Sorry for being a newbie!
    I was using JPQL to grab data from one table that requires an outer join to another table.
    I thought I could do this:
    select a.f1,a.f2,b.f3 from A a LEFT OUTER JOIN B b
    where a.id = b.id and
    a.match = b.match;
    A and B are entities and I need to join with two columns. Can someone please tell me what I'm doing wrong.
    Thanks!

    osubb wrote:
    Sorry for being a newbie!Everybody starts out with less knowledge than others, no need to apologize for that.
    >
    I was using JPQL to grab data from one table that requires an outer join to another table.Okay.
    >
    I thought I could do this:
    select a.f1,a.f2,b.f3 from A a LEFT OUTER JOIN B b
    where a.id = b.id and
    a.match = b.match;
    A and B are entities and I need to join with two columns. Can someone please tell me what I'm doing wrong.
    Thanks!Generally you do these kind of mappings through the Entities. For example, you can have a OneToMany / ManyToOne mapping between the two entities. Check out the Toplink reference guide for some examples on how to do this:
    [http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html#ManyToOne|toplink JPA annotations reference]
    Even if you are not using Toplink, this is the same for all persistence providers.

  • JDBC and outer joins

    What is the correct syntax for an outer join using JDBC. A statement such as the following is returned with an illegal char. error:
    select x.value, y.value from x_table x, y_table y
    where x.id = y.id(+);     
    I'm using oracle 8i and the thin client driver.
    Thanks

    osubb wrote:
    Sorry for being a newbie!Everybody starts out with less knowledge than others, no need to apologize for that.
    >
    I was using JPQL to grab data from one table that requires an outer join to another table.Okay.
    >
    I thought I could do this:
    select a.f1,a.f2,b.f3 from A a LEFT OUTER JOIN B b
    where a.id = b.id and
    a.match = b.match;
    A and B are entities and I need to join with two columns. Can someone please tell me what I'm doing wrong.
    Thanks!Generally you do these kind of mappings through the Entities. For example, you can have a OneToMany / ManyToOne mapping between the two entities. Check out the Toplink reference guide for some examples on how to do this:
    [http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html#ManyToOne|toplink JPA annotations reference]
    Even if you are not using Toplink, this is the same for all persistence providers.

  • Entity bean (ejb 3.0) refactoring problem

    I didn't find a better method than regenerating an entity bean after modifying the table definition and renaming the class after deleting the old one.
    I'm not sure i can delete the old class representing the entity bean before regenerating it without any effects into the others entity beans.
    It work fine but still a little problem. The refactoring process didn't change the name of the entity bean into the select clauses into queynamed injection.

    I am facing a similar problem. Does JDeveloper 10g (10.1.3.3.0) provide an automatic process to update an Entity Bean definition when the underlying database table definition changes?
    I also noticed that for JDeveloper to create all the relationships (i.e. @OneToMany, @ManyToOne) between multiple Entity beans, I need to create all the Entity beans together in one pass using the wizard. If two entities depend on each other, and not created together, JDeveloper will not create the relationships between them. Is there a way around that?
    Thank you

  • Uses a non-entity as target entity

    Hi everyone,
    I need your help because I am working on a project j2ee6
    I am using jpa (eclipseLink)
    when I created entities without relation, all worked perfectly
    but now that I am trying to set up relation @oneTomany @ManyToOne
    I got this error all the time
    Exception Description: [class com.Domain.User] uses
    [ERROR] a non-entity [class com.Domain.Groups] as target entity in the
    [ERROR] relationship attribute [field groupe].
    here is my user entity :_
    @Entity
    @NamedQueries({
         @NamedQuery(name = "findAllUsers", query="select u from User u"),
         @NamedQuery(name = "findWithLogParam", query="select u from User u where u.Email = :fmail and u.Password = FUNC('sha1', :fpass)")
    public class User implements Serializable{
         private static final long serialVersionUID = 3175161374832714727L;
         @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
         private Long UserId;
         @Column(nullable = false)
         private String Title = "Mr";
         @Column(nullable = false)
         private String Login;
         @Column(nullable = false)
         private String Password;
         @Column(nullable = false)
         private String Firstname;
         @Column(nullable = false)
         private String Lastname;
         @Column(nullable = false)
         private String Email;
         private String Telephone;
         private String Mobile;
         @Temporal(TemporalType.DATE)
         private Date Date_of_birth;
         private String Postcode;
         private String Address;
         private String City;
         private String County;
         private String Region;
         private String Country;
         private String AccountEnabled="On";
         @ManyToOne(optional=false)
    @JoinColumn(name="GROUPID", referencedColumnName="GROUPID")
         private Groups groupe;
         private String Token;
    Here is the entity Groups*
    @Entity
    public class Groups implements Serializable{
         private static final long serialVersionUID = 7092895671981671161L;
         @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
         private Long GroupId;
         @Column(nullable = false)
         private String GroupName;      
         @OneToMany(mappedBy="groupe", targetEntity=User.class, fetch=FetchType.EAGER)
         private List<User> UserList = new ArrayList<User>();
    Here is my persistence.xml*
    <?xml version="1.0" encoding="windows-1252" ?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
                   version="2.0">
         <persistence-unit name="testPU" transaction-type="JTA">
              <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>     
              <jta-data-source>jdbc/UnmodDB</jta-data-source>     
              <class>com.unmod.Domain.User</class>
              <class>com.unmod.Domain.Groups</class>
    ........ other classes ......
              <exclude-unlisted-classes>false</exclude-unlisted-classes>
              <properties>
                   <property name="eclipselink.target-database" value="MySQL"/>
                   <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
                   <property name="eclipselink.ddl-generation.output-mode" value="database" />
              <property name="eclipselink.create-ddl-jdbc-file-name" value="create.sql"/>
              </properties>
         </persistence-unit>
    </persistence>
    It works (compliation works) when I add @Basic however only the user table is created
    Thanks

    Yes it's strange because
    when I comment the oneToMany/ManyToOne parts
    I see hibernate is called
    Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
    INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    INFO: Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
    INFO: Using provided datasource
    INFO: RDBMS: MySQL, version: 5.5.20
    INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.18 ( Revision: [email protected] )
    INFO: Using dialect: org.hibernate.dialect.MySQLDialect
    INFO: Transaction strategy: org.hibernate.ejb.transaction.JoinableCMTTransactionFactory
    INFO: instantiating TransactionManagerLookup: org.hibernate.transaction.SunONETransactionManagerLookup
    INFO: instantiated TransactionManagerLookup
    INFO: Automatic flush during beforeCompletion(): disabled
    INFO: Automatic session close at end of transaction: disabled
    INFO: JDBC batch size: 15
    INFO: JDBC batch updates for versioned data: disabled
    INFO: Scrollable result sets: enabled
    but when I added the OneToMany/ManyToOne
    I got
    [INFO] Command deploy failed.
    [ERROR] remote failure: Unknown plain text format. A properly formatted response from a PlainTextActionReporter
    [ERROR] always starts with one of these 2 strings: PlainTextActionReporterSUCCESS or PlainTextActionReporterFAILURE. The response we received from the server was not understood: Signature-Version: 1.0
    [ERROR] message: Error occurred during deployment: Exception while preparing t
    [ERROR] he app : Exception [EclipseLink-28018] (Eclipse Persistence Services
    [ERROR] - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.EntityMa
    [ERROR] nagerSetupException
    [ERROR] Exception Description: Predeployment of P
    [ERROR] ersistenceUnit [chapter02PU] failed.
    [ERROR] Internal Exception: Exce
    [ERROR] ption [EclipseLink-7250] (Eclipse Persistence Services - 2.3.0.v20110
    [ERROR] 604-r9504): org.eclipse.persistence.exceptions.ValidationException%%%
    [ERROR] EOL%%%Exception Description: [class com.unmod.Domain.User] uses a non
    [ERROR] -entity [class com.unmod.Domain.Groups] as target entity in the relat
    [ERROR] ionship attribute [field groupe].. Please see server.log for more det
    [ERROR] ails.
    [ERROR] Exception while invoking class org.glassfish.persistenc
    [ERROR] e.jpa.JPADeployer prepare method : javax.persistence.PersistenceExcep
    [ERROR] tion: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2
    [ERROR] .3.0.v20110604-r9504): org.eclipse.persistence.exceptions.EntityManag
    [ERROR] erSetupException
    [ERROR] Exception Description: Predeployment of Pers
    [ERROR] istenceUnit [chapter02PU] failed.
    [ERROR] Internal Exception: Excepti
    [ERROR] on [EclipseLink-7250] (Eclipse Persistence Services - 2.3.0.v20110604
    [ERROR] -r9504): org.eclipse.persistence.exceptions.ValidationException%%%EOL
    [ERROR] %%%Exception Description: [class com.unmod.Domain.User] uses a non-en
    [ERROR] tity [class com.unmod.Domain.Groups] as target entity in the relation
    [ERROR] ship attribute [field groupe].
    [ERROR] Exception [EclipseLink-28018]
    [ERROR] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.p
    [ERROR] ersistence.exceptions.EntityManagerSetupException
    [ERROR] Exception Descripti
    [ERROR] on: Predeployment of PersistenceUnit [chapter02PU] failed.
    [ERROR] Internal E
    [ERROR] xception: Exception [EclipseLink-7250] (Eclipse Persistence Services
    [ERROR] - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.Validati
    [ERROR] onException
    [ERROR] Exception Description: [class com.unmod.Domain.User] uses
    [ERROR] a non-entity [class com.unmod.Domain.Groups] as target entity in the
    [ERROR] relationship attribute [field groupe].
    it's like eclipseLink wanted to bug me over Hibernate.

  • Looping the one to many: ConcurrentModificationException

    In slow steps my BM gets shape. I now run into the following issue:
    I have a OneToMany / ManyToOne relationship between two classes: standversion contains many standassigns. The classes have the following mappings:
    Standassign:
         @ManyToOne(fetch = FetchType.LAZY, targetEntity = nl.reinders.bm.Standversion.class ) @JoinColumn(name="standversionnr")
         private nl.reinders.bm.Standversion iStandversion;
    StandVersion:
         @OneToMany(mappedBy = "iStandversion", fetch = FetchType.LAZY, targetEntity = nl.reinders.bm.Standassign.class)
         private java.util.Collection<nl.reinders.bm.Standassign> iStandassignsWhereIAmStandversion = new java.util.ArrayList<nl.reinders.bm.Standassign>();
    This works perfectly, lazy loading and all.
    So the next step is to define accessor methods:
    - StandAssign has a get/setStandversion
    - StandVersion has a add/remove/getStandassignsWhereIAmStandversion
    Works perfectly.
    However, if I execute a "setStandversion" on the Standassign, followed by a "getStandassignsWhereIAmStandversion" on the corresponding Standversion, the standassign is not present in de collection. This relation needs to be wired into the BM.
    In order to implement this, the setStandversion does a:
         if (value == iStandversion) return; // optimalisation and prevent looping
         if (lValue != null) lValue.removeStandassignsWhereIAmStandversion( (nl.reinders.bm.Standassign)this );
         iStandversion = value;
         if (value != null) value.addStandassignsWhereIAmStandversion( (nl.reinders.bm.Standassign)this );
    In effect: when a value is set, remove me from the old value's collection and add me to the new values collection.
    And correspondingly, the addStandassignsWhereIAmStandversion does:
         if (value != null && !iStandassignsWhereIAmStandversion.contains(value))
              iStandassignsWhereIAmStandversion.add(value);
              value.setStandversion( (nl.reinders.bm.Standversion)this);
    And the remove ofcourse the opposite. In effect: if a standassign is added to a standversion, make sure the standversion in the standassign is changed also.
    Logically this works. But if some testcode is executed, this exception occurs:
    Exception in thread "main" java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
         at java.util.AbstractList$Itr.next(AbstractList.java:420)
         at oracle.toplink.essentials.indirection.IndirectList$1.next(IndirectList.java:418)
         at oracle.toplink.essentials.indirection.IndirectList$1.next(IndirectList.java:418)
         at nl.reinders.bm.BMTestToplink.main(BMTestToplink.java:71)
    What is where and why concurrent modified???

    Found it!
    The testcode fetched all Standassigns from one Standversion, looped over them and make a shallow clone of each standversion. Then the newly clone Standassign was reassigned to a new Standversion. So:
    create new standversion
    loop over all standassigns of the old standversion
    create a clone of the standassign
    assign the new standversion to the cloned stand assign
    The creation of the clone basically is a whole list of "new.setXXX( getXXX )", so it initially also copies the value for "Standversion". So the cloned Standassign is initially bound to the old standversion and then after the clone the Standversion is replaced with the new one.
    This means that the collection that is iterated over is altered by the clone method. So what needs to be done is full fetch the collection of standassigns prior to looping over it.

  • Blackberry and Jdeveloper

    is it possible to use jdeveloper to develop applications for blackberry devices. if it is possible cam someone provide links to samples / tutorials etc
    Regards
    Srinivas

    Shay
    Thanks for the info
    I followed the instructions from the first article and i am getting below exception
    May 22, 2007 10:15:57 AM com.evermind.server.ejb.logging.EJBMessages logException
    SEVERE: [current-workspace-app] An error occured deploying EJB module: com.evermind.server.ejb.exception.DeploymentException: [current-workspace-app:EIM_PDA_Model_0] - Exception creating EntityManagerFactory using PersistenceProvider class oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider for persistence unit default.
    com.evermind.server.ejb.exception.DeploymentException: [current-workspace-app:EIM_PDA_Model_0] - Exception creating EntityManagerFactory using PersistenceProvider class oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider for persistence unit default.
         at com.evermind.server.ejb.exception.DeploymentException.exceptionCreatingEntityManagerFactory(DeploymentException.java:130)
         at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.createContainerEntityManagerFactory(PersistenceUnitManagerImpl.java:197)
         at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.initializePersistenceUnit(PersistenceUnitManagerImpl.java:159)
         at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.initialize(PersistenceUnitManagerImpl.java:94)
         at com.evermind.server.ejb.EJBPackageDeployment.initializePersistenceUnitManager(EJBPackageDeployment.java:1022)
         at com.evermind.server.ejb.EJBContainer.postInit(EJBContainer.java:845)
         at com.evermind.server.ApplicationStateRunning.initializeApplication(ApplicationStateRunning.java:217)
         at com.evermind.server.Application.setConfig(Application.java:439)
         at com.evermind.server.Application.setConfig(Application.java:340)
         at com.evermind.server.ApplicationServer.addApplication(ApplicationServer.java:1853)
         at com.evermind.server.ApplicationServer.initializeDeployedApplications(ApplicationServer.java:1608)
         at com.evermind.server.ApplicationServer.setConfig(ApplicationServer.java:990)
         at com.evermind.server.ApplicationServerLauncher.run(ApplicationServerLauncher.java:131)
         at java.lang.Thread.run(Thread.java:595)
    Caused by: Exception [TOPLINK-7160] (Oracle TopLink Essentials - 2006.8 (Build 060829)): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: @OneToMany for attribute name [warehouseinventoryitemCollection] in entity class [class oracle.wireless.demo.part.model.Part] should not have @JoinColumn(s) specified. In the case where the @OneToMany is not mapped by another entity (that is, it is the owning side and is uni-directional), it should specify (optional through defaulting) a @JoinTable.
         at oracle.toplink.essentials.exceptions.ValidationException.uniDirectionalOneToManyHasJoinColumnAnnotations(ValidationException.java:1172)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataValidator.throwUniDirectionalOneToManyHasJoinColumnSpecified(MetadataValidator.java:266)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.OneToManyAccessor.process(OneToManyAccessor.java:85)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.RelationshipAccessor.processRelationship(RelationshipAccessor.java:250)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProject.processRelationshipDescriptors(MetadataProject.java:513)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProject.process(MetadataProject.java:445)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.processAnnotations(MetadataProcessor.java:203)
         at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.processORMetadata(EntityManagerSetupImpl.java:993)
         at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:501)
         at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createContainerEntityManagerFactory(EntityManagerFactoryProvider.java:152)
         at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.createContainerEntityManagerFactory(PersistenceUnitManagerImpl.java:192)
         ... 12 more
    07/05/22 10:15:57 WARNING: Application.setConfig Application: current-workspace-app is in failed state as initialization failed.
    java.lang.InstantiationException: Error initializing ejb-modules: [current-workspace-app:EIM_PDA_Model_0] - Exception creating EntityManagerFactory using PersistenceProvider class oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider for persistence unit default.
    May 22, 2007 10:15:57 AM com.evermind.server.ServerMessages warningApplicationInitializationFailed
    WARNING: Exception initializing deployed application: current-workspace-app. Application: current-workspace-app is in failed state as initialization failed
    Ready message received from Oc4jNotifier.
    Embedded OC4J startup time: 15421 ms.
    Target URL -- http://localhost:8993/EIM_PDA-ViewController-context-root/faces/indexPDA.jspx
    07/05/22 10:16:01 Oracle Containers for J2EE 10g (10.1.3.1.1) initialized
    May 22, 2007 10:16:02 AM oracle.wireless.its.ra.TelnetResourceAdapter run
    INFO: Industrial Telnet Server version: Version 10.1.3.0.0 started-up successfully.

Maybe you are looking for