OneToMany 2 « Map « JPA Q&A

1. JPA How add unique contraint on column for @OneToMany relation like on username

I have a nice problem. I'll resume the context. I have a Class : Site that represent a website, and a Class User. A Site can have multiple Users.

class Site {


2. TABLE_PER_CLASS Bidirectional @OneToMany Problem

Hibernate can do bidirectional polymorphism with TABLE_PER_CLASS (<union-subclass>), says so here:

This strategy supports one-to-many associations provided that they are bidirectional.
I'm trying to get a simple example to ...

3. Unable to persist new object graph using JPA (hibernate) with simple oneToMany - ManyToOne relationship

I am attempting to persist/merge a brand new object graph through jpa but it seems like the order of persistance is incorrect as it tries to save sub objects who have ...

4. JPA how to remove parent without delete children?

I'm trying to remove a parent, but I keep getting a Foreign Key violation. If I put Cascade.ALL in the parent, it delete the children too. And it's now what ...

5. How to use Hibernate Criteria for joining two tables with OneToMany relation

I have two tables for which I can't implement mapping @OneToMany in their entities unless I have a circle dependency. I want to create a Hibernate Criteria so that I'd be ...

6. OneToMany, ManyToOne why value of parent in children is null?

I read similar questions, but still have problem. Configuration info: Hibernate 3.5.1 Parent class Question:

public class Question implements Serializable {

    private static final long serialVersionUID = 1L;


7. @OneToMany pulling all related fields except foreign key

I have a Demographics entity that contains a Collection of MedicalRecordsReceived entities: //Demographics entity @OneToMany(cascade = CascadeType.ALL, mappedBy = "demographics", fetch=FetchType.EAGER) private Collection medicalRecordsReceivedCollection; and //MedicalRecordsReceived entity @JoinColumn(name = "demographics_id", referencedColumnName = "iddemographics") @ManyToOne(optional = false, fetch=FetchType.EAGER) private Demographics ...

8. JPA: uni-directional OneToMany question

I have the following classes:

class A{
   private B b;

class C{
  private A a;    

class B{
  private A ...

9. OpenJPA treats field with oneToMany Mapping as a Blob

I'm having a serious issue with JPA's implementation of OneToMany relationships and I'm looking for a reasonable workaround. The issue is that JPA appears to get confused reading it's @OneToMany ...

10. Hibernate : Use of @OneToMany or @ManyToMany targeting an unmapped class

i can't find where is my error, where i'm not mapping my class, but to me everything shoud be fine.. but isn't. Can someone help me to find it ?

org.hibernate.AnnotationException: Use of ...

12. How do you order a oneToMany join table in hibernate criteria

Say I have a class Mother with a oneToMany mapping to Kittens

@org.hibernate.annotations.Entity(dynamicUpdate = true)
@Table(name = "Mother")


@OneToMany(fetch = FetchType.LAZY, targetEntity=Kittens.class, cascade=CascadeType.ALL)
private List<Kittens> kittens;
I am using the criteria Api to provide a list
Criteria ...

13. When using setFetchMode in Hiberate criteria how do I set a restriction on the oneToMany table

I'm struggling to create a Hibernate criteria query that uses setFetchMode(... SELECT) and places a restriction on the returned child records. If I use a creteAlias as recommended it produces an ...

14. Set null value on delete with @OneToMany

I have two classes, Person and Position. Person can be assigned to many Positions, and one Position can have only one Person (or no Person assigned). Everything works fine, but deletions of ...

15. JPA2.0: Delete Entity in OneToMany RelationShip

How do I delete an entity in a OneToMany relationship.

     query="select c from User c where c.userName = :userName AND c.password = :password")
public ...

16. @OnetoMany class call

i need some help for my class...

import javax.persistence.*;
import java.util.List;

 * Created by IntelliJ IDEA.
 * User: Shahriar Newaz
 * Date: 07/03/11
 * Time: 10.07
@Inheritance(strategy =InheritanceType.JOINED)
public class OrbitObject {

17. Java - A JPQL Query to delete a oneToMany relationship

If I have this 3 entities :

@Entity public class Student {
protected Long id;

private String name; 
} @Entity @Inheritance(strategy=InheritanceType.JOINED) ...

18. Insert fails for @OneToMany Hibernate mapping with inheritance

I'm using Java and Hibernate 3.6.4.Final.
TABLE_B is a mapping table for a specific type of A entities (B) which have a OneToMany relationship with X entities.
I'm having problems inserting a B ...

19. JPA (hibernate) OneToMany relationship and null

I have a relation OneToMany between a class Resident and ResidentInfo ResidentInfo is not supposed to exists without Resident, but ResidentInfo is not required Here are my classes:

public class Resident {

20. JPA (hibernate) Mapping OneToMany incorrect?

Hi I'm new to JPA and I think I have an issue with my mapping annotations I'm using hibernate 3.6.1 final with JPA 2 Here are my class :

    public class ...

21. annotation mapping bidirectional OneToMany/ManyToOne not fetching?

I'm clearly struggling to understand this so help greatly appreciated... I have the following mapping:

@Table(name = "parent")
public class ParentEntity
    @Column(name = "parent_id")

22. Save a model with a relation OneToMany

Hi I have models like this :

public class Person extends Model {
    @OneToMany(orphanRemoval = true, mappedBy = "person")
    @Cascade({ CascadeType.ALL })
    public List<Contact> ...

23. JPA : best practices with unidirectional OneToMany

I have several little questions about best practices with JPA (via hibernate). My first question is about the complexity of one domain model. I've got a model Account which represents an... account ;) An ...

24. JPA: Table Relationship Issue

I've two tables: reservation and machine. So, I have two classes: Reservation

@Table(name = "reservation")
        name = "getActiveReservationByStatus",
        query ...

25. Hibernate Mapping Conflicts

I am having a parent table and child table in Oracle Schema. Also created a Hibernate Classes for this tables. for e.g. parent table Called A which has primary key p_key ...

26. Unneeded column added trying to set up OneToMany relationship

I'm trying to set up a OneToMany relationship between an author and his posts with author as the foreign key and username as primary key, using JEE 6 and toplink+eclipselink as ...

27. hibernate OneToMany criteria returns duplicates

I have an association mapped by the following:

public class Parent
    @Column(name = "parent_id")
    private Long id;

    @OneToMany(mappedBy = ...

28. OpenJPA: Update statements not generated for a @OneToMany mapping (with persistent entity)

OpenJPA 1.2.2 Spring 3 HSQLDB 2.0 JUnit Testing with SpringJUnit4ClassRunner & Spring @Transactional on Testclass --

class Settlement {

    @OneToMany(mappedBy = "settlement", Cascade=CascadeType.REFRESH)
    private List<VoucherProcessed> vouchersProcessed = new  ...

29. Have to persist both sides of @OneToMany self-join

I have a bi-directional @OneToMany self-join on a JPA 2.0 entity and I find that I have to persist both sides of the relationship for the changes to be reflected in ...

30. left outer join in microsoft sql server

Please explain the behaviour. I am following struts2 and hibernate5.0 and i am not using any annotations. I have two tables table A and table B Table A has columns id , model, ...

31. Eclipselink, possible to do @OneToMany relationship to class on an @EmbeddedId property as foreing key?

I want to do a Jaas login module using JPA to store my AuthUser and AuthUserRole. I'll focus on the JPA side on this question. Here is what I would do in ...

32. workaround/get rid of multiple writable mappings in OneToMany and ManyToOne relationship?

i've been trying to solve a problem but got stuck now.
I have 2 entity classes/tables Order and OrderItem. OrderItem has 1 Order and Order has 1..* OrderItems. My EJB works fine, it ...

33. @OneToMany List<> vs Set<> difference

Is there any difference if I use

public Set<Rating> ratings;
or if I use
public List<Rating> ratings;
both work OK, i know difference between list and a set, however I don't know if this makes ...

34. Constract JPA query for a OneToMany relation

I've those 2 entities

Class A {
    private List<B> bs;

Class B {

    private A a;


35. Hibernate OneToMany Relation Error

I'm newbie on Hibernate. I failed when I try to make one to many relationship between two classes. It gave an error:

Exception in thread "main" java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z
    at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(

36. Hibernate updates @Version property of entity when adding items to @OneToMany collection - is this normal?

I have two Foo and Bar entities which have a 1:n relationship:

public class Foo {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = ...

37. (Open-)JPA 1.0: OneToMany-related list is null, when fetching in lazy mode

I have a problem with JPA 1.0 (OpenJPA) Following situation

public class A{
    private Long aId;
    private List<B> bEntities;
    //myId getter and ...

38. Hibernate OneToMany without a foreign key

Is there any way to tell JPA to not create a Foreign Key on a OneToMany relationship when creating tables? Here is some sample code of what I'm trying to do: I ...

39. Update an entity (OneToMany relationship)

i got 2 entities, Student and Phone, and a relationship one-to-many between them.

@Table(name = "STUDENT") 
public class Student { 

    private long studentId; 

40. How to perform the OneToMany Hibernate mapping when reverse reference is just an id attribute, not full reference

Let me be more specific, it was hard to describe this in the title. I have a class called Bucket, which has a map to a series of Labels. The Bucket class ...

41. JPA: @SqlResultSetMapping OneToMany problem

I am trying to do some NatveQueries, but I am stuck with @SqlResultSetMapping configuration. I have those classes:

public class LocalUser implements Serializable {  
private static final long ...

42. How to add children by specifying only children's id in an OneToMany relationship?

For example, I have Person and Pet.

Person {
    private Integer id;
    private List<Pet> pets;

Pet {
    private Integer id;

43. overriding lazy fetch in OneToMany association

I've been facing the LazyInitializationException and had three solutions by googling it:

  1. add myList.size() in getMyList()
  2. override the lazy fetch (join fetch)
  3. eager fetch
i'm avoiding the eager fetching and was wondering what's the difference ...

44. JPA @OneToMany Mapping Problem

I am trying to do do JPA/Hibernate mappings to map two tables, but am getting this error. any help would be greatly appreciated!!

public class Restaurants{


45. @OrderColumn, @OneToMany & null index column for collection

I am trying to create parent child tables where the order is preserved. The example 7.8 from Hibernate documentation shows how to do this:

public class Customer {
   @Id ...

46. How to access a OnetoMany join table in JPQL?

I want to write a lttl complicated query in JPQL where i access a OneToMany Join table. I get QuerySyntaxException: Pan_PanRes is not mapped. QUERY - ...

47. Hibernate @OneToMany(mappedBy="...") relation not being cached

I have a following class called Article (simplified):

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Article {
    // .....
    @OneToMany(mappedBy = "author.article")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

48. annotation to filter results of a @OneToMany association

I have parent/child relationship between two tables, and the corresponding mapping in my Java classes. The tables roughly look like that:

A (ref number, stuff varchar2(4000))
B (a_ref number, other number, foo varchar2(200))
and ...

49. Version of all children is incremented in OneToMany when merging parent entity

I have a OneToMany relationship defined like this:

Parent extends BaseEntity {
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
    private List<Child> ...

50. org.hibernate.AnnotationException: Collection has neither generic type or OneToMany.targetEntity()

I used Hibernate Tools to generate my Hibernate POJO mapping. Unfortunately the code generated by Hibernate tools seems not to work, I get the exception org.hibernate.AnnotationException: Collection has neither generic type or ...

51. JPA - OneToMany, ManyToOne, OneToOne problem

Given the following two entities :

class Parent {
       private Set<Child> children;


class ...

52. Hibernate OneToMany generated foreign key

I have the following table structure:

child(childId, parentId fk)
Then, I have the following objects:
@Table(name = "parent")
public class Parent {
   private String id;


53. JPA EclipseLink @OneToMany returns empty set

I am using an embedded id:

public class EntityId {
    private long id;
And I have the following tables:
public class Master {
    @EmbeddedId private EntityId id;


54. How to select the size of a @OneToMany(mappedBy))collection using HQL

First some context and explanation: I have written the following HQL query:

select size(childGroups), size(ipts),,, g.status from LogicalGroup g where g.isRoot=true group by,, g.status
LogicalGroup is an entity with scalar ...

55. Hibernate -- Using @SecondaryTable, @OneToMany

(Simplified Example below) I'm trying to map one POJO class with 2 DB tables and also creating a OneToMany association. Here is how the class looks like..

@Table(name = "external_data")
@SecondaryTable(name = "external_data_hierarchy")
public class ...

56. OneToMany HIbernate Projections problem

I'm trying to create a Hibernate projection for database stored File and its versions like this:

DetachedCriteria criteria = DetachedCriteria.forClass(File.class, "file");
    criteria.createAlias("versions","versions", CriteriaSpecification.LEFT_JOIN);
    criteria.createAlias("publishedVersion","publishedVersion", CriteriaSpecification.LEFT_JOIN);

57. JPA OneToMany multiple column join enum

I am using JPA for my project. I am stuck with getting to retrieve entities in a OneToMany relation. Here is the scenario. My Entities are EntityX -Id -name -etc EntityY -Id -name -etc EntityZ -Id -name -etc EntityD -Id -EntityRefType (Enum of X/Y/Z) -EntityRefId (Can be Or ...

58. JPA/Hibernate, @OneToMany and constraints (Oracle)

I have the following scenario:

class A {

  private long dbId;

  @OneToMany ( cascade = CascadeType.ALL )
  @JoinColumn( name = "A_ID", referencedColumnName = "DBID" )

59. JPA OneToMany Cacade.ALL creating two entries for the parent

We are using JPA-Hibernate in our project We have a entity, say a A which has a list of entity Bs. Within A, there is a OneToMany on list of Bs Within B, there ...

60. OneToMany Mapping with with Joined Inheritence Annotations:

I have the following domain classes:

public abstract class AbstractAddressbookField {
   private int dbID;
   private Addressbook addressbook;

   public AbstractAddressbookField() {


61. Play JPA Hibernate special self-referencing bidirectional ManyToOne/OneToMany relationship join question

I'm new to the Play Framework, Java and Hibernate JPA so appreciate any help (come over from PHP). My goal is to have a tree of categories. It's essentially an infinite parent/child ...

62. How to merge a @OneToMany relationship effectively?

For example I have the following two entity classes with a one-to-many relationship:

public class A implements Serializable {
    @OneToMany(mappedBy = "a", cascade = CascadeType.ALL)

63. Hibernate: mapping @OneToMany / @ManyToOne problems (not using entity primary keys)

I am new to Hibernate / Spring, trying to map legacy database while creating a little web utility, which should ease some work for the colleagues. As I had mapped the ...

64. Getting list of null values when retrieveing list of child entities in hibernate using bidirectional @OneToMany

I have problem when accessing list of child entities in my @OneToMany association in hibernate. I am able to load the parent object using successfully

from Exam query
But when i try to access ...

65. Hibernate: map last row of a @OneToMany relation

I have a relation between element and its names. All historical names as well as the current one are located in table "element_name" that has field "created". The row last created ...

66. JPA composite key @OneToMany

Aloha! I already have the following db schema, which I'd like to recreate with Java and plain JPA annotations (using hibernate as provider, so hibernate specific annotations would work as a last ...

67. JPA (hibernate) relation OneToMany with date

I need to create hibernate relation one to many between Department and Person (one Department has many persons). The problem is that I want to maintain time validity. Without ORM (hibernate) it ...

68. Hibernate relation OneToMany with non unique key

I am not able to describe my problem, I try it again with example: I have two entities (tables): Department and Person. Both tables have a field CODE which is not unique. ...

69. JPA: @JoinTable - Both columns are Primary Keys.. How do I stop that?

This is my annotation I use to generate my Join Table.

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "service_operations", 
        joinColumns = { @JoinColumn(name = "serviceId") ...

70. Hibernate mapping: OneToMany and OneToOne on child object property

Here is parent class Enterprise. It has employers and one of them is president of enterprise.

class Enterprise
   // fields

   public List<Employee> getEmployers()

71. Override @OneToMany targetEntity in subclass?

Consider the following example:

public interface Bar {

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public DefaultBar implements Bar {

  @GeneratedValue(strategy = GenerationType.TABLE)
  private long id;


public class Foo {

  @GeneratedValue(strategy = ...

72. JPA/Hibernate OneToMany & ManyToOne annotations

I'm writing code that looks like Google Latitude (locate a user). I'm under tomcat 6.0.33, using jpa/hibernate, and easybeans 1.1 They work independently, but when I try to link them it fails:

Caused ...

73. orderBy and OneToMany-Relation -- criteria query with jpa 2.0

I have the following structure...

Entity A
  - ...
  - Collection<B> c (@OneToMany)

Entity B
  - ...
  - Date d
I want the queryResult to be ordered by the Date ...

74. JPA OneToMany with inherited entities using DiscriminatorOptions and orphanremoval

I've a problem, that I can't solve for days now. I have read many docs, searched many forums, but found no solution. I've inherited class as the code shows below:

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name ...

75. Mapping a unidirectional OneToMany association on a wrapper object using JPA

I am converting Hibernate configuration over to using JPA. The current configuration has an AlertPref class (ALERT_PREF table) with a collection of Long types that are primary key values from ...

76. one-to-many bidirection performance issue

i have one doubt, that is when we create one-to-many as bidirectional. we will put one parent class reference in child class. see the code.

public class Person {

77. one-to-many detached Criteria parent table fetch based on child table

i have one problem in one-to-many mapping using hibernate. i have 2 classes, Person and Address. Person is mapped by Address ( one-to-many) i want get all Person where Address = "xxxx";. how ...

78. Hibernate and H2 "Referential integrity constraint violation" for OneToMany bidirectional mapping

So I have two simple beans -- FatKid and Hamburgers. Now, for reasons unbeknownst to me I need to be able to not only look up all of the hamburgers ...

79. OneToMany and complex PK

I have problem with one-to-many mapping.
Two tables questions(PK(id), text) and answers(PK(id, questionId), text)
In my app I use this tables in read-only mode.
I want define relations between this tables

@Table(name = "QUESTIONS")
public class ...

80. TWO - records are getting saved In OneToMany Bidirectional Relation in Update Operation?

I am new to JPA, using JPA 2.0. I am facing on problem with OneToMany Bidirectional Relation. When i am updating these, TWO - records are getting saved. My Entities are: 1) Claimant: having ...

81. is it possible to map a Map in hibernate with @OneToMany relation?

i have a table Permission:

  • permission_id
  • permission_name
  • permission_desc
and a table PermissionCategory with one to many relation to Permission is it possible to return map in one to many relationship instead of list. this is what i ...

82. @OneToMany mapping list size limit

Is there any way to limit the list's size of the @OneToMany relationship in JPA? Here's my code sample:

@OneToMany(mappedBy = "publication", cascade=CascadeType.PERSIST)
private List<Comment> commentList;
I'm using EclipseLink 2.3 JPA implementation. Thanks in advance. ...

83. Hibernate inserts duplicates into a @OneToMany collection

I have a question concerning Hibernate 3.6.7 and JPA 2.0. Consider following entities (some getters and setters are omitted for brevity):

public class Parent {

84. Jpa OneToMany not persist child

I've trouble on persistence of OneToMany field. These are two simplified classes I'm using to make test.

public class User implements Serializable {
private String name;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<PhoneNumber> phoneNumbers;

public class ...

85. Bidirectional OneToMany assocation between sub and superclass not working (JPA with Hibernate 3.6.7)

I have two classes, Employee and Manager. Manager extends Employee, as it is a type of employee. Employee has an instance of Manager, which represents the idea of an ...

86. remove an entity in OneToMany relationship

I have trouble understanding what minimal effort is needed on my part in removing an Entity from a OneToMany relationship. I find a lot of examples just adding Entities to these ...

87. Order a Hibernate Criteria result by an Agreggation of a Property of OneToMany relationship

I have the following classes mapped:

class Student {
    @OneToMany(mappedBy = "student")
    private List<Grades> grades;

class Grade {

88. JPA ManyToOne/OneToMany annotation return NullPointer during select operation

I'm try to use JPA to map two tables with N:N relation, the binding table has 3 columns (the 2 foreigns keys + a custom column), so I must to use ...

89. Hibernate OneToMany. Getting empty list when loadin from DB

I'm new to Hibernate so my question can be silly a bit, by i'm stucked and will be glad to get help. I have two entities: Book and Tag with following ...

90. JPA Union on two @OneToMany Collections on the parent object

  • Account has many Payments (paymentType, date)
  • Account has many Letters (letterType, date)
  • You have 10,000 accounts, each having at least 5 payments and letters.
What's the query to return all Accounts whose paymentType ...

91. Hibernate OneToMany using annotations with legacy database

I'm working with a legacy database that isn't normalized at all. They've been coding relationships directly in the program (written in Uniface). Now, they are migrating to Java. Sadly, I can't ...

92. Efficiently determining the IDs of entities referenced via OneToMany relationship

Let's say I have a Hibernate entity that declares a OneToMany relationship to a different entity:

public class SomeEntity {
  @OneToMany(fetch = FetchType.LAZY)
  private List<OtherEntity> otherEntities = new LinkedList<OtherEntity>();


93. "Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements" in hibernate when annotating a ConcurrentHashMap

I've tried annotating a property accessor whose return value is a map as follows:

public ConcurrentHashMap<String, Serializable> getParameterValues()
This is in accordance with the hibernate user guide (section However, I get:
org.hibernate.AnnotationException: Illegal ...

94. Difference between using @OneToMany and @ManyToMany

I am having some trouble understanding the difference between @OneToMany and @ManyToMany. When I use @OneToMany it defaults to create a JoinTable and if you add the mappedBy attribute you will ...

95. Hibernate oneToMany Abstract Class override ID

I'm using JPA 1.0 so I am limited in what I can do but I still think it should be possible to do the following however I cant get it working...

Table ...

96. JPA OneToMany relation not automatically populated?

I have a simple OneToMany relation between Task and TaskError. Task maps the TaskErrors:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "task", orphanRemoval = true)
private List<TaskError> taskErrorCollection;
The TaskErrors should be deleted when the Task is ...

97. JPA persist with OneToMany ManyToOne

I am trying to persist entities with @OneToMany and @ManyToOne relationships.

@OneToMany(mappedBy="customer", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
private Collection<Address> addresses = new LinkedHashSet<Address>();

@JoinColumn(name="customer_id", referencedColumnName="customer_id")
private Customer customer;
problem is that it inserts NULL instead of customer_id in the ...

98. update @OneToMany in Play framework

I have a simple form that intend to update a list of items in a cart. The form works pretty well, I display an input text for each item in the cart. But ...

99. Hibernate - HQL to fetch a collection from Unidirectional OneToMany relationship

I have an Class with a unidirectional one to many relationship as follows:

public class Order {
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name="order_item", joinColumns={@JoinColumn(name="order_id")}, inverseJoinColumns={@JoinColumn(name="item_id")})

100. OneToMany relationship is not working

My Tables: Product: id, name Offer: id, value, product_id Entities:

public class Product implements Serializable {
    private Set<Offer> offers;

public class Offer implements Serializable {