OneToOne mapping

Hi,
I need some help with mapping tables PERSON and PERSON_CARD. PERSON can have none or one CARD.
table PERSON
idperson
name
table CARD
idperson
number
Thanks

Solved this way:
@Entity
public class Person implements Serializable {
@Id
@Column(name="idperson")
private Integer idperson;
@OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="person")
private Card card;
@Entity
public class Card implements Serializable {
@Id
@Column(name="idperson", insertable=false, updatable=false)
private Integer idperson;
@OneToOne
@JoinColumn(name="idperson", referencedColumnName="idperson")
private Person person;

Similar Messages

  • OnetoOne Mapping Problem in EJB 3.0 CMP's

    Hi,
    Im new EJB3.0, and trying to implement onetoone mapping between two tables.
    The beans are deployed successfully, but when I find an object using the EntityManager, it is throwing
    java.sql.SQLException: ORA-00904: "COLUMN_NAME": invalid identifier.
    When I am using the following tables and Classes,
    The searching statement is as follows:
    SELECT COMPANYID, COMPANYNAME, COMPANYADDR, ENAME, EMPNO FROM COMPANY WHERE ((COMPANYID = 'MUM') AND (COMPANYNAME = 'MUMBAI'))
    But I want to retieve the Company Details, and Employee details individually,
    Please help me to sort this out.
    The script for tables is:
    create table emp (empno VARCHAR2(4),ENAME VARCHAR2(10),SAL NUMBER(10,2),companyid varchar2(10) ,companyname varchar2(20),primary key(empno,ename,companyid,companyname));
    create table company(companyid varchar2(10),companyname varchar2(20),companyaddr varchar2(20) not null,primary key(companyid,companyname));
    ALTER TABLE EMP ADD CONSTRAINT PROJ_EMP_EMPLOYEE FOREIGN KEY (companyid,companyname) REFERENCES company(companyid,companyname);
    desc company;
    desc emp;
    insert into company values('MUM','MUMBAI','MUMBAI BASTI');
    insert into company values('CHE','CHENNAI','CHENNAI NAGAR');
    insert into company values('HYD','HYDERABAD','HYDERABAD HITECH');
    insert into emp values('12','GANGADHAR','2500','MUM','MUMBAI');
    insert into emp values('16','SESHU','6500','CHE','CHENNAI');
    insert into emp values('18','RUSTUM','8500','HYD','HYDERABAD');
    COMMIT;
    And the two Entitys and its primary keys are :
    Company.java ( Entity Class , CMP)
    package com.foursoft.hr;
    import java.util.*;
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.OneToOne;
    import javax.persistence.Id;
    import javax.persistence.IdClass;
    import javax.persistence.Column;
    import javax.persistence.Table;
    import static javax.persistence.CascadeType.*;
    import static javax.persistence.FetchType.*;
    import static javax.persistence.EntityType.*;
    @IdClass("com.foursoft.hr.CompanyPK")
    @Entity()
    @Table(name="COMPANY")
    public class Company implements Serializable
         public String companyid;
         public String companyname;
         public String companyaddr;
         private Employee employee;
         public Company(){}
         @Id
         @Column(name="COMPANYID",primaryKey=true)
         public String getCompanyid(){ return companyid; }
         public void setCompanyid(String compid){ companyid = compid; }
         @Id
         @Column(name="COMPANYNAME",primaryKey=true)
         public String getCompanyname(){ return companyname; }
         public void setCompanyname(String compname){ companyname = compname; }
         public String getCompanyaddr(){ return companyaddr; }
         public void setCompanyaddr(String compaddr){ companyaddr = compaddr; }
         @OneToOne(targetEntity="com.foursoft.hr.Employee", cascade=ALL )
         public Employee getEmployee()
    return employee;
         public void setEmployee(Employee employee)
              this.employee = employee;
    public String toString()
    StringBuffer buf = new StringBuffer();
    buf.append("Class:")
    .append(this.getClass().getName())
    .append(" :: ")
    .append(" COMPANYID:")
    .append(getCompanyid())
    .append(" COMPANYNAME:")
    .append(getCompanyname());
    return buf.toString();
    CompanyPK.java (Primary Key Class for Company Table)
    package com.foursoft.hr;
    public class CompanyPK implements java.io.Serializable
         public java.lang.String companyid;
         public java.lang.String companyname;
         public boolean equals(Object obj){
              CompanyPK pkObj = (CompanyPK)obj;
              return (companyid.equals(pkObj.companyid) && companyname.equals(pkObj.companyname));          
         public int hashCode(){
              try {
                   long     crcKey = -1;
                   java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
                   java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(bos);
                   oos.writeObject(this);
                   oos.flush();
                   java.util.zip.Adler32 adl32 = new java.util.zip.Adler32();
                   adl32.update(bos.toByteArray());
                   crcKey = adl32.getValue();
                   return (int)(crcKey ^ (crcKey >> 32));
              } catch (java.io.IOException ioEx) {
                   return -1;
    Employee.java (Entity Class, CMP)
    package com.foursoft.hr;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Column;
    import javax.persistence.IdClass;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;
    import static javax.persistence.CascadeType.*;
    import static javax.persistence.FetchType.*;
    @IdClass("com.foursoft.hr.EmployeePK")
    @Entity
    @Table(name = "EMP")
    public class Employee implements java.io.Serializable
    private String empNo;
    private String eName;
    private double sal;
    private Company company;
    private String companyid;
    private String companyname;
    @Id
    @Column(name="EMPNO",primaryKey=true)
    public String getEmpNo() {      return empNo;   }
    public void setEmpNo(String empNo) {      this.empNo = empNo;   }
    @Id
    @Column(name="ENAME" , primaryKey=true)
    public String getEName() {      return eName;   }
    public void setEName(String eName) {      this.eName = eName;   }
    public double getSal() {      return sal;   }
    public void setSal(double sal) {      this.sal = sal;   }
    @OneToOne(fetch=LAZY,optional=false)
    public Company getCompany() {        return company;   }
    public void setCompany(Company company) {        this.company=company;    }
    public String toString()
    StringBuffer buf = new StringBuffer();
    buf.append("Class:")
    .append(this.getClass().getName())
    .append(" :: ")
    .append(" empNo:")
    .append(getEmpNo())
    .append(" ename:")
    .append(getEName())
    .append(" sal:")
    .append(getSal());
    return buf.toString();
    EmployeePK.java (Primary Key Class for Employee Table)
    package com.foursoft.hr;
    public class EmployeePK implements java.io.Serializable
         public java.lang.String empNo;
         public java.lang.String eName;
         public boolean equals(Object obj){
              EmployeePK pkObj = (EmployeePK)obj;
              return (empNo.equals(pkObj.empNo)&& eName.equals(pkObj.eName));
         public int hashCode(){
              try {
                   long     crcKey = -1;
                   java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
                   java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(bos);
                   oos.writeObject(this);
                   oos.flush();
                   java.util.zip.Adler32 adl32 = new java.util.zip.Adler32();
                   adl32.update(bos.toByteArray());
                   crcKey = adl32.getValue();
                   return (int)(crcKey ^ (crcKey >> 32));
              } catch (java.io.IOException ioEx) {
                   return -1;
    Thanks very much!
    Gangadhar.

    The beans are deployed successfully, but when I find an object using the EntityManager, it is throwing
    java.sql.SQLException: ORA-00904: "COLUMN_NAME": invalid identifier.
    Is the EntityManager find method
    find(java.lang.String entityName,
    java.lang.Object primaryKey)?
    @Id annotation is used for a single field primary key.
    For a composite primary key use the @EmbeddedId annotation
    and specify a primary key class with the @Embeddable annotation.
    example:
    @EmbeddedId
    PKClass pkClass
    @Embeddable
    public PKClass {}
    In the find method specify the @EmbeddedId instead of the @id.
    find(entity, pkClass)

  • JPA OneToOne mapping issue

    Simple one to one mapping to itself, tries to update primary key and throws this error.
    Also tried without cascade and persist the other object separate but that doesn't work either. I don't understand why it is trying to update primary key column ?.
    Class A
    @Id()
    private Long id
    *@OneToOne(fetch=FetchType.LAZY, cascade= CascadeType.ALL)*
    *@JoinColumn(name="TARGETID", insertable=true, updatable=false)*
    private A target;
    Test data:
    A(123) has target A(1234)
    when try to insert A(123) it throws this error :
    Exception [TOPLINK-7251] (Oracle TopLink Essentials - 2.1 (Build b60e-fcs (12/23/2008))): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: The attribute [id] of class [ObjectA] is mapped to a primary key column in the
    database. Updates are not allowed.
    at oracle.toplink.essentials.exceptions.ValidationException.primaryKeyUpdateDisallowed(ValidationException.java:2222)
    at oracle.toplink.essentials.mappings.foundation.AbstractDirectMapping.writeFromObjectIntoRowWithChangeRecord(AbstractDirectMapping.java:750)
    at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.buildRowForUpdateWithChangeSet(ObjectBuilder.java:948)

    Think I missed out one more thing on id :
    Class A
    *@Id()*
    *@GeneratedValue(strategy=GenerationType.TABLE, generator="mySeq")*
    private Long id
    *@OneToOne(fetch=FetchType.LAZY, cascade= CascadeType.ALL)*
    *@JoinColumn(name="TARGETID", insertable=true, updatable=false)*
    private A target;
    Though the primary key has strategy to generate value, id value is inserted manually before persisting it.
    So may be it could be something to do with this ?

  • Tricky OneToOne mapping

    Hi!
    I'm using EclipseLink to map two classes, A and B, with a one to one relationship. Both classes have a primary key "OBJECT_ID", but they are joined by two other fields that comprises a composite key: "ID" and "ID_NUMBER".
    The code thus far:
    @Entity
    public class A {
      @Id
      @Column(name = "OBJECT_ID")
      private String objectId;
      @OneToOne(mappedBy = "a")
      private B b;
    @Entity
    public class B {
      @Id
      @Column(name = "OBJECT_ID")
      private String objectId;
      @OneToOne
      @JoinColumns({
          @JoinColumn(name = "ID", referencedColumnName = "ID", insertable = false, updatable = false),
          @JoinColumn(name = "ID_NUMBER", referencedColumnName = "ID_NUMBER", insertable = false, updatable = false)
      private A a;
    }So far so good. Now here's the tricky part: in some cases A and B are supposed to be joined even though their ID_NUMBERs don't match. This happens when A.ID = B.ID and B.ID_NUMBER = "999". At that time ID is unique on its own and A's ID_NUMBER is "1".
    I have no idea how to accomplish this. Maybe through some EclipseLink specific customizer of some kind? Please help!

    Not having used EclipseLink I can only guess but your required functionality is very odd. As such there is unlikely to be anything that allows support for it directly.
    However the API should have some mechanism to allow pass through SQL. So you can build your own SQL which has what ever rules you wish and execute that.

  • Creating Relationships between views, causes writable mapping error

    Hi
    I'm using the DBAdapter in ESB (10.1.3.3), which uses Toplink and I am trying to create a relationship between a table and a view. None of the objects have any keys or indexes, so I am creating a relationship directly.
    When I have created the adapter service and compile the ESB, I get the following error:
    Descriptor EmployeePhonesV -> The following primary key fields are unmapped: STAFF_NUMBER
    Descriptor EmployeePhonesV -> The following primary key fields have no writable mappings: STAFF_NUMBER
    When I imported the view, I had to tell it that the primary key was a composite as there is no real unique key field.
    Is this a known problem that I can't create relationships between views???
    Any help most appreciated.
    Chris

    Hello Chris,
    The exception is stating there isn't a mapping capable of setting the STAFF_NUMBER field. How do you have this field mapped? Generally there should be a writable either direct-to-field mapping or OnetoOne mapping using this field though other types of mappings will work.
    Best Regards,
    Chris Delahunt

  • Onetoone mappings in jpa 3.0

    I am having problems with a onetoone mapping.
    I have a Customer class
    Customer
    @Entity
    public class Customer implements Serializable {
    @Id
    @Column(name = "CUSTOMER_ID", nullable = false)
    @GeneratedValue(generator = "CusSeq")
    @SequenceGenerator(name = "CusSeq, sequenceName = "Cus_Seq", allocationSize = 1)
    private Long customerId;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    //getters and setters for the variables
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "ADDRESS_ID", unique=true, nullable=false)
    private Address address;
    Address class
    @Entity
    public class Address implements Serializable {
    @Id
    @Column(name = "ADDRESS_ID",nullable = false)
    @GeneratedValue(generator = "AddSeq")
    @SequenceGenerator(name = "AddSeq", seqenceName = "ADD_SEQ", allocationSize = 1)
    private Long addressId;
    @OneToOne(optional=false, mappedBy = "address")
    private Customer customerAddressMandatory
    private String street1;
    private String street2
    private String city;
    private String state;
    private Strng county;
    //getters and setters for the variables
    mainTest
    public class MainTest {
    public MainTest(){
    public static void main(String[] args) {
    MainTest mainTest = new MainTest();
    Customer customer = new Customer();
    customer.setFirstName("John");
    customer.setLastName("Doe);
    customer.setPhoneNum("5716122300");
    Address address = new Address();
    address.setStreet1("111 Waxpool rd");
    address.setCity("Ashburn");
    address.setState("VA");
    address.setCounty("Loudon");
    customer.setAddress(address);
    address.setCustomerAddressMandatory(customer);
    // persistence code
    The ForeignKey in the database in Customer table is Primary_Address_Id;
    The primary Key in the Customer table is CUSTOMER_ID
    the primary key in the Address table is ADDRESS_ID
    The oneToOne mapping does not work. JPA does not work here because just for example purposes
    the address and Customer are mandatory fields for one another.
    I get an error message saying null cannot be inserted into the primary key filed of either customer
    or address depending on how I play with the onetoone mapping.
    Any help would be appreciated.
    Thanks,
    Veena
    Edited by: user597294 on Jun 8, 2011 5:36 AM
    Edited by: user597294 on Jun 8, 2011 5:37 AM
    Edited by: user597294 on Jun 8, 2011 5:57 AM

    Customer.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.NamedQueries;
    import javax.persistence.NamedQuery;
    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 = "XXXX.CUSTOMER_SEQ", allocationSize = 1)
    private BigDecimal customerId;
    @Column(name = "CUSTOMER_NAME", length = 20)
    private String customerName;
    @Column(name = "PHONES_ID", nullable = false)
    private BigDecimal phonesId;
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "customer")
    private Phones telephoneNumberMandatory;
    public Customer() {
    public Customer(BigDecimal customerId, String customerName, BigDecimal phonesId) {
    this.customerId = customerId;
    this.customerName = customerName;
    this.phonesId = phonesId;
    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 BigDecimal getPhonesId() {
    return phonesId;
    public void setPhonesId(BigDecimal phonesId) {
    this.phonesId = phonesId;
    public void setTelephoneNumberMandatory(Phones telephoneNumberMandatory) {
    this.telephoneNumberMandatory = telephoneNumberMandatory;
    public Phones getTelephoneNumberMandatory() {
    return telephoneNumberMandatory;
    Phones.java
    @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 = "XXXX.PHONES_SEQ", allocationSize = 1)
    private BigDecimal phonesId;
    @Column(name = "PHONE_NUMBER", length = 20)
    private String phoneNumber;
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Customer customer;
    public Phones() {
    public Phones(BigDecimal customerId, String phoneNumber, BigDecimal phonesId) {
    this.customerId = customerId;
    this.phoneNumber = phoneNumber;
    this.phonesId = phonesId;
    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;
    public Customer getCustomer() {
    return customer;
    TestOneToOne.java
    package testonetoone;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    public class TestOneToOne {
    public TestOneToOne() {
    super();
    public static void main(String[] args) {
    TestOneToOne testOneToOne = new TestOneToOne();
    EntityManagerFactory emf = null;
    emf = Persistence.createEntityManagerFactory("TestOneToOne", new java.util.HashMap());
    // 1) Create customer, create phones, set add mapping
    EntityManager em = emf.createEntityManager();
    Customer c = new Customer();
    Phones p = new Phones();
    c.setCustomerName("Chrysler");
    p.setCustomer(c);
    p.setPhoneNumber("5716120000");
    c.setTelephoneNumberMandatory(p);
    try {
    em.getTransaction().begin();
    em.persist(c);
    em.getTransaction().commit();
    } finally {
    em.close();
    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="TestOneToOne">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>java:/app/jdbc/jdbc/idev01DS</jta-data-source>
    <class>testonetoone.Customer</class>
    <class>testonetoone.Phones</class>
    <properties>
    <property name="eclipselink.target-server" value="WebLogic_10"/>
    <property name="javax.persistence.jtaDataSource" value="java:/app/jdbc/jdbc/idev01DS"/>
    <property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
    <property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@idev01.xxxx.com:1521:dev"/>
    <property name="eclipselink.jdbc.user" value="DBSCHEMA"/>
    <property name="eclipselink.jdbc.password" value="password"/>
    </properties>
    </persistence-unit>
    </persistence>
    The error message I get is as follows:
    [EL Warning]: 2011-06-21 09:12:14.261--UnitOfWork(24485138)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("XXXX"."CUSTOMER"."PHONES_ID")
    Error Code: 1400
    Call: INSERT INTO CUSTOMER (CUSTOMER_ID, CUSTOMER_NAME, PHONES_ID) VALUES (?, ?, ?)
         bind => [2, Chrysler, null]
    Query: InsertObjectQuery(testonetoone.Customer@2c9103)
    Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("XXXX"."CUSTOMER"."PHONES_ID")
    Error Code: 1400
    Call: INSERT INTO CUSTOMER (CUSTOMER_ID, CUSTOMER_NAME, PHONES_ID) VALUES (?, ?, ?)
         bind => [2, Chrysler, null]
    Query: InsertObjectQuery(testonetoone.Customer@2c9103)
         at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
         at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
         at testonetoone.TestOneToOne.main(TestOneToOne.java:30)
    Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("XXXX"."CUSTOMER"."PHONES_ID")
    Error Code: 1400
    Call: INSERT INTO CUSTOMER (CUSTOMER_ID, CUSTOMER_NAME, PHONES_ID) VALUES (?, ?, ?)
         bind => [2, Chrysler, null]
    Query: InsertObjectQuery(testonetoone.Customer@2c9103)
    Edited by: user597294 on Jun 21, 2011 6:46 AM
    Edited by: user597294 on Jun 21, 2011 6:47 AM

  • Toplink Cache "back reference" best practice question.

    I have too many objects being stored in the Identity map. I'm using the default Soft/Weak map. The problem is every objects connects to every other objects. Since every objects can somehow be traced to each other all objects nothing is removed.
    Let's look at an example. I have two objects Projects and Tasks. A project has a collection of tasks and the task's have a "back reference" to the project. If just one task is in the "soft" section of the Identity map then all the other tasks, which are in the weak section, aren't eligible for garbage collection. The task has a simple OneToOne mapping to the project. I'm using a valueholder to hold the project. This particular instance doesn't use indirection, but there are many other objects that have a similar setup that do.
    These mappings are really convenient for reporting. For example through any task I can easily print the project's name. No query, joining, etc is necessary. This is critical to the app because we have a dynamic report builder where end users and print off anything they want. This flexibility though all of our mappings enables us to build a powerful report builder. Besides the report builder there are other modules that work in a similar fashion. Needless to say the application will build with the assumption that these "back references" exist. That said, I need to remove objects from the identity map.
    Is there a way to manually remove / invalidate the back references and have it repopulated on access? Similar to how indirection works?
    Is it possible to re-init an indirection value holder?
    Does anyone have any suggestions?
    I've looked at using an invalidation policy but that doesn't seem to remove anything. It still keeps the objects in memory. It just refreshes the object on access.

    Soft references should still garbage collect when memory is low, so you should still be ok memory wise, even with your cycles. If you want memory to be freed more aggressively, then use a Weak cache instead of Soft, or decrease your Soft cache size.
    There is no refresh() or revert() API on a ValueHolder, but if you refresh the source object, it will revert all of its relationships. Having a refresh() or revert() API of ValueHolder would be useful, so feel free to log an enhancement request on EclipseLink for that. You also may be able to cook something up using the mapping and readFromRowIntoObject(). Another option would be to just set the relationship to null and invalidate the object so it is refreshed when next accessed.
    James : http://www.eclipselink.org

  • LOB question about performance, fragmentation etc.

    Well..
    I want to discuss the issues around LOB objects.
    If I have an enttity class with n-count fields and then a lob as the n+1th field, does this affect performance in any way ? E.g. if performance is random access for an object without a lob, does the performance get linear or something when the lob is introduced?
    Another one:
    If the latter is true: is it an option for me to use an @OneToOne mapping to compensate ?
    What about fragmentation ? How can a database or whoever compensate for fragmentation, in the case the lob is the n+1th field ? Or just in general: How the fragmentation issues are handled?
    (Im just thinking that lobs introduce fragmentation and brings performance down...)

    This will be san=me if you are considering the Local interfaces.
    For remote interface(like accessing EJB from Servlets resides in diffferent Apps Server) use the DTO(data Transfer Object) patterns.
    Regards
    Sushil

  • Toplink UpdateAllQuery Issue

    We're experiencing some problems with an UpdateAllQuery when trying to update some fields belonging to an aggregate mapping within the component we're trying to update.
    We want to set these fields to NULL.
    One of the fields in the Aggregate mapping is a OneToOne mapping lookup type component. We want to set this field to NULL. (In a nutshell we want to set the FK to this lookup type object to NULL).
    In order to accomplish this, we have created a DirectQueryKey for the OneToOne mapping inside of the Aggregate mapping and then physically mapped it within the Component that makes use of the Aggregate mapping.
    It appears that this DirectQueryKey is not working properly. Even when we create a ReadAllQuery and use the same selection criteria, TopLink complains with a TOPLINK 6015 "Invalid QueryKey [businessFuncId] in expression" exception when trying to execute the query.
    We have checked to make sure the QueryKey name in our TopLink mapping matches the name used in the query definition... we're stumped... can someone review and provide some clues as to what we may be doing wrong.
    Here is the UpdateAllQuery definition:
    UpdateAllQuery updateQuery = new UpdateAllQuery(RegisterImpl.class);
    updateQuery.setCacheUsage(UpdateAllQuery.INVALIDATE_CACHE);
    ExpressionBuilder registerBuilder = updateQuery.getExpressionBuilder();
    updateQuery.addArgument("userId");
    updateQuery.addArgument("channel");
    updateQuery.addArgument("token");
    updateQuery.addArgument("date");
    updateQuery.addArgument("businessFuncId");
    Expression reservedDetailReg = registerBuilder.get("reservedDetail");
    Expression userIdExp = reservedDetailReg.get("userId").equal(
    registerBuilder.getParameter("userId"));
    Expression channelExp = reservedDetailReg.get("channel").equal(
    registerBuilder.getParameter("channel"));
    Expression tokenExp = reservedDetailReg.get("token").equal(
    registerBuilder.getParameter("token"));
    Expression dateExp = reservedDetailReg.get("date").equal(
    registerBuilder.getParameter("date"));
    Expression busFuncExp = reservedDetailReg.get("businessFuncId").equal(
    registerBuilder.getParameter("businessFuncId"));
    updateQuery.setSelectionCriteria(userIdExp.and(channelExp.and(tokenExp.and(dateExp
    .and(busFuncExp)))));
    updateQuery.addUpdate(reservedDetailReg.get("userId"), "");
    updateQuery.addUpdate(reservedDetailReg.get("channel"), "");
    updateQuery.addUpdate(reservedDetailReg.get("token"), "");
    updateQuery.addUpdate(reservedDetailReg.get("date"), "");
    updateQuery.addUpdate(reservedDetailReg.get("businessFuncId"), "");
    descriptor.getQueryManager().addQuery(QueryConstants.UNFREEZE_REGISTER_BY_RESERVED_DETAIL,
    updateQuery);
    Thanks in advance.

    In answer to your posted questions:
    1) Are you mapping a query key for the lookup object(between an attribute of the object and a field of the table) or are you adding a query key for the relationship mapping?
    Answer: We are mapping a DirectQueryKey (see "businessFuncId" above) to a field on the table directly related to the component being updated. However, the query key represents the foreign key (primary key) for a OneToOne mapping contained within an aggregate descriptor.
    Here's an explanation of the OR mapping/object relationship (reference the query definition in the original posting for more details):
    RegisterImpl (target of updateAllQuery) contains a ReservedDetail (Aggregate mapping) which in turn contains a OneToOne mapping to a BusinessFunction (read-only lookup type object).
    We created a DirectQueryKey: businessFuncId which represents the FK on the RegisterImpl table that is used within the ReservedDetail aggregate mapping for the OneToOne mapping to the BusinessFunction component.
    This query key is for query purposes only. As you can see from the query definition it is used to avoid a join with a BusinessFunction table. This is because, as we understand it, an UpdateAllQuery can only update ONE target component (table). The problem we're having is: how do you set a OneToOne FK reference field on the target component to NULL???
    2) To which descriptor are you adding the query key?
    Answer: The query key ("businessFuncId") must be, by convention, defined within the ReservedDetail aggregate mapping. When we map the ReservedDetail aggregate mapping within the RegisterImpl component mapping, we map the query key to the businessFunction FK field contained with the RegisterImpl table, (the target table we're trying to update).

  • How to persist interface in JPA?

    Hello guys,
    I am having a class which has a Interface reference as a attribute.
    If i want to persist my class how i can do that???
    class MyNode {
    //Ref of interface
    private MyInterface inter;
    If it is not possible then what it's workaround?? Because interface usage is essential. RIGHT???
    Regards,
    Nachiket

    You'll need to define the classes implementing the interface as JPA entities, and provide a @OneToOne mapping.
    Of course you'll need to design the mapping in such a way that you can get disparate objects to map correctly.
    Most likely that means you'll have to map from the contained entity to the containing entity.

  • Weaving (static and dynamic)

    I'm having a lot of difficulty setting up weaving (for entities with OneToOne lazy load relationships). I have searched all day on forums here and else where but to no avail on how to get this correctly setup.
    I am using Netbeans 5.5.1 for a standalone Java SE desktop applications, with JPA and toplink for the database access. This is what I have tried so far:
    1) Dynamically weaving using the <property name="toplink.weaving" value = "true" /> in the persistence.xml file and the "-javaagent:C:\libs\toplink-essentials-agent.jar" as the VM option at runtime. When doing this, the program begins but as soon as something is done to query an entity with a OneToOne relationship, an exception is thrown because methods on the "woven" entities are not found. It appears that the entity's methods are changed in one place but not in another perhaps?
    However, I would really like to statically weave these entities since ultimately deployment will be done using Java WebStart. I have tried to create an ant script to do this in the netbeans project build.xml file. This is what I have so far:
    <target name="define.task" description="New task definition for toplink static weaving">
    <taskdef name="weave" classname="oracle.toplink.essentials.weaving.StaticWeaveAntTask"
    classpath="libs/toplink-essentials.jar"/>
    </target>
    <target name="weaving" description="perform weaving" depends="define.task">
    <weave source="C:/JavaDev/projectName/dist/projectName.jar"
    target="C:/JavaDev/projectName/dist/projectName1.jar"
    loglevel="FINER">
    <classpath>
    <pathelement path="C:/JavaDev/projectName/libs/toplink-essentials.jar"/>
    </classpath>
    </weave>
    </target>
    (I am working of an example from an Oracle page.) The problems that I am running into with this are as follows:
    1) I don't really know what I am supposed to put in the <classpath> tag.
    2) When I run this through Netbeans (right click -> Run Target) it tries to run but at the first entity that it tries to weave none of the annotations appear to be recognized because it complains about the entity not having an @Id, etc.
    I am REALLY stumped on this and have spent a lot of time. Any help in regards to setting up static weaving with a Netbeans project would be GREATLY appreciated.
    Thanks in advance!

    Thanks for your response Doug.
    I have run it with that logging option and didn't notice anything out of the ordinary. The log says that it creates a temporary class loader, overrides load class for collection members (true), the weaver processes my classes, and registers a transformer.
    When I try to load an entity that has a OneToOne relationship, I get a:
    Exception [TOPLINK-0] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.IntegrityException
    followed by a:
    Exception [TOPLINK-60] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: The method [_toplink_setpatronData_vh] or [_toplink_getpatronData_vh] is not defined in the object [edu.byui.fitnesscommon.model.FitnessPerson].
    Internal Exception: java.lang.NoSuchMethodException: edu.byui.fitnesscommon.model.FitnessPerson._toplink_getpatronData_vh()
    Mapping: oracle.toplink.essentials.mappings.OneToOneMapping[patronData]
    Descriptor: RelationalDescriptor(edu.byui.fitnesscommon.model.FitnessPerson --> [DatabaseTable(FITNESS_PERSON)])
    Which gives a NullPointer runtime exception.
    I took out the fetch = FetchType.LAZY from the OneToOne mapping, and the program executes just fine.
    Thanks for your help on this. (Also if anyone knows anything about the static weaving, any help would be greatly appreciated.)

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

  • How to reduce clone/merge overhead in high cardinality 1:M relationships?

    Our application has numerous parent/child type 1:M relationships, where the collection size can be very large, and often the child object is itself very large. For these relationships, we have a catch-22 when using Toplink. Using the 1:M relationship with lazy loading and batch-reading is ideal for code that may or may not need the child objects. TopLink caching saves much SQL overhead when traversing the relationship in a read-only context. However, when making updates, the relationship becomes a burden, due to the overhead of cloning and merging the entire collection of objects. When we simply need to add a new object to the collection, TopLink automatically instantiates the collection, and makes clones and backup copies of all the contained objects. The database query is not needed, because the collection is stored in the cached parent object, but the copying overhead really hurts performance.
    What we need is a way to add or remove child objects in a UOW without this overhead, but still maintain the collection in the cached parent. I have been trying various things without any success. Is there documented pattern for this problem? Do I need to resort to using the AttributeChangeTrackingPolicy and/or a custom CopyPolicy, or is there a way I can avoid the cloning entirely?
    Thanks in advance.
    - Bruno

    Of the options you've suggested, I suspect the simplest and most performant option would be to use a postMerge handler to maintain the parent collection. This would work in a replicated cache as well, correct? How do I avoid introducing race conditions? Would I need to lock the parent object using the IdentityMapManager while I add or remove from the collection?
    As an aside, I must say that the documentation is really lacking for information about what is implied by a "bi-directional" mapping. What I have found through experimentation is that when the "relationshipPartner" is set on the OneToOne mapping for the back-reference, and basicIndirection is used, TopLink will automatically put the object in the parent's OneToMany collection when setValue() is called on the ValueHolderInterface, and thereafter it is essentially conformant within the UOW. Conversely if I create a child object and add it to the parent's collection, the back-reference will be set automatically on the child, as long as I use transparent indirection. I haven't tried it with basic indirection, but I suspect it won't work.
    However, it does all this by instantiating the ValueHolder on the parent container and thereby triggering the clone-merge of all the objects in the collection. This is the symptom I'd hoped to avoid. If I don't set the relationshipPartner, on the child mapping I can avoid this, but now my data access logic gets more complicated. What I really want to do is have something like a UnitOfWork within the collection itself. I want add and remove operations to be deferred. When I add or remove something to the collection, it would be kept in a holding area which would be merged into the parent cache when committed, but the ValueHolder would not be triggered. If/when the entire contents of collection is needed within the UnitOfWork, the ValueHolder would be instantiated, the collection contents would be cloned, and then the added/removed objects in the holding area would be merged into the collection. Am I missing any reasons why this approach is technically not feasible?
    The other suggestion to use the AttributeChangeTrackingPolicy has been considered, but I think that still won't be as good as what could be achieved by the above approach. There would still be a need to make clones for every object in the collection, and in order to avoid the drudgery of updating all my domain objects I'd have to resort to code-generation, or runtime method interception (we're not using CMP). I'm not quite ready to leap into that approach until all other alternatives have failed.
    As for the query cache, I would have to invalidate the entire query cache whenever objects are added or removed either locally or remotely, correct? TopLink won't check each query cache when an object is merged to determine if the object still matches the query criteria, correct? Are you saying that I would need to create my own cache invalidation policy to do this? I could handle removed objects that way, but I'd still need to invalidate the cache for any additions, right?
    I know this message is long. Please, any help is much appreciated.
    - Bruno

  • 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

  • Mapping question using @OneToOne @PrimaryKeyJoinColumn

    I am trying to create a simple web application to maintain a ContractAssignment table.
    Created an EJB from this table with @Id of contractNumber.
    public class ContractAssignment .....
    @Id
    @Column(name = "CONTRACT_NUMBER",
    nullable = false,updatable=false)
    private String contractNumber;
    @OneToOne @PrimaryKeyJoinColumn
    private Contract contractInfo;
    I need contract info that exists in multiple tables so I created a view called Contract.
    Created an EJB for this view with @Id of contractNumber.
    public class Contract ......
    @Id
    @Column(name="CONTRACT_NUMBER", nullable = false,updatable=false)
    private String contractNumber;
    I will only be maintaining the ContractAssignment EJB.
    The Contract EJB will NOT be maintained by this app.
    It will only be used to obtain valid contract numbers that can be used in ContractAssignment maintenance.
    It will also be used to display contract information when maintaining the ContractAssignment.
    Is this the right way to map the relationship?
    Another question. I've created a search page to look up ContractAssignments.
    For some reason, the SQL generated is joining the table to itself.
    Not sure if this is because of incorrect mapping (described above).
    SQL that was generated:
    SELECT t0.CONTRACT_NUMBER, t0.DESCRIPTION, t0.CONTRACT_START_DATE, t0.IMS_STATUS
    FROM CONTRACT_ASSIGNMENT t0,
    CONTRACT_ASSIGNMENT t1
    WHERE (CONTRACT_NUMBER = ?)
         bind => [1234]
    from the following OQL:
    select o from ContractUserAssignment o where ocontractNumber like :contractNumber
    What is causing the incorrect join?
    Thank you for any help.

    All - Thanks much.. Here is my requirement that is no solved by regular mapping
    <Root>
    <Recordset>
      <Ordheader>
        <ord>
        <ord_type>
      </Ordheader>
       <Ord_line>
         <ord>
         <Linnum>
       </Ord_line>
      </Recordset>
    <Recordset>
      <Ordheader>
        <ord>
        <ord_type>
      </Ordheader>
       <Ord_line>
         <ord>
         <Linnum>
       </Ord_line>
    </Recordset>
    <Root>
    As you see above, each recordset has order transaction. One Root message can contain multiple of these. So, when I map to the IDOC, I want to filter out any ord_type <> XX.
    If I use regular graphical map, it only looks at first recordset and accepts all or rejects all.
    I need to use UDF. In the UDF, what comes in as input ? Resultset is output -correct ? Now how do I usse graphical mapping with UDF to generate the correct target info

Maybe you are looking for

  • FI-GL allocation - distribution error: no valid receiver entries exist

    When creating an allocation cycle with fixed percentages and distribution defined on own Z-field (exists in table T800D without checks) we get Message no. GA109 when going to the receiver tracing factor screen. This happens only when entering a range

  • Error while starting ERS instance

    Hi , Not able to start ERS instance .Seems some permission issue has been occour. while starting instance giving error /usr/sap/SID/ERS11/exe/sapcontrol -prot NI_HTTP -nr 11 -function Start startup of Instance failed See /home/sidadm/startsap_ERS11.l

  • Sybase JDBC driver & Invalid column name error

    I submitted a note a year ago concerning JDBC-ODBC bridge and SQL Server db. Same Invalid column name error. The resolution was a bug in the XSU code. This time the error is with a jconnect5 JDBC driver from Sybase to a Sybase ASA db. ASA is Adaptive

  • Some contacts missing on both iPhone and Outlook since installing iOS 7.1

    I have an iPhone 5S which I successfully sync to Outlook 2007 using iCloud, until recently when I upgraded to iOS 7.1. Most contacts are still there on both my PC and iPhone, but as luck would have it, the ones missing are mostly the important ones f

  • Table model and default model

    Hi All, can u tell me how to use table model or default table model. where i can references about it??? thanks for all