OneToMany 1 « Map « JPA Q&A

1. Why @OneToMany does not work with inheritance in Hibernate

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Problem {
    private Person person;

public class UglyProblem extends Problem {}

public class Person {

2. JPA @OneToMany Sets and unique contstaints

I have the following scenario: I have a system full of users. There is a desire to run contests for users who log into the site over a week or so. ...

3. jpa inheritance and a OneToMany Relation

I have written the following code:

public class Person {

    private Long id;

    protected String email;
    private String firstName;
    private ...

4. hibernate OneToMany List ordering persisting but reversing?

so I have a persistent entity that has a @OneToMany list of another entity and I need the list order to be able to be edited by the user, which works ...

5. JPA Entity Mapped as OneToOne as well as OneToMany

Consider the following JPA entity. My application instance class must always have a OneToOne reference to 4 special instances of Envelope but it also has a set of 0-infinite user ...

6. Hibernate Example OneToMany with compositeKey

Can you give me an example of a Hibernate mapping for the following situation:

  1. Parent table(foo) with a simple primary key (foo_id)
  2. child table(bar) with a composite key consisting of a> Foreign key ...

7. When to use inverse=false on NHibernate / Hibernate OneToMany relationships?

I have been trying to get to grips with Hibernate's inverse attribute, and it seems to be just one of those things that is conceptually difficult. The gist that I get ...

8. Hibernate @OneToMany with mappedBy (parent-child) relationship and cache problem

I have this problem for a long time now, I have searched the web and SO in and out and didn't find a solution yet. I hope you can help me ...

9. How to have a @OneToMany relationship with its own entity?

I have items that can contain further items, therefore I need a @OneToMany relationship with the same Entity. I have configured my field like this:

@ManyToOne(targetEntity=PersistentItem.class, fetch=FetchType.EAGER)
@JoinColumn(name="ID_CHILDREN", nullable=false)
HashSet<PersistentItem> children=new HashSet<PersistentItem>();
However, Java always ...

10. Hibernate @OneToMany - mapping to multiple join tables

Consider the following domain model:

- id
- List<Comment>

- id
- List<Comment>

In my design, I was attempting to create two join tables to manage the associations; issue_comments, and entry_comments. I assumed @OneToMany on ...

11. Hibernate @OneToMany without a separate join table

Consider the following database schema:

create table UserGroup ( id int not null auto_increment, name varchar(200), primary key(id));

create table User ( id int not null auto_increment, name varchar(200), groupId int not null, ...

12. Determining ManyToMany vs OneToMany using ClassMetadata

I am using ClassMetadata to determine the structure of a hibernate POJO. I need to determine if a collection is OneToMany or ManyToMany. Where is this information? Can I get ...

13. Java JPA OneToMany - "Many" relationship not refreshing

I'm running into a strange problem using the Toplink implementation of JPA. I'm writing a stand-alone application to manage loans. I define a LOAN class that has a OneToMany (bi-directional) relationship ...

14. How does Hibernate find the generic type of a collection in a @OneToMany mapping?

Given a simple entity relationship:

public class Single {

  public Set<Multiple> multiples;
How does Hibernate find out that the generic type of multiples is Multiple? This information is impossible to ...

15. @OneToMany association joining on the wrong field

I have 2 tables, devices which contains a list of devices and dev_tags, which contains a list of asset tags for these devices. The tables join on dev_serial_num, which is ...

16. making a jpa oneToMany relationship effective?

I have written a very basic and naive oneToMany relationship between a ChatComponent and its Chat Messages like this:

List<ChatMessage> chatMessages;
This basically works, i.e., doing something like:
ChatMessage chatMessage = vo.toDomainObject();
chatMessage.setDate(new Date());
//Add the ...

17. JPA and EJB - OneToMany problem

I try to build simple Java EE application that uses JPA + EJB3 and Stripes. It's a little address book. I'm using 2 JPA entities, Person and Email. Every person can have ...

18. JPA OneToMany not deleting child

i have a problem with a simple @OneToMany mapping between a parent and a child entity. All works well, only that child records are not deleted when i remove them from ...

19. @OneToMany without inverse relationship and without a join table?

This is a similar problem to "Hibernate @OneToMany without a separate join table", in that I need a @OneToMany relationship without a join table. However, I would also like ...

20. hibernate criteria OneToMany, ManyToOne and List

I have three entities ClassA, ClassB and ClassC.

ClassA {
 @Column(name = "a_id")
 private long id;
 private List<ClassB> bbb;

ClassB {
 private ClassC ccc;

21. Hibernate: Why @OneToMany with List fails?

I have a strange error with Hibernate3 here: Got a SoftwareDescription class, persisting it with the following field commented out works just fine:

@JoinColumn(name = "id")
private List<SoftwarePrice> prices = new ArrayList<SoftwarePrice>();
Got getters and ...

22. Hibernate performance issue with OneToMany / nullable relationship

We use @OneToMany for our Parent->Child->Child->Child DB relationship:

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "THE_ID", nullable = false )
private List<ChildClass> children = new ArrayList<ChildClass>();
We have a scenario with a lot of data (100K inserts) ...

23. JPA concatenating table names for parent/child @OneToMany

We are trying to use a basic @OneToMany relationship:

@Table(name = "PARENT_MESSAGE")
public class ParentMessage {

 @Column(name = "PARENT_ID")
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer parentId;

 private List childMessages;

 public List getChildMessages() ...

24. Hibernate mapping, on a unmapped class

I' ve got 2 tables... Challenge and ChallengeYear, ChallengeYear is only to create a list of years in challenge. I only want to make Challenge an entity, containing a list of List ...

25. The type of field isn't supported by declared persistence strategy "OneToMany"

We are new to JPA and trying to setup a very simple one to many relationship where a pojo called Message can have a list of integer group id's defined by ...

26. In a bidirectional JPA OneToMany/ManyToOne association, what is meant by "the inverse side of the association"?

In these examples on TopLink JPA Annotation Reference: Example 1-59 @OneToMany - Customer Class With Generics

public class Customer implements Serializable {
    @OneToMany(cascade=ALL, mappedBy="customer")

27. @OneToMany and composite primary keys?

I'm using Hibernate with annotations (in spring), and I have an object which has an ordered, many-to-one relationship which a child object which has a composite primary key, one component of ...

28. How to specify the cardinality of a @OneToMany in EclipseLink/JPA

I'm trying to impose a @Oneto7 association. I'd have imagined an attribute that specifies the target many value, but have found none. If there is no such attribute, how else, in ...

29. JPA @OneToMany and composite PK

Good Morning, I am working on project using JPA. I need to use a @OneToMany mapping on a class that has three primary keys. You can find the errors and the classes ...

30. why when I delete a parent on a one to many relationship on grails the beforeInsert event is called on the child?

I have a one to many relationship and when I try to delete a parent that haves more than one child the berforeInsert event gets called on the frst child. I ...

31. Java JPA @OneToMany needed to reciprocate @ManyToOne?

Create Table A (
ID varchar(8),
Primary Key(ID)

Create Table B (
ID varchar(8),
A_ID varchar(8),
Primary Key(ID),
Foreign Key(A_ID) References A(ID)
Given that I have created two tables using the SQL statements above, and I want to create ...

32. Lost with hibernate - OneToMany resulting in the one being pulled back many times

I have this DB design:

    user ...

33. CascadeType problem in One to Many Relation

I have two classes which have a Unidirectional One to Many relation with each other.

public class Offer{
    @JoinTable(name = "Offer_Fields",

34. JPA polymorphic oneToMany

I couldn't figure out how to cleanly do a tag cloud with JPA where each db entity can have many tags. E.g Post can have 0 or more Tags User can have 0 or ...

35. Update OneToMany list after entity save in Hibernate

i have relationship:

// In class
@OneToMany(mappedBy="a", fetch=FetchType.LAZY)
private List<B> bList;

// In class
private A a;
Now look this:
A a=new A();
// setting A

B b=new B();
// setting B
b.setA(a);; // this save b and a obviously
Now ...

36. JPA/Hibernate conditionally onetomany relationship?

I am using Hibernate Tools to generate the DAO and classes straight from database. There are two tables (table A and B) in the database, and there is a one to ...

37. Hibernate 3.5.x: NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval

I'm trying to upgrade to Hibernate 3.5.3-FINAL. When running my unit tests, I now receive the following exception:

java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z   
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(
My classpath contains the following JAR's: From the hibernate dist:

Other jars:
ejb3-persistence.jar ...

38. Fetch multiple onetoMany relationships Hibernate JPA

I am using Hibernate JPA 1.0. I have the following type of model and I consider manyToOne and oneToOne relationships "eagerly" fetched and oneToMany "lazily" fetched. I want to fetch Entity A and ...

39. JPA OneToMany problems after update

I have 2 Classes, Parent and Child, with a @OneToMany relationship. Every parent has 0 or more children.

@OneToMany(fetch=FetchType.LAZY, cascade={CascadeType.REMOVE})
The Parent class has also other fields like the name. I'm in a ...

40. Hibernate : OneToMany mapping not based on PK?

I have 2 entities/tables. One is a proper entity, let's call it data. It has a number of fields containing so-called "multilingual codes". The second table, code, contains the multilingual values themselves. ...

41. @OneToMany does not insert foriegn key in Hibernate+JPA

I am facing some strange issue, I have a user table(use class) and a country table(country class). An user may have N number of countries. Hence, I have added a List ...

42. JPA (hibernate) onetomany relation

I am not sure what I am missing to make a bidirectional onetomany relationship (hibernate engine). A scaled down version of the domain model:

class Person {
@OneToMany(mappedBy="personFrom", cascade = CascadeType.PERSIST)

43. Java JPA, Swing and Beans Binding: Changes to a OneToMany collection in entity not immediately reflected in GUI

I am trying to learn JPA with Hibernate and binding it to a GUI built in Netbeans with Beans Binding. It is a application listing dogs. Each dog can have one ...

44. Duplicate entry using unidirectional mapping using JoinTable

I created a JPA unidirectional join table following the JPA documentation very closely ( I could insert an applicant, A, with joblist (JobOne, JobTwo) without any problems. However, when I tried to ...

45. Hibernate, Persistence and @OneToMany and @ManyToOne annotations problems

I have some problem with @OneToMany and @ManyToOne annotations. I have two class Suite and SuiteVersion. A SuiteVersion is dependent of a suite. So i have implemented this in my code: Class Suite ...

46. Lost with JPA @OneToMany and composite PK

I'm pretty lost with mapping the following structure with JPA annotations.

+===========+             +====================+
| Offer     |  ...

47. Grails AddTo in for loop

I am facing a problem due to that i'm newbie to grails i'm doing a website for reading stories and my goal now is to do save the content of the ...

48. What is the best optimized way to select many entities with subentities in JPA?

Let's say we have:

@Entity public class Order {
  @Id private int id;
  @OneToMany(mappedBy="order") private List<Item> items;
@Entity public class Item {
  @Id private int id;

49. JPA: Merge @OneToMany Duplicate entry error

I'm alwways getting the following error:

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2-1' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ENTITY_ENTITY (relationships_ID, Entity_ID) VALUES (?, ?)
    bind => [1, 2]
Query: ...

50. OneToMany Annotated Collection Not Persisting via Hibernate

I currently am trying to persist a collection using @OneToMany(cascade=CascadeType.ALL) for a simple list of objects. The table for Parent_Child gets created in MySQL but the keys for each object are ...

51. JPA+Hibernate(J2SE) @OneToMany - Millions of records slows adding a new object down

I'm using JPA+Hibernate with a PostGre SQL database in a J2SE project.
I have 2 entities A and B. A has a @OneToMany relationship to B.
In my domain model ...

52. How would you declare the OneToMany member variable

Which of the following declaration would be the right one to choose for allocating the right amount of memory. Option 1 has an initial collection capacity of 0 and Option 2 ...

53. Persisting OneToMany relationship only persists first object in set?

Been messing around with Hibernate and PostgreSQL trying to get it to work as expected. But for some reason when I try to persist an object with a @OneToMany relationship with more ...

54. JPA: question on impedance mismatch in OneToMany relations

I have a question about JPA-2.0 (provider is Hibernate) relationships and their corresponding management in Java. Let's assume i have a Department and an Employee entity:

public class Department {

55. Hibernate onetomany mapping

I try to map a relation for the first time. I have found a lot of ways to go. There are two classes: - Project (Parent) - Application (Child) So one project can ...

56. Hibernate retrieving list from onetomany

I managed (as you can see in older posts from me) to insert a onetomany relation through hibernate. My two entity classes look like following:

public class Project {

 @GeneratedValue(strategy = ...

57. Hibernate: How do I write the HQL for getting records of an entity without records for its identifying relation

I have Hibernate Objects defined as

Class SomeText{
  private Long textId;
  private Set<Tag> Tags = new HashSet<Tag>();

  @ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE })
  @JoinTable(name = "text_tag_reln",
   joinColumns = { ...

58. Hibernate One to many

As per hibernate documentation:

To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many ...

59. Hibernate: joining with one of the keys of a multi-keyed table

I've got a table Category and a table TranslatableText. The category is like this

create table Category (
  id int not null,
  parent_id int default 0,
  TranslatableDescriptionId int default ...

60. jpa removing child from collection

I'm using JPA over Hibernate in my web-app. Here are two entities (only getters are shown):

class Child {

  private Parent parent;

  @JoinColumn(name="parent_id", referencedColumnName="parent_id", nullable=false, updatable=false)
  public ...

61. Hibernate: Update onetomany list

I have got a onetomany relation in Hibernate:

public class Project
    @OneToMany(cascade = CascadeType.ALL)
    @OrderColumn(name = "project_index")
    List<Application> applications;

public class Application
Now, I ...

62. Hibernate - OneToMany - Several Columns

I have those 2 tables Teacher and Contact, a teacher can have x Contacts SO here we are looking at a @OneToMany association. Tables Structure: User [userid, username, email,...] Contact [contactid, contactname, ref, reftype,...] I want ...

63. Hibernate ConstraintViolationException when cascading delete on @OneToMany

This may seem like a very simple question, but I have been struggling with it for a while. I have two entities Client and User where Client is a parent of ...

64. JPQL to query entity connected to another by @OneToMany


class Container {

    protected long id;

    @JoinColumn(name="container_id", nullable=false)
    protected Collection<Content> ...

65. How to persist a @OneToMany update with hibernate?

in my application I've got users which have files. The UserVO has the following mapping:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "users")
public Set<Files> getFiles()
    return this.files;
Then I ...

66. How can I do paging with @OneToMany collections

Suppose I have a Post entity and a Comment entity and a one to many relationship:

@Entity class Post {
    List<Comment> ...

67. one shot delete with hibernate on onetomany association

On a onetomany associations I am attempting to delete all the many associations and see that multiple delete statements are being executed.

// The entities
class Users{
    public void setPhones(Set<Phone> ...

68. Constraint violation in Hibernate unidirectional OneToMany mapping with JoinTable and OrderColumn when removing elements

I have a problem when removing elements from a list mapped as described above. Here is the mapping:

@Table( name = "foo")
class Foo {

    private List bars;


69. JPA: Entity X has a OneToMany relationship to itself. How?

I have one Entity call Comment Comment
+ id (PK)
+ fromUserId
+ targetId
+ replyId : This is the foreign key to id The idea is a comment can have many replies, but a ...

70. Deletion order for contained @OneToMany members

@Entity public class Organization {

List<A> Aobjects;

List<B> Bobjects;

List<C> Cobjects;

I have @OnDelete annotation on all the @OneToMany members. What would be the order of deletion of these objects when the ...

71. Hibernate mapping association OneToMany with constraint restriction

I have the following code:

class A{
  private Long id;
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "a", cascade = CascadeType.ALL)
  private List<B> bs =new ArrayList<B>();

class B{


72. Issue With @OneToMany and Abstraction in JPA

I have an issue with one-to-many relationship. I have an abstract class This is not mapped to a table. There are other concrete classes extending from this, and they are ...

73. Remove duplication in OneToMany/ManyToOne bidirectional relationship using a JoinTable (with an OrderColumn)

I have a OneToMany/ManyToOne bidirectional relationship using a join table. The children are in a List and are ordered. Here's the setup: Parent:


74. hibernate: list of child ids retrieval for parent

Technology: Hibernate 3.0 Suppose i have Entity class Company

    public class Company

75. one to many mapping to a property of superclass

I have a superclass "Questions" and its subclass "MultipleChoiceQuestions" superclass ha a field "activity" I want to create a Set and use OneToMany annotation using "mappedBy = "activity" eg..... @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, ...

76. JPA OneToMany, ManyToOne bidirectional

I'm trying to get rid of the following error:

The attribute [lcritical] in entity class [class] has a mappedBy value of [pl704_error] which does not ...

77. JPA @OneToMany join on part of a multipart key

A Profile table has a one to many association with a Privilege table. The privilege table has a multipart key, of a profile_id and a privilege_id. I want to join from ...

78. java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z

I am getting this error:

java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z
These are the jars in my classpath:

79. OpenJPA: "cant-set-value" exception persisting entity with onetomany field

So I have two tables:

and a join table CRAWL_SEED mapping the two with fields:
ID  int
A client crawl can ...

80. javax.persistence one to many - how does it work?

Say that I have 2 Entites of User and Message. User has a field called "messages" that has a list of messages and is annotated with "@manyToOne" and Message has a ...

81. How to maintain a Map in JPA2?

I have three entity classes (A, B, C). A should contain a map which maps instances of B to instances of C. All instances of C are owned by a map ...

82. Hibernate criteria with projection not performing query for @OneToMany mapping

I have a domain object, Expense, that has a field called initialFields. It's annotated as so:

@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JoinTable(blah blah)
private final List<Field> initialFields;
Now I'm trying ...

83. When is @OneToMany list populated in Play framework?

The Play framework's Yet Another Blog Engine example has a Post class with children Comments:

// ... other fields, etc.
@OneToMany(mappedBy="post", cascade=CascadeType.ALL)
public List<Comment> comments;
// ...

When data is populated by the ...

84. How to map @OneToMany to a java.util.Map with custom keys?

class A{

  private List<B> bs;


class B{

  private Long id;
  private String name;

And I'd like to have this:
class A{

  // the map should ...

85. Envers @OneToMany audit on CREATE(0) but not on DELETE(2)

I've looked a quite a few similar issues like: but haven't found a solution yet. An Activity has many Occurences, when an occurence is created the activity_occurence_AUD table is ...

86. @MappedSuperclass and @OneToMany

UML Diagram I need association OneToMany from Country to superclass Place (@MappedSuperclass). It could be bidirectional. I wolud need something like @OneToAny...

public class Place {

private String name;
private Country country;

public String ...

87. Hibernate OneToMany and ManyToOne confusion! Null List!

I have two tables... For example - Company and Employee (let's keep this real simple)

Company( id, name );
Employee( id,  company_id );
Employee.company_id is a foreign key. My entity model looks like this... Employee
@ManyToOne(cascade = ...

88. JPA query, oneToMany or manyToOne, should both work?

I am porting some code from an old OpenJPA implementation to a more recent one, specifically to

OpenJPA 2.1.0-SNAPSHOTversion id: openjpa-2.1.0-SNAPSHOT-r422266:990238
My previously working query failed in this new environment ...

89. inverse=true in JPA annotations

In my application I use JPA 2.0 with hibernate as the persistence provider. I have a OneToMany relationship between two entities (using a @JoinColumn and not @JoinTable). I wanted to know ...

90. EclipseLink/JPA @OneToMany Backpointer Cardinality Error

I am trying to generate a unidirectional one-to-many mapping between two JPA entities. In my ChatRoom class, I have a Vector<User> type object that represents Users in a ChatRoom. I am ...

91. OneToMany Update not working in child class

I have OnetoMany relationship between Person and Role class. A Person can have multiple roles. When I create a new person, roles (existing records) should get updated with the person ids. ...

92. Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

I'm finding my feet with Hibernate Annotations and I've hit a problem I hope some one can help with. I have 2 entities, Section and ScopeTopic. Section has a List class member, ...

93. HIbernate - "A Foreign Key referring from has the wrong number of column. Should be 2" error

I've been searching for the solution to this question for a while now. I have found a few threads talking about many-to-many relationships causing this issue, but I don't think that ...

94. Bidirectional OneToMany/ManyToOne mapping in OpenJPA JPQL problem

I have two classes with a bidrectional relationship:

public class Room {
    @Column(name="ROOM_ID_PK", updatable=false, nullable=false)
    private int id;

95. JPA replace 1:M set for an entity

I have the following entities:

public class Alert implements Serializable {
    private long alertId;
    private Set<AlertTime> alertTimes = new HashSet<AlertTime>(0);

    @OneToMany(cascade = CascadeType.ALL)

96. Hibernate ManyToOne and OneToMany i one Entity

I have 3 tables University(id,name), Group(id,name,university_id), Student(id,name,number,group_id). One university have many groups and one group have many students. My POJOs look like this:

@Entity(name = "Student")
public class Student {
    @SequenceGenerator(name = ...

97. JPA 2.0 Hibernate @OneToMany + @MapKeyJoinColumn

OneToMany + MapKeyJoinColumn doesn't work for me, please suggest what I'm doing wrong. I'm using JPA 2.0 + Hibernate 3.6.1 And want to map following tables:

Question to Statement to Language relationship
To ...

98. Does JPA support a @OneToMany mapping between entities without a foreign key constraint in the database?

This is for a legacy database. The two database tables in this relationship don't have a foreign key constraint even though the child table column holds the PK of the ...

99. JPA OneToMany, always empty

i have a bidirectional, one to many, and many to one relationship. say, a Company has many Persons, and a Persons has one company, so, in company,

@OneToMany(mappedBy = "company", fetch = ...

100. Create ORMapping using OneToMany relations for 3 tables

I have 3 tables: Project, User and Role. Now I would like to have a table Project2User2Role with the embedded key id_project, id_user,. I tried it using @OneToMany relations in all three ...