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

Similar Messages

  • 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

  • Couldn't persist OneToMany JoinColumn/JoinTable (Unidir) using TopLink JPA

    Hi All,
    I am having a lot of difficulty deploying a OneToMany Unidirectional (Zipcode) record which consist of multiple Zipnames using TopLink on Glassfish v2r2, JDK1.6.0_06, MySQL 5.0, Netbeans 6.1 and Windows XP platform.
    Below are the relevant EJBs snippets:
    Zipcode class
    @Entity
    @Table(name="ZIPCODE")
    public class Zipcode implements Serializable {
    @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
    @JoinColumn(name="ZIPCODE_ID")    
                 or
        @JoinTable(name="ZIPCODE_ZIPNAME",          
                   joinColumns={@JoinColumn(name="ZIPCODE_ID")},
                   inverseJoinColumns={@JoinColumn(name="ZIPNAME_ID")})
        private Collection<Zipname> zipnames = new ArrayList<Zipname>();
        public Collection<Zipname> getNames()
         return zipnames;
        public void setZipnames(Collection<Zipname> zipnames)
         this.zipnames = zipnames;
    Zipname class does not maintain relationship back to Zipcode.
    public class ZipcodeApplicationClient {
    @PersistenceContext(unitName="GeographicalDB-PU")
    private static EntityManager manager;
        public ZipcodeApplicationClient() {
        public static void main(String[] args) {
            try {
                Zipcode zipcode_1 = new Zipcode();
                zipcode_1.setcode(9001);
                Zipname zipname_1 = new Zipname();
                zipname_1.setName("Harbour Cove");
                zipcode_1.getNames().add(zipname_1);
                // Can add one Zipname record with JoinTable but not JoinColumn
                Zipname zipname_2 = new Zipname();
                zipname_2.setName("Wonderland");
                zipcode_1.getNames().add(zipname_2);
                manager.persist(zipcode_1);   // line 45
    The same deployment error message below was generated from both JoinColumn and JoinTable methods:
    run-deploy:
    run-display-browser:
    run-ac:
    Copying 1 file to C:\Documents and Settings\Jack\GeographicalBean\dist
    Caught an unexpected exception!
    java.lang.NullPointerException
            at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:45)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:266)
            at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:449)
            at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:259)
            at com.sun.enterprise.appclient.Main.main(Main.java:200)
    run-InvestmentBean-app-client:The JoinColumn method would not work for one Zipname record. On the other hand, JoinTable approach would allow us to add a single Zipname record without error out.
    Q1. Can you confirm whether TopLink JPA 1.0 (Glassfish v2r2) support OneToMany JoinColumn Unidirectional at all?
    Q2. Does TopLink JPA 1.0 (Glassfish v2r2) support OneToMany JoinTable Unidirectional? If so, what is the cause of this issue? Otherwise, please make appropriate recommendation steps to take.
    This question has been posted on http://forums.sun.com/thread.jspa?threadID=5330670&tstart=0 and http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=78&t=004489&p=1 earlier in the hope a quicker response.
    Your guidance would be very much appreciated.
    Many thanks,
    Jack

    Hi,
    Below are some more error output from the OneToMany JoinTable Unidirectional approach:
    pre-run-deploy:
    Initial deploying InvestmentBean to C:\Documents and Settings\abc\InvestmentBean\dist\gfdeploy
    Completed initial distribution of InvestmentBean
    Start registering the project's server resources
    Finished registering server resources
    moduleID=InvestmentBean
    deployment started : 0%
    deployment finished : 100%
    Deploying application in domain completed successfully
    Trying to create reference for application in target server completed successfully
    Trying to start application in target server completed successfully
    WARNING:
    JDO76614: Deployment encountered SQL Exceptions:
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPCODE (ID INTEGER NOT NULL, DIALING_CODE VARCHAR(255), TIME_ZONE VARCHAR(255), CODE INTEGER, NEAREST_AIRPORT VARCHAR(255), LONGITUDE VARCHAR(255), NEAREST_TRAIN_STATION VARCHAR(255), NEAREST_URBAN_CENTRE VARCHAR(255), HOTELS VARCHAR(255), LATITUDE VARCHAR(255), NEARBY_FEATURES VARCHAR(255), COUNCIL VARCHAR(255), LOCALITY VARCHAR(255), PRIMARY KEY (ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipcode' already exists
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPCODE_ZIPNAME (ZIPCODE_ID INTEGER NOT NULL, ZIPNAME_ID INTEGER NOT NULL, PRIMARY KEY (ZIPCODE_ID, ZIPNAME_ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipcode_zipname' already exists
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPNAME (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipname' already exists
    JDO76609: Got SQLException executing statement "ALTER TABLE ZIPCODE_ZIPNAME ADD CONSTRAINT FK_ZIPCODE_ZIPNAME_ZIPCODE_ID FOREIGN KEY (ZIPCODE_ID) REFERENCES ZIPCODE (ID)": java.sql.SQLException: Can't create table '.\geographicaldb\#sql-434_4.frm' (errno: 121)
    JDO76609: Got SQLException executing statement "ALTER TABLE ZIPCODE_ZIPNAME ADD CONSTRAINT FK_ZIPCODE_ZIPNAME_ZIPNAME_ID FOREIGN KEY (ZIPNAME_ID) REFERENCES ZIPNAME (ID)": java.sql.SQLException: Can't create table '.\geographicaldb\#sql-434_4.frm' (errno: 121)Enable of InvestmentBean in target server completed successfully
    Enable of application in all targets completed successfully
    All operations completed successfully
    post-run-deploy:
    run-deploy:
    run-display-browser:
    run-ac:
    Copying 1 file to C:\Documents and Settings\Jack\GeographicalBean\dist
    Caught an unexpected exception!
    java.lang.NullPointerException
    at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:266)
    at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:449)
    at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:259)
    at com.sun.enterprise.appclient.Main.main(Main.java:200)
    run-GeographicalBean-app-client:
    run:
    I would like to correct an earleir comment where I stated that this method did work when adding a single Zipname record. This is no true.
    Thanks,
    Jack

  • JPA OneToMany mapping whit toplink...

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

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

  • OneToMany differences - Hibernate EntityManager 3.3.1 and TPL11.1.1.0.0

    Two entities 'Employee' and 'Address'. Employees as a collection of 'Addresses' and I want to map this OneToMany unidirectionally. In doing so I've noticed some differences between Hibernate EM 3.3.1 and TPL 11.1.1.0.0. Apart from the fact that I didn't manage to get this OneToMany mapping working in Toplink - can somebody explain why there is a difference, since it is standard.
    @OneToMany without any other annotations in Hibernate results in (With ddl creation on):
    a created intersection/jointable containing two FKs for each relationship end.
    @OneToMany without any other annotations in Toplink results in (With ddl creation on):
    Exception Description: [class com.cumquatit.research.derby.domain.Employee] uses a non-entity [class com.cumquatit.research.derby.domain.Address] as target entity in the relationship attribute [private java.util.Collection com.cumquatit.research.derby.domain.Employee.addresses].
    @OneToMany with @JoinColumn(name="EMPLOYEE_ID") in Hibernate results in:
    a created column (EMPLOYEE_ID) at the Address table which is FK to Employee.
    @OneToMany with @JoinColumn(name="EMPLOYEE_ID") in Toplink results in:
    Exception Description: one-to-many for attribute name [addresses] in entity class [class com.cumquatit.research.derby.domain.Employee] should not have join-column(s) specified. In the case where the one-to-many is not mapped by another entity (that is, it is the owning side and is uni-directional), it should specify (optional through defaulting) a join-table.
    Thanks (again),
    -J.

    Update -
    Having established that the @OneToMany + @JoinColumn annotation as accepted by Hibernate is non-standard, and the fact that that unidirectional OneToMany relationships should be implemented using a JoinTable, I have found yet another error (of mine) that Hibernate is ironing out.
    Regardind @OneToMany and Toplink I now can confirm that this indeed works according to specs. Toplink will create the tables like so:
    CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, EMPLOYEENUMBER VARCHAR(10)
    UNIQUE NOT NULL, GENDER VARCHAR(255), FULLNAME VARCHAR(255), HIREDATE DATE,
    EMAIL_ADDRESS VARCHAR(255), PRIMARY KEY (ID))
    CREATE TABLE ADDRESS (ID INTEGER NOT NULL, ADDRESSLINEONE VARCHAR(255), CITY
    VARCHAR(255), ZIPCODE VARCHAR(255), PRIMARY KEY (ID))
    CREATE TABLE EMPLOYEE_ADDRESS (Employee_ID INTEGER NOT NULL, addresses_ID
    INTEGER NOT NULL, PRIMARY KEY (Employee_ID, addresses_ID))
    ALTER TABLE EMPLOYEE_ADDRESS ADD CONSTRAINT MPLYADDRESSmplyeID FOREIGN KEY
    (Employee_ID) REFERENCES EMPLOYEE (ID)
    ALTER TABLE EMPLOYEE_ADDRESS ADD CONSTRAINT MPLYDDRESSddrsssID FOREIGN KEY (addresses_ID) REFERENCES ADDRESS (ID)The thing I was missing - silly mistake coming - was to incorporate the entity class in the orm.xml file as it is references from the persistence.xml file. Not doing so in Toplink will yield:
    Exception Description: [class com.cumquatit.research.derby.domain.Employee] uses a non-entity [class com.cumquatit.research.derby.domain.Address] as target entity in the relationship attribute [private java.util.Collection com.cumquatit.research.derby.domain.Employee.addresses].It looks like Hibernate simply corrects my mistake by implicitly using the referenced class.

  • ManyToOne relationship with extra field in the joinTable

    Hi,
    I wanted to make a ManyToMany unidirectional relationship using these two entities.
    Invoice (id)
    Product (id, price)
    The problem is that I want in the resulting joinTable another field named QUANTITY
    I don’t think there is a way to obtain a join table with an extra field from a ManyToMany relationship, am I right ?
    Si I decided to add an InvoiceLine table
    With Invoice and InvoiceLine tables having a OneToMany unidirectional relationship.
    And InvoiceLine and Product tables having a ManyToOne unidirectional relationship.
    This is the code I made
    import java.util.Set;
    import java.util.HashSet;
    import javax.persistence.*;
    @Entity
    public class Invoice implements java.io.Serializable {
         private long id;
         private Set<InvoiceLine> InvoiceLines = new HashSet<InvoiceLine>();
         @Id
         @GeneratedValue
         public long getId() {
              return id;
         public void setId(long id) {
              this.id = id;
         @OneToMany(cascade={CascadeType.ALL})
         @JoinColumn(name="INVOICE_ID")
         public Set<InvoiceLine> getInvoiceLines() {
              return InvoiceLines;
         public void setInvoiceLines(Set<InvoiceLine> InvoiceLines) {
              this.InvoiceLines = InvoiceLines;
    import javax.persistence.*;
    @Entity
    public class InvoiceLine implements java.io.Serializable {
         private long id;
         private Product product;
         private int quantity;
         @Id
         @GeneratedValue
         public long getId() {
              return id;
         public void setId(long id) {
              this.id = id;
         @ManyToOne
         public Product getProduct() {
              return product;
         public void setProduct(Product product) {
              this.product = product;
         public int getQuantity() {
              return quantity;
         public void setQuantity(int quantity) {
              this.quantity = quantity;
    import javax.persistence.*;
    @Entity
    public class Product implements java.io.Serializable {
         private long id;
         private double price;
         public Product() {
         public Product(double price) {
              this.price = price;
         @Id
         @GeneratedValue
         public long getId() {
              return id;
         public void setId(long id) {
              this.id = id;
         public double getPrice() {
              return price;
         public void setPrice(double price) {
              this.price = price;
    }The problem is that I want the InvoiceLine table to have a composite primary key (from the two foreign keys in the table invoice_id and product_id).
    Can anyone tell me how I can do this.
    Thanks.
    Edited by: Exhortae on Jun 23, 2009 4:59 PM
    Edited by: Exhortae on Jun 23, 2009 5:01 PM

    Hello,
    If we create a Z report for this program, can anyone please tell me where can I find the function "REUSE_ALV_GRID_DISPLAY" in the given program so that I can add my fields along with the default filelds displayed...
    Thanks
    ~Him

  • How can I establish many to many unidirectional relationship?

    Hi, EJB Fans!
    I am an ejb fan too.
    This time I am learn ejb2.0 and find very funny in cmr. I think it is a good idea and can do manythings we cann't do or difficult with ejb1.1.
    But in many to many relationship, I don't know how to give my tables to entity A and entity B. How can I define tables to make A contains related Bs' information? And so do B. But i think make this table is difficult, because we don't know exactly how many should contains? And this is an examples:
    Difine entity A as User, and B as roles such as Administration, user, power user, as we often used in network. A user can have many roles, and roles can allocated to many roles.
    Another examples is entity A as person, and B as Department. B container A, and A can join many department as he or she can.
    B can find A(s) with which clues?? Methods like this java.util.Collection getAs()
    , this collection how can ejb container caculate it out?
    It is very myth, even wonderful!
    I love java and more like ejbs.

    No body reply.
    My question is silly or my english is very bad.
    Sorry I am chinese-speaking programmer.

  • JPA Object-Relational Mapping: how to deal with self-related mapping?

    ignore the post.
    sorry for my stupidity
    ==
    Hello,
    Suppose I have a class nemed Group, which can have sub-groups. It is defined like:
    @Entity
    Class Group{
    private int id;
    private String name;
    private Group parent; //M-1 mapping
    The problem is Group is mapped to itself:
    child group -- parent group
    M : 1
    How JPA supports that kind of relationship? Can I put both
    @Many-to-One and @One-to-Many over parent field like:
    @Many-to-One
    @One-to-Many
    private Group parent;
    Thanks a lot!
    Message was edited by:
    javasprinter

    One possibility could be the following - (included annotation mappings):
    @Entity
    Class Group{
    private int id; // probably should change to Integer to account for null data
    private String name;
    @ManyToOne
    @JoinColumn(name = "PARENT_GROUP_FK")
    private Group parent; //M-1 mapping
    @OneToMany
    @JoinTable ( name = "SUB_GROUPS",
    joinColumns = { @JoinColumn(name = "PARENT_GROUP_ID")},
    inverseJoinColumns = {@JoinColumn(name = "CHILD_GROUP_ID")}
    private List subGroups;
    Tables -
    Group - columns - id, name, parent_group_fk
    Sub_groups - columns - parent_group_id, child_group_id
    The above maps a unidirectional relationship from parent group to child groups, but that really isn't a big deal because you can always get the parent from the parent group id.
    I'm sure this isn't the best way, but it worked for me. HTH.

  • Strange @OneToMany generated schema

    Hi all,
    I just deploy 2 Entities (User and Contact) that are aggregated using a non bijective OneToMany annotation
    public class User implements serializable {
    @OneToMany(cascade=CascadeType.PERSIST)
    private List <Contact> contacts;
    And no user field into Contact class (so I can easily serialize User including theirs contacts without circular reference in XML style)
    The underlying mysql schema is really strange and is not functional at all, cause not null column reference problem occur when I try to create a new Contact.
    I expect to have a contact table with a foreign key user_id field that could be null (a contact can exist without user), but the Toplink essential generate a contact table with an User_ID and a contacts_ID fields, and this fields cannot be null and act as primary key of this table ....
    And so when creating a new Contact, a problem occur when inserting a null value for user_id (and contacts_id).
    My environment :
    IDE :
    - Product Version: NetBeans IDE 6.0 (Build 200711261600)
    - Java: 1.5.0_13; Java HotSpot(TM) Client VM 1.5.0_13-121
    - Glasshfish v2ur1
    - Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))
    I've created a complete Test suite project where I had reproduce this behaviour (excluding all my other stuff around to spot this point)
    So my question is : how to generate a correct DB Schema and not this buggy one ? Is there something that I misunderstand ?
    And last : how can I influence Toplink to make the correct thing ? I didn't find any annotation to fine grain schema strategy adjustments.
    Any help will be welcome ;)
    update information :
    I try with postgresql 8.2 instead of mysql ... and I'got the same strange schema.
    I try a new project from scratch and same thing ...
    I deploy with Hibernate 3 instead of Toplink and this time generated schema is more usable (but not efficient as it could be using normal rdbms modeling rules)
    So Toplink seem to be the accused in my problem.. I'll submit this problem to Oracle part and keep Hibernate running ;)
    Edited by: AymericB on Apr 3, 2008 6:27 AM

    Hello,
    It looks you have a unidirectional 1:M between User and Contact. Because you don't have a ManyToOne back pointer from Contact to User, the OneToMany is essentially the same as a ManyTomany in that it requires a relation table. So I believe what you are seeing is a User_Contact relation table that will have User_id and contact_id fields, but nothing else. I think you should be seeing 3 tables - 2 for the entities and 1 for the relation table, and cannot explain why you would have problems inserting new Contacts without more information, but I would suspect something else might be going wrong.
    If you want Contact to have a foreign key to User, you will need to have a ManyToOne reference to user, then have the OneToMany specify it is mapped by the ManyToOne attribute.
    @ManyToOne
    private User user;
    @OneToMany(mappedBy="user", cascade=CascadeType.PERSIST)
    private List <Contact> contacts
    Best Regards,
    Chris

  • Unidirectional one-to-many relationship without a join table

    Hello,
    I have 2 classes, Invoice and InvoiceLine, and a one-to-many unidirectional relationship from Invoice to InvoiceLine. By default, with JPA, it would be mapped by a join table with foreign keys that refer to the 2 tables which represent Invoice and InvoiceLine.
    My problem: the database has already a foreign key in the table which represents InvoiceLine that refers to the table which represents Invoice.
    To solve my problem I could make the relationship bidirectional but I would like to know if it is possible to keep it unidirectional and to use the foreign key which already exists (in the table that represents InvoiceLine). How could I declare the mapping with JPA?
    Thanks in avance for your answers.

    JPA requires that any @OneToMany mapping not using a join table have an inverse @ManyToOne mapping. In general the foreign key in the target object needs to be mapped and a @ManyToOne mapping is normally the best way to map it, so making the relationship bi-directional is your best option.
    There are other ways in TopLink to map a unidirectional 1-m, but these are not directly supported by the JPA spec. You could define a TopLink OneToManyMapping for the relationship through a TopLink DescriptorCustomizer and the code API. You would still need to map the foreign key in the target object some way, but you could use a @Basic mapping for this as long as you keep it in synch.
    In TopLink you could also map the relationship using an AggregateCollectionMapping (basically a collection of embeddables), and then not require mapping the foreign key in the target, but this imposes limitations on the target object (must be treated like an embeddable instead of entity). You would also need to configure the target object to be an aggregateCollectionDescriptor if using this option.

  • How to automate a unilateral sync from Aperture to an FTP server?

    +You can export multiple Projects at once:+
    +1. Select the top-level *Blue Folder*, this will show all the images from all the Projects in it.+
    +2. Select all the Versions.+
    +3. Export, using the image export preset of your choice, and a folder-naming preset made up of 'Folder Name', '/' & 'Project Name'.+
    +This will export the whole lot in one go, into a subfolder structure of 'name of *Blue Folder*'/'Name of Project'. Note that it will only take the name of the topmost *Blue Folder*, so it will only work for single-level *Blue Folder* structures.+
    I want to take this one step further. My goal is to have a "mirror" of a given *Blue Folder* (with the projects and sub-folders represented as sub-directories as accomplished by the advice above) not just on my hard drive, but on a (private) FTP server. In essence, I want a significant percentage of my photo database mirrored on an FTP server. Note that this is not for backup purposes but for sharing the contents of my photo library (the portion of it that is appropriate to share--for example photos of family events, travels, etc.)
    Currently my workflow is to click the *Blue Folder* that houses all of my family photos, select all versions, and export to a directory as advised above: Folder Name / Project Name. That takes a long time. Then I ftp the entire exported-directory tree to my FTP server. I try to do this cleverly by taking advantage of Yummy FTP's relatively new "sync" feature that compares my source directory tree with the destination directory tree, deletes files on the destination FTP server that aren't in the source file tree and uploads only the files in the source tree that aren't present in the destination tree (i.e. a unidirectional sync).
    This works well enough, but it seems like a process that could be readily automated. Does anyone know of an Aperture plugin that can accomplish this workflow? Ubermind's plugin "UberUpload for Aperture" appears to come close, but it doesn't approximate the Project-Name/Folder-Name to directory tree conversion and it doesn't delete files on the destination FTP server, so it doesn't accomplish the unilateral sync I'm looking for.
    Are there any other plug-ins I should look at; are there any other plug-ins you know of that might accomplish this task?
    Thank you,
    George
    This is a new question but partially in response to a previous post (here --> http://discussions.apple.com/thread.jspa?threadID=1586469) that was marked answered.

    Hmm, that's a possibility, made a little more difficult by the fact that I don't know how to write Applescript. I understand that it's not too difficult to pick up, but that will add to the time required to figure this out (especially if there's no documentation for calls to Aperture--is there really no documentation?). The simplest way to do this with Applescript would probably be to run a script that exports my library of photographs into a file structure as described above, then runs the sync commands available through YummyFTP, and finally deletes the exported files off my hard drive. The major drawbacks to this approach include the long time required for export (and sync if there are a large number of changes) and the need to have a significant amount of free hard drive space (probably 10 gigs in my case) which could be potentially be a problem if one were running low on disk space.

  • How to create a cache for JPA Entities using an EJB

    Hello everybody! I have recently got started with JPA 2.0 (I use eclipseLink) and EJB 3.1 and have a problem to figure out how to best implement a cache for my JPA Entities using an EJB.
    In the following I try to describe my problem.. I know it is a bit verbose, but hope somebody will help me.. (I highlighted in bold the core of my problem, in case you want to first decide if you can/want help and in the case spend another couple of minutes to understand the domain)
    I have the following JPA Entities:
    @Entity Genre{
    private String name;
    @OneToMany(mappedBy = "genre", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<Novel> novels;
    @Entity
    class Novel{
    @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Genre genre;
    private String titleUnique;
    @OneToMany(mappedBy="novel", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<NovelEdition> editions;
    @Entity
    class NovelEdition{
    private String publisherNameUnique;
    private String year;
    @ManyToOne(optional=false, cascade={CascadeType.PERSIST, CascadeType.MERGE})
    private Novel novel;
    @ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Catalog appearsInCatalog;
    @Entity
    class Catalog{
    private String name;
    @OneToMany(mappedBy = "appearsInCatalog", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<NovelEdition> novelsInCatalog;
    The idea is to have several Novels, belonging each to a specific Genre, for which can exist more than an edition (different publisher, year, etc). For semplicity a NovelEdition can belong to just one Catalog, being such a Catalog represented by such a text file:
    FILE 1:
    Catalog: Name Of Catalog 1
    "Title of Novel 1", "Genre1 name","Publisher1 Name", 2009
    "Title of Novel 2", "Genre1 name","Pulisher2 Name", 2010
    FILE 2:
    Catalog: Name Of Catalog 2
    "Title of Novel 1", "Genre1 name","Publisher2 Name", 2011
    "Title of Novel 2", "Genre1 name","Pulisher1 Name", 2011
    Each entity has associated a Stateless EJB that acts as a DAO, using a Transaction Scoped EntityManager. For example:
    @Stateless
    public class NovelDAO extends AbstractDAO<Novel> {
    @PersistenceContext(unitName = "XXX")
    private EntityManager em;
    protected EntityManager getEntityManager() {
    return em;
    public NovelDAO() {
    super(Novel.class);
    //NovelDAO Specific methods
    I am interested at when the catalog files are parsed and the corresponding entities are built (I usually read a whole batch of Catalogs at a time).
    Being the parsing a String-driven procedure, I don't want to repeat actions like novelDAO.getByName("Title of Novel 1") so I would like to use a centralized cache for mappings of type String-Identifier->Entity object.
    Currently I use +3 Objects+:
    1) The file parser, which does something like:
    final CatalogBuilder catalogBuilder = //JNDI Lookup
    //for each file:
    String catalogName = parseCatalogName(file);
    catalogBuilder.setCatalogName(catalogName);
    //For each novel edition
    String title= parseNovelTitle();
    String genre= parseGenre();
    catalogBuilder.addNovelEdition(title, genre, publisher, year);
    //End foreach
    catalogBuilder.build();
    2) The CatalogBuilder is a Stateful EJB which uses the Cache and gets re-initialized every time a new Catalog file is parsed and gets "removed" after a catalog is persisted.
    @Stateful
    public class CatalogBuilder {
    @PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @EJB
    private Cache cache;
    private Catalog catalog;
    @PostConstruct
    public void initialize() {
    catalog = new Catalog();
    catalog.setNovelsInCatalog(new ArrayList<NovelEdition>());
    public void addNovelEdition(String title, String genreStr, String publisher, String year){
    Genre genre = cache.findGenreCreateIfAbsent(genreStr);//##
    Novel novel = cache.findNovelCreateIfAbsent(title, genre);//##
    NovelEdition novEd = new NovelEdition();
    novEd.setNovel(novel);
    //novEd.set publisher year catalog
    catalog.getNovelsInCatalog().add();
    public void setCatalogName(String name) {
    catalog.setName(name);
    @Remove
    public void build(){
    em.merge(catalog);
    3) Finally, the problematic bean: Cache. For CatalogBuilder I used an EXTENDED persistence context (which I need as the Parser executes several succesive transactions) together with a Stateful EJB; but in this case I am not really sure what I need. In fact, the cache:
    Should stay in memory until the parser is finished with its job, but not longer (should not be a singleton) as the parsing is just a very particular activity which happens rarely.
    Should keep all of the entities in context, and should return managed entities form mehtods marked with ##, otherwise the attempt to persist the catalog should fail (duplicated INSERTs)..
    Should use the same persistence context as the CatalogBuilder.
    What I have now is :
    @Stateful
    public class Cache {
    @PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @EJB
    private sessionbean.GenreDAO genreDAO;
    //DAOs for other cached entities
    Map<String, Genre> genreName2Object=new TreeMap<String, Genre>();
    @PostConstruct
    public void initialize(){
    for (Genre g: genreDAO.findAll()) {
    genreName2Object.put(g.getName(), em.merge(g));
    public Genre findGenreCreateIfAbsent(String genreName){
    if (genreName2Object.containsKey(genreName){
    return genreName2Object.get(genreName);
    Genre g = new Genre();
    g.setName();
    g.setNovels(new ArrayList<Novel>());
    genreDAO.persist(t);
    genreName2Object.put(t.getIdentifier(), em.merge(t));
    return t;
    But honestly I couldn't find a solution which satisfies these 3 points at the same time. For example, using another stateful bean with an extended persistence context (PC) would work for the 1st parsed file, but I have no idea what should happen from the 2nd file on.. Indeed, for the 1st file the PC will be created and propagated from CatalogBuilder to Cache, which will then use the same PC. But after build() returns, the PC of CatalogBuilder should (I guess) be removed and re-created during the succesive parsing, although the PC of Cache should stay "alive": shouldn't in this case an exception being thrown? Another problem is what to do when the Cache bean is passivated. Currently I get the exception:
    "passivateEJB(), Exception caught ->
    java.io.IOException: java.io.IOException
    at com.sun.ejb.base.io.IOUtils.serializeObject(IOUtils.java:101)
    at com.sun.ejb.containers.util.cache.LruSessionCache.saveStateToStore(LruSessionCache.java:501)"
    Hence, I have no Idea how to implement my cache.. Can you please tell me how would you solve the problem?
    Many thanks!
    Bye

    Hi Chris,
    thanks for your reply!
    I've tried to add the following into persistence.xml (although I've read that eclipseLink uses L2 cache by default..):
    <shared-cache-mode>ALL</shared-cache-mode>
    Then I replaced the Cache bean with a stateless bean which has methods like
    Genre findGenreCreateIfAbsent(String genreName){
    Genre genre = genreDAO.findByName(genreName);
    if (genre!=null){
    return genre;
    genre = //Build new genre object
    genreDAO.persist(genre);
    return genre;
    As far as I undestood, the shared cache should automatically store the genre and avoid querying the DB multiple times for the same genre, but unfortunately this is not the case: if I use a FINE logging level, I see really a lot of SELECT queries, which I didn't see with my "home made" Cache...
    I am really confused.. :(
    Thanks again for helping + bye

  • How to use Oracle partitioning with JPA @OneToOne reference?

    Hi!
    A little bit late in the project we have realized that we need to use Oracle partitioning both for performance and admin of the data. (Partitioning by range (month) and after a year we will move the oldest month of data to an archive db)
    We have an object model with an main/root entity "Trans" with @OneToMany and @OneToOne relationships.
    How do we use Oracle partitioning on the @OneToOne relationships?
    (We'd rather not change the model as we already have millions of rows in the db.)
    On the main entity "Trans" we use: partition by range (month) on a date column.
    And on all @OneToMany we use: partition by reference (as they have a primary-foreign key relationship).
    But for the @OneToOne key for the referenced object, the key is placed in the main/source object as the example below:
    @Entity
    public class Employee {
    @Id
    @Column(name="EMP_ID")
    private long id;
    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ADDRESS_ID")
    private Address address;
    EMPLOYEE (table)
    EMP_ID FIRSTNAME LASTNAME SALARY ADDRESS_ID
    1 Bob Way 50000 6
    2 Sarah Smith 60000 7
    ADDRESS (table)
    ADDRESS_ID STREET CITY PROVINCE COUNTRY P_CODE
    6 17 Bank St Ottawa ON Canada K2H7Z5
    7 22 Main St Toronto ON Canada     L5H2D5
    From the Oracle documentation: "Reference partitioning allows the partitioning of two tables related to one another by referential constraints. The partitioning key is resolved through an existing parent-child relationship, enforced by enabled and active primary key and foreign key constraints."
    How can we use "partition by reference" on @OneToOne relationsships or are there other solutions?
    Thanks for any advice.
    /Mats

    Crospost! How to use Oracle partitioning with JPA @OneToOne reference?

  • How to retrieve detached @ManyToOne entities with relationship

    Hi All,
    I am having difficulty retrieving all the Zipcode, Zipname records which have successfully been deployed on Glassfish v2r2, JDK1.6.0_06, MySQL 5.0, Netbeans 6.1 on Windows XP platform.
    Below are the relevant EJBs snippets:
    package domain;
    @Entity
    @Table(name="ZIPCODE")
    public class Zipcode implements Serializable {
        @Id
        @Column(name="ID")
        private int id;
        public int getId() {
            return id;
        @OneToMany(cascade={CascadeType.ALL}, mappedBy="zipcode", fetch=FetchType.EAGER, targetEntity=Zipname.class)
        private Collection<Zipname> zipnames = new ArrayList<Zipname>();
        public Collection<Zipname> getNames()
         return zipnames;
    package domain;
    @Entity
    @Table(name="ZIPNAME")
    public class Zipname implements Serializable {
        @Id
        @Column(name="ID")
        private int id;
        public void setId(int id) {
            this.id = id;
        @ManyToOne(fetch=FetchType.EAGER)
        @JoinColumn(name="ZIPCODE_ID")
        private Zipcode zipcode;
        public Zipcode getZipcode() {
            return zipcode;
    package ejb;
    @Stateless
    public class ZipcodeBean implements ZipcodeRemote {
        @PersistenceContext(unitName="GeographicalDB") private EntityManager manager;
        public void createZipcode(Zipcode zipcode)
           manager.persist(zipcode);
        public Zipcode findZipcode(int pKey)
           Zipcode zipcode = manager.find(Zipcode.class, pKey);
            zipcode.getNames().size();
            return zipcode;
        public List fetchZipcodesWithRelationships()
          List list = manager.createQuery("FROM Zipcode zipcode").getResultList();
          for (Object obj : list)
             Zipcode zipcode = (Zipcode)obj;
             zipcode.getNames().size();
          return list;
    @Stateless
    public class ZipnameBean implements ZipnameRemote {
        @PersistenceContext(unitName="GeographicalDB") private EntityManager manager;
        public void createZipname(Zipname zipname)
         manager.persist(zipname);
        public Zipname findZipname(int pKey)
            Zipname zipname = manager.find(Zipname.class, pKey);
            zipname.getZipcode().getNames().size();
            return zipname;
        public List fetchZipnamesWithRelationships()
          List list = manager.createQuery("FROM Zipname zipname").getResultList();
          for (Object obj : list)
             Zipname zipname = (Zipname)obj;
             zipname.getZipcode().getNames().size();
          return list;
    public class ZipcodeApplicationClient {
        @EJB
        private static ZipcodeRemote zipcodebean;
        private static ZipnameRemote zipnamebean;
        public ZipcodeApplicationClient() {
        public static void main(String[] args) {
            try {
                Zipcode zipcode_1 = new Zipcode();
                zipcode_1.setcode(9001);
                Zipname zipname_1 = new Zipname();
                zipname_1.setName("Harbour Cove");
                zipcode_1.getNames().add(zipname_1);
                zipname_1.setZipcode(zipcode_1);
    //          zipnamebean.createZipname(zipname_1);
                zipcodebean.createZipcode(zipcode_1);
                //fetch detached entity without relationship
                Zipcode zipcode_2 = zipcodebean.findZipcode(0);
                System.out.println("zipcode_2.getId(): " + zipcode_2.getId());
                System.out.println("zipcode_2.getCode(): " + zipcode_2.getCode());
                Iterator iterator = zipcode_2.getNames().iterator();
                while (iterator.hasNext())
                    System.out.println(iterator.next().toString());
                // output of fetching detached entity without relationship
                zipcode_2.getId(): 0
                zipcode_2.getCode(): 2010
                domain.ZipName@107e9a8
                zipcode_2.getLatitude: -33.883
                zipcode_2.getLongitude(): 151.216
                zipcode_2.getLocality(): Sydney
                //fetch detached entity with relationship
                List list =  zipcodebean.fetchZipcodesWithRelationships(); // line 76         
                // output of fetching detached entity with relationship
                           Caught an unexpected exception!
                           javax.ejb.EJBException: nested exception is: java.rmi.MarshalException: CORBA BAD_PARAM 1330446342 Maybe; nested exception is:
                           java.io.NotSerializableException: ----------BEGIN server-side stack
                           at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:76)
                           -------------------------------------------------------------------------------------------------------------------------------------------( i ) As a result, please advice on how to utilise both fetchZipcodesWithRelationships() & fetchZipnamesWithRelationships() in ZipcodeApplicationClient() to retrieve collections of Zipcodes & Zipnames without encountering this issue?
    (ii) I also like to utilise the zipnamebean.createZipnamez(zipname_1) to properly create this entity.
    The local firewall has been de-activated. All components reside on the same host.
    I have tried various approaches and googled without success.
    Your guidances would be very much appreciated.
    Many thanks,
    Jack

    Hi All,
    When trying to add multiple Zipnames with the following additional statements at the beginning of ZipcodeApplicationClient:
                Zipcode zipcode_1 = new Zipcode();
                zipcode_1.setcode(9001);
                Zipname zipname_1 = new Zipname();
                zipname_1.setName("Harbour Cove");
                zipcode_1.getNames().add(zipname_1);
                Zipname zipname_2 = new Zipname();
                zipname_2.setName("Fairyland");
                zipcode_1.getNames().add(zipname_2);
                Zipname zipname_3 = new Zipname();
                zipname_3.setName("Wonderland");
                zipcode_1.getNames().add(zipname_3);
                zipname_1.setZipcode(zipcode_1);
                zipname_2.setZipcode(zipcode_1);
                zipname_3.setZipcode(zipcode_1);
                zipcodebean.createZipcode(zipcode_1); // line 49
    The whole persistence step (line 49) failed altogether with these output:
    Caught an unexpected exception!
    javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: null; nested exception is:
            javax.persistence.EntityExistsException:
    Exception Description: Cannot persist detached object [domain.Zipname@1a6eaa4].
    Class> domain.Zipname Primary Key> [0]
    at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:49)Any ideas on why this occur?
    Thanks,
    Jack

  • How do I setup a quadrature applicati

    on to reload a zero on the z pulse while counting up AND reload the stripe count of my encoder (i.e 720) while counting down. I understand how the reload mechanism works in one direction but what about bi-directional??? I am using Traditional NI-DAQ & VB6I am monitoring the position of a rotating shaft. The shaft has a quadrature encoder directly connected with 720 pulses per rev. I am using a 6602 board and would like to have a counter count up from 0 to 719 and reset to 0 (on the index pulse) in the positive direction (A leads B) and count down to 0 and reset to 719 in the negative direction (B leads A) direction. The Z index reload feature is specified as a unidirectional feature. What does one do in a bi-firectional sysytem?

    on to reload a zero on the z pulse while counting up AND reload the stripe count of my encoder (i.e 720) while counting down. I understand how the reload mechanism works in one direction but what about bi-directional??? I am using Traditional NI-DAQ & VB6I don't think that sort of behavior is supported in hardware for the 660x series. There's only one reload value which changes the count register without regard to the direction of approach. However, there may be a simple software solution. Let's look at what you have now:
    In the '+' direction, the counter resets to 0, then counts up from 1 to 719 before resetting again. In the '-' direction, the counter resets to 0, then counts down from -1 to -719 before resetting again. You'd like it to count down from 719 to 1 before resetting.
    Well, you could just conditally add 720 to the count whenever count < 0. Or you may prefer to use a remainder function on all the data without any conditional.
    Sound like it could work for you?
    My ow
    n wishlist for hardware-driven reset of the count register is:
    1. I'd like to do it in modes other than position measurement (especially edge counting mode).
    2. I'd like an option like Z index reload phase == 'A any, B any' (meaning, reset the count regardless of whether A & B are high or low)
    3. I'd like to select a RTSI signal or other counter output as the Z-index signal source rather than needing to hardwire it.
    -Kevin P.
    -Kevin P.

Maybe you are looking for

  • GR/IR account setup

    Does anyone know of any risks, if I setup multipal GI/IR accounts? In other words I will have Plant A with X, and Plant B with Y. Both using the same supplier, but managed in a different area. for this reason I want to ensure that the GR/IR is Split

  • Imac freezing and cannot force quit

    Imac keeps freezing upon startup and I cannot force quit anything. It just sits and wheel of death. Is this a hardware failure?

  • My Windows wont boot from the Recovery USB

    Hi, I created a recovery USB and when pressing f12 at start it does show me the USB as boot option. But when I select it nothing happens and it again shows me boot option. THe space consumed by recovery media is 10.1 GB and it wont let  me create it

  • JAXRPC  to handle Soap Attachment using JDeveloper

    I need to write a simple web services to handle request with image attachment. JAXRPC is good enough and I don't manipulate the attachment at a lower level. Is there a easy way to do this using JDeveloper, where shall I start with, a WSDL or a Java c

  • Auto converting to jpg files?

    So, I almost always shoot in RAW. I then unload all my pix from my cam into IPhoto. When I go to do anything with the pix, I notice that when I drag them out of IPhoto and into Photoshop (Elements 2 or 6), some of them have magically become JPG files