• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using a new object for reference to an existin entity

 
Jhon Gonzales
Greenhorn
Posts: 22
Java Linux PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Guy, I have this doubt. May I create a new object that represent an entity and assign an existing primary key, and use this object for reference to an existing entity, instead of use getReference or find method of EntityManager?.

Regards.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And why would you not simply use the find-method of EntityManager?
 
Jhon Gonzales
Greenhorn
Posts: 22
Java Linux PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because I have seen it in a code and the code works. The code have the flowing structure:


There is an Entity named A, with a relation with entity B. The relation is OneToMany using a Join Table and the Owner in the relation is the Entity A. B is an Entity with predefined inserts, so its only used for reference in relations.

So, when there are creating a new Object A for persist it, they don't use find or reference for get a reference of an entity B and add it to the list, instead they create new Object of B, assing its a primary key and add the new Object B to the List that Belong to the Object A. And the code works and i don't understand why its work.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A concrete example could look like this:

Assume we have already 10 phones in the database with ids ranging from 1 to 10. To create a new person the code looks like:

Do I understand correctly?
 
Jhon Gonzales
Greenhorn
Posts: 22
Java Linux PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And I probably can assume that the Phone entity has other properties (instance members) as well besides the id property, otherwise it would be a very weird entity

I'm not a JPA (Hibernate) guru at all, but I've never done it as you have described. And I wonder why the other properties of Phone (Object B) are not changed to null if an existing primary key is used.

Could you share (a part of) the mapping of both entities? You can always use dummy class and property names.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic