relation 1 « Map « JPA Q&A

1. How to work around a potential performance issue when using a Grails hasMany relation?

Given the following domain classes:

class Post {
    SortedSet tags
    static hasMany = [tags:Tag]

class Tag {
    static belongsTo = Post

2. Hibernate: Mapping User-Friends relation in Social Networks

It's quite some time that I'm trying to figure out this problem and from googling around many people have similar problems. I'm trying to model a User in a Social Network, using ...

3. Two-way relation in JPA

I have the two entity classes, User and MyCharacter. User has a list of MyCharacters and each MyCharacter has a reference back to the User (owner). What I'd like to accomplish ...

4. Hibernate with relations

I have a relational DB, contains tables and all kinds of relations(1>n, n>1, 1>1 and n>n).. Let's take one of these tables which is "Department" table, this table is the most complicated ...

5. How to update a collection-type relation with mappedBy in Hibernate?

I have two related entities, say

public class Book {
    Shelf shelf;

public class Shelf {
    Set<Book> books;
If I ...

6. Hibernate: bad performance when removing element from many-to-many relation

I have to Classes (UserSet and User) which have a many-to-many relation (i.e. every user can belong to some UserSets). In the database there is a UserSet Table, a User Table ...

7. How to do many-to-many relation between the same entity

I have an Employee entity class with (Id,Name,EmployeeType). EmployeeType entity (Id, Description) where Description can be either REGULAR/MANAGER. I am confused on how to map Employees who are of type REGULAR ...

8. Hibernate ManyToOne relation to a joined subclass type

I have the following structure:

public class SuperClass

public class SubClass : SuperClass

public class ContainerClass
  public SuperClass SomeProperty {get; set;}
However, when retrieving an instance of ContainerClass ...

9. Does Hibernate's Criteria API still not support nested relations

I'd like to use Hibernate's Criteria API for precisely what everybody says is probably its most likely use case, applying complex search criteria. Problem is, the table that I want ...

10. Hibernate @ManyToMany delete relation problem

I have 2 entities: User and UsersList.

@Table(name = "USERS")
public class User {
    @Column(name = "ID")
    private Long ...

11. Making a OneToOne-relation lazy

In this application we are developing, we noticed that a view was particularly slow. I profiled the view and noticed that there was one query executed by hibernate which took 10 ...

12. JPA one-to-many relationship question (relations on one entity)

In this JPA example there is a code:

private Deity mother;

private Deity father;

private Set<Deity> children;
Why relation with father and mother is implemented by @OneToOne annotation and not in @ManyToOne relation? ...

13. Use fewer columns on SQL query through Hibernate Projections on Entity with ManyToOne relation

I'm trying to build a smaller SQL, to avoid the "select * from A" that is being build by default for hibernate Criteria. If I use simple fields (no relation), through "Transformers", ...

14. PSQLException: ERROR: relation "TABLE_NAME" does not exist

I am trying to run hibernate on a PostgreSQL 8.4.2 DB. Whenever I try to run a simple java code like:

List<User> users = service.findAllUsers();
I get the following error:
PSQLException: ERROR: relation ...

15. hibernate: how to setup on-delete="cascade" in one-to-one relation

i have to table relation one-to-one: message & scheduled_message my hibernate config

<class name="Message" table="message">
    <id name="id" column="id">
        <generator class="native" />

16. Relation many-to-many with attributes : how?

Excuse me for my poor english in advance as it is not my mother tongue.
Like in this example:

But i have in the table foo-bar 2 attributes which are not ...

17. Hibernate and parent/child relations

I'm using Hibernate in a Java application, and i feel that something could be done better for the management of parent/child relationships. I've a complex set of entities, that have some kind ...

18. ManyToMany Relation does not create the primary key

I have a ManyToMany relationship between two classes: ClassA and ClassB, but when the table for this relationship (table called objectA_objectB) there is no primary key on it. In my ClassA I ...

19. Hibernate: order multiple one-to-many relations

I have a search screen, using JSF, JBoss Seam and Hibernate underneath. There are columns for A, B and C, where the relations are as follows: A (1< -- >) B (1< ...

20. Hibernate + PostgreSQL : relation does not exist - SQL Error: 0, SQLState: 42P01

I am having some problems trying to work with PostgreSQL and Hibernate, more specifically, the issue mentioned in the title. I've been searching the net for a few hours now but ...

21. JPA map relation entity parentID

could someone help me to understand how can I define an entity with JPA mapping that has a relation with it self? For example, my entity is CompanyDivision, divisionA contains divisionB, divisionC and ...

22. How to configure Hibernate database reverse engineering tool to map database table relation as a entites inheritance?

Is it possible to configure Hibernate reverse engineering and code generation tool in such a way that one-to-many relation between tables is mapped to entities inheritance instead of enrites relation? I have ...

23. JPA joined column allow every value

I'm testing JPA, in a simple case File/FileVersions tables (Master/Details), with OneToMany relation, I have this problem: in FileVersions table, the field "file_id" (responsable for the relation with File table) accepts ...

24. How to retrieve row count of one-to-many relation while also including original entity?

Say I have two entities Foo and Bar where Foo has-many Bar's,

class Foo {
  int ImportantNumber { get; set; }
  IEnumerable<Bar> Bars { get; set; }

class FooDTO {

25. JPA OUTER JOIN without relation

I need make OUTER JOIN of two entities in JPA (saying master, detail), but the problem that at the entity level there are no relations (and i don't want add it).

class ...

26. How to get Hibernate object relations dynamically?

I'm using Hibernate and I need to find a way of retrieving the relations for an object dynamically at run-time. I can't find this in the API. Can anyone point me in ...

27. How to represent a 3-way relation with JPA?

A user may have several labels, and links. Then, a user associates a label (or more) to a link. How does one represent the later relationship? A solution could be a many-to-many ...

28. What's the best way to index many-to-one relation with hibernate search?

I have an entity with many-to-one mapping. (Product 1-* Regions, unidirectional association) What is the best way to store index of such relation? So it can be easily used to filter search ...

29. Hibernate criteria distinct with join - fetch the relation

I've searched on the internet but I didn't understand very much the problem: I'm trying to build a distinct query using criteria and a distinct clause using a projection, trying to resole ...

30. Hibernate -> n:m relation -> problem insert in a joined table

I have a bidirectional n:m relation with two entities and I have created domain objects for using with Hibernate in the latest version 3.5.3. I used this for my example: My ...

31. Hibernate Envers - traversing the relations

In my application, I have a several audited entity classes for example the following.
It contains multiple HAS-IS relations to other entities with various hibernate annotations.

public class Entity implements Serializable {


32. Problem with parent/child relation with hibernate

I am facing a problem with parent child type relations.
Hibernate docs say to add a "many-to-one" relation in child class to get value of foreign key from parent. But to make ...

33. Hibernate - encrypted reference by relations on usernames

I was wondering if my idea is possible with hibernate. What I want is that there is one table with usernames and every table wich has a reference to this table ...

34. Can't create a Many-To-One relation with all-delete-orphan cascade. MySQL says a foreign key constraint fails when deleting the parent

I started using Hibernate recently and I'm still a newbie, however, the error I'm facing doesn't seem to be simple. My current environment is:

  • Windows 7
  • MySQL 5.1.49-community
  • mysql-connector-java-5.1.13-bin.jar
  • hibernate-distribution-3.6.0.Beta1
I'm following the ...

35. JPA: How to have one-to-many relation of the same Entity type

There's an Entity Class "A". Class A might have children of the same type "A". Also "A" should hold it's parent if it is a child. Is this possible? If ...

36. Moving a database with pg_dump and psql -U postgres db_name < ... results in "ERROR: relation "table_name" does not exist"

I moved my PostgresQL database from one hard drive to another using

pg_dump -U postgres db_name > db_name.dump
and then
psql -U postgres db_name < db_name.dump
I created the database db_name the same way ...

37. Netbeans code for Postgresql and Eclipselink - identifying relation question

I have the following database tables:

  • party, with a pk "pty_id" connected to a sequence for generating pk values.
  • person with a fpk "prs_pty_id" in an identifying relation to party.pty_id.
  • company ... which is ...

38. parent-child relation, cascade-save with generated parent-key as foreign key in child table

I have two tables in parent child relation. Parent can have multiple child records. Primay key of parent table is generated by hibernate, this generated primary key of parent table is foreign ...

39. ManyToMany relation with jointable

Category EJB

package session;

import com.Entity.Category;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Item EJB
package session;

import com.Entity.Item;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class saveItemBean implements saveItemRemote {

    private EntityManager em;


40. Finding the row with matching relations using HQL

I am using Castle ActiveRecord and NHibernate. I have an Instance class which has a many-to-many relationship with a Component class. I would like to find the instance which is related ...

41. Mapping same class relation

Hi I’m trying to map some classes in hibernate there and have general problem how such mapping can be done. There is User class and Facebook user class which has the ...

42. How to handle JPA Many-to-One Relation?

I am designing an application for collecting weather data. I have 2 POJO objects "Location" and "Record". Location contains information about latitude and longitude and the current weather conditions, and Record ...

43. Mapping same class relation - continuation

This post is an continuation of this post I have DlUser Class each object of this class may have DLFaceBook class and each object of DlFaceBook can have Friends which are ...

44. Creating a many-to-many relation between an entity and an another many-to-many relation with (N)Hibernate

I'm trying to create a many-to-many association between an entity and another many-to-many association. How can that be done? I followed the Customer/Order/Product example to attach custom properties to a ...

45. jpa/hibernate drag-n-drop/orm/graphical relations

Hey all, I'm reviewing the IntelliJ ability related to JPA ER Diagrams (, and is something I've been looking for a while. Does anyone know of other tools that have similar abilities, whether ...

46. Hibernate -> LazyInitializationException with n:m relation

I have a problem with Hibernate and the LazyInitializationException. I searched and find a lot of answers, but I can not use them to solve my problem, because I have to ...

47. Can't create grails Criteria query containing a belongsTo relation

I've been trying to create a criteria builder containing a belongsTo relation and have yet to succeed. Consider the following model:

class Msg {
    static ...

48. How to cascade delete an entry without cascading into ManyToMany relations

I have a piece of code that 'updates' an entry in the database by first cascade deleting it, and then replacing it with a new object, because I had a lot ...

49. Java: Objects relations with criteria (hibernate)

I have a problem with criteria and relation between objects. I present a simple scheme before: I have 2 objects: A is the parent B is the child with a link at parent. I know how ...

50. JPA/Hibernate: ManyToMany delete relation

I have two classes, say Group and Person with a ManyToMany-Relation that is mapped in a JoinTable. If I delete a Person that has a relation to a Group, I want ...

51. Is it possible to have @OneToOne relation between 2 objects but not having the child automatically persisted in Hibernate

I'm using jpa persistance annotations. I have 2 objects, Order(parent) and Transaction(child). I want to be able to fetch my oder and get its transaction. The problem is I don't want ...

52. JEE6 JPA 2 ManyToOne Relation Creates Invalid Foreign Key

I am trying to create two entities where both entities have embeddedIds. One of the entities have 2 references to the other entity, where both of those references are related as ...

53. Hibernate Search and Relations

I have an object called MyItemBean which can have 0 or more associated KeywordBean objects. The resulting classes look like this:

public class MyItemBean {


   @ManyToMany(targetEntity ...

54. Eclipse Dali can not find table relations for MS SQL Server

I am using eclipse dali to generate jpa entities .. It works fine for Oracle, but for MS SQL Server , Dali can not find relations between tables, therefore the generated ...

55. How to select property from an entity in a hibernate relation

I have an entity class set up in Java, with a many-to-many relationship to another class. However, rather than selecting the entire entity collection, I'd like to select only a property ...

56. Cannot remove entity which is target of @OneToOne relation

I have following entities with @OneToOne relation:

public static class EntityChild extends BaseEntity {
    //Id from superclass

public static class EntityParent extends BaseEntity {

    //Id from superclass


57. Problem with retrieving data from 2 tables when having third table between them for history relations

So i have 3 tables: Table: User
Field: id, username Table: RelUserHardware
Field: id, id_user, id_hardware, datefrom, dateto, isactive Table: Hardware
Field: id, serialnumber One User can have many Hardware, but one Hardware can have only one User So ...

58. hibernate second level cache and one to one relation

I have an entity that I'd like to cache in the 2nd level cache, but it is updated frequently(via hibernate) and this makes it a poor candidate for the 2nd level ...

59. DO i manually need to create relation table in hibernate

If i have two tables


As it has one to many relation . i want to ask that do i have to manually create third table like person_phone or hibernate automatically ...

60. Do i always need to create separate class for manytomany relation in hibernate

I was reading this article But he created three classes

Do i always need separate table for relation or this can be done in 2 tables as well like only in ...

61. JPA Save non owning side of ManyToMany Relation

I have a question about how to save M2M relations. One side must be always the owning side. In our scenario we have a entity "Role" and a entity "User". A ...

62. JPA entity relations are not populated after .persist()

this is a sample of my two entities:

public class Post implements Serializable {
    @OneToMany(mappedBy = "post", fetch = javax.persistence.FetchType.EAGER)
    @OrderBy("revision DESC")
    public ...

63. Using flex and java, how to fill a datagrid when entity has a relation(one-to-many or any other)

I am using flex4 on the frontend, and java spring services on the backend. When I follow the tutorials, I can get entities from db (mysql5.0) and fill the datagrid provided by ...

64. Problem in Mapping many-to-one relation in Hibernate

With respect to my previous post Previous Post I have a Parent table A and its Child table B. Relation of A to B is one-to-many where as of that of B ...

65. Can I create an attribute without relation with DB Table in a Entity?

Can I create an attribute without relation with DB Table in a Entity ? If it can, which annotation should I use ?

66. No relations in entity classes created with NetBeans from database

I'm using Netbeans to create entity class from database, I select all table in my database and the classes are created without any information about relations, like @OneToMany, @ManyToOne etc... This is ...

67. How to map a ManyToMany reflexive relations ship with extra coloumn in JPA

I'm trying to map a USER/FRIEND relation ships using JPA over Hibernate. The ralation ship have an extra coloumn friendShipStatus that describe if the requested frien has accepted on not the ...

68. Hibernate Map an object without relation

I have a situation where i have relations like this: A person has one or more addresses. A customer has one or more addresses. Person,customers and addresses are separate tables. I used to do this ...

69. unidirectional one-to-many relation without join table

public class Book {

    @Id @GeneratedValue @Column private Long bookId;

    @Column private String name;


70. @OneToOne relations hibernate question

I'm working in a project using Hibernate +JPA. I have this Entity class:

public class CafeUser implements Serializable {

    @GeneratedValue(strategy ...

71. Hibernate JPA2 - n+1 select problem affects only one side of OneToOne relation

I was not getting lazy loading on either class until I added bytecode instrumentation via:


72. @ManyToOne relation never read

I have to implement parent-child tree with EclipseLink. The following code compiles Ok, reasonable DDL code is auto-generated, but the children field always resolves to an empty set, and tracing shows that ...

73. JPA : relation with other column than id

When I do a relation one to one with to entities, JPA use the id to register the target ; but I should want an other column. How is possible ? For ...

74. Hibernate Many to Many relation

I have a problem with Hibernate many to many relationship. In the project has two persistence class named Student and Course. I configure both classes with many to many relationship. Thats ...

75. Insert one-to-many relation using hibernate

What is the best way to insert data using Hibernate? As a example when I wont to insert new Order into order table. It has one-to-many relationship with Item. when we ...

76. Transitive relation in hibernate

I just want to know if transitive relation(i don't know if it can be called so) can be persisted in hibernate using annotations. ie, i have 3 pojo classes namely A,B and ...

77. Exception while many-to-one relation org.hibernate.MappingException: Could not determine type for

i want to write a simple many-to-one ORM using hibernate. I have tow tables, user and location. Location contains country names one of which i want to refer in user class.

public class ...

78. Hibernate - delete child in one-to-many relation throws ObjectDeletedException

Please, sorry if i ask already asked, but i just don't understand why Hibernate throws exception mentioned in title. I'm beginner and probably don't understand state management idea behind Hibernate. I have ...

79. Create a JPA many-to-many relation using an id instead of an object

I have a large dataset which I am importing in bulk with rows looking like

(news_id, category_id_1, category_id_2, ..., category_id_9)
Each category_id_x is an integer from a fixed set of categories. I want to ...

80. Hibernate Enum relation mapping in database

Currently I have Enums let's say

enum Category {
  A, B
enum Type {
  TYPE1(Category.A), TYPE2(Category.B), TYPE3(Category.A)

  private Category cat;
  private Type(Category cat) { ...

81. JPA manytoone relation delete operation

I want to delete ExternalProcessed files has same ExternalProcessedFileInfo But this query fails.It is easy when Relation reverted to @onetomany and cascade on delete but ...

82. hibernate many to many relations cascade

Newbie to hibernate i have two tables A and B that have many to many relations defined by a table AB(A_ID and B_ID) with foreign key reference to A.A_ID and B.B_ID ...

83. JPA - how to avoid the same entity reference when having multiple relations of the same type?

My app has Struts-based GUI and EJB3 + JPA based backend. Say I have entity class like below:

class Command {
    private Long id;


84. help to identify relation between database entites (for hibernate mapping)

I have a web app in which I use hibernate and deploy on tomcat using ant .I have created a hibernate.cfg.xml in source directory with all mapping values . My app has ...

85. Sub-optimal queries over many-to-many relations with HQL

I have two entities, Location and Industry, and a link-table between them. I've configured a many-to-many relationship, in both directions, between the two entities. In a search query, I'm trying to select ...

86. avoid relation table in Hibernate's mapping one-to-many(or one-to-many) association into db tables

I am new to Hibernate. I notice that in Hibernate, mapping the java classes into database tables often involve relation tables, even sometimes relation tables are not necessary(Like in a one-to-many ...

87. Why do Hibernate docs recommend to use a join table for a one-to-many relation?

I thought that the common way to model a one-to-many relation in a database is via a foreign key relationship (i.e. one customer with many orders -> order table gets a ...

88. Hibernate create object in relation through factory

I'm new to Hibernate and I'm trying to achieve the following: the class i'm working with is persistent and is stored in DB. It looks like this:

class Card {
  private ...

89. Relation not found error with play and postgres (while table does exists)

I have a table called ETL_TABLES which resides on the public schema. In my application.conf I have the following line:

that should mean the search_path of postgres is set to the public schema. I ...

90. JPA Relation or Secondary Table

Hi I am reengineering one of my project with JPA which was initially on iBatis.

public class Entity{
    //ids and other stuff
    String locale;

91. What is Object/relational mapping(ORM) in relation to Hibernate and JDBC?

Can someone explain, in layman terms, what is Object/relational mapping(ORM) in relation to Hibernate and JDBC? Diagrams would be especially helpful for understanding... EDIT: I found this via google for Hibernate ORM, ...

92. How to map a dynamic relation in JPA

I have an Entity for holding Selection Domains, e.g. for Dropdown Boxes:

public class Selection {
    private long id;

    private String category;

93. Hibernate 3.6.7: Problem with @ANY and Foreign-Key

I have the entities "User" and "Customer":

@Table(name = "USR_USER")
public class User extends PersistentObject {


   @Any(metaColumn = @Column(name = "USR_OWNERTYPE"))
   @AnyMetaDef(idType = "long", metaType = ...

94. hibernate OneToOne relation with compound key

enter image description here

public class UserCompoundKey implements Serializable {  

    private int user_id;
    private String user_name;

    public UserCompoundKey(){


95. How to set values treated as NULL in JPA relations

I have an Entity "A" with a one-to-many relation (1:n) to another Entity "B". Unfortunately, the (for years existing) database defines the column in B for the primary key of A ...

96. Criteria query ManyToMany relation wint

Table A --(joinTable)-- Table B So, there's many-to-many relation.

class A{
return bs;
I already have NOT so small Criteria Query, I need to add additional restriction.
crit.add("", wantedBsList);
And my consol says:
SQLException: Parameter #5 has not ...

97. HQL with Null check for one-to-one relation

I have the following one-to-one relation in Hibernate (that could be null):

<one-to-one name="details" class="com.example.Details" lazy="false" cascade="all"/>
I am trying to select all entities that have non-null details with HQL:
from Entity e where ...

98. Query M:N relationship with GORM for entity instances _not_ in relation to each other?

I need to track a M:N relationship with attributes, so I'm using a link table (following the pattern at Many-to-Many Mapping without Hibernate XML) ...

99. setting the correct jpa mapping for shopping cart items and product

I am learning jpa through some examples ,involving a shopping cart and cart items.I defined them as below..but am not very sure about which mapping to use

class Product{

   private ...

100. Optional one-to-one relation in hibernate

I have been trying to find some information on how to implement a optional one-to-one constraint in hibernate. Apperently hibernate doesn't support @OneToOne(optional=true) from JPO, so how am I supposed to ...