0

I have 3 tables Users, Archivements and ArchivemetnsUSers. This is a relathionship Many-To-Many.

My problem is that i want save a new user in my DataBase but, i dont want save/update the archivement assigned to user, because i have only N pre-existent archivements.

Then, when i go to save hibernate session for my user... i get a exception: the selected archivement exists in DataBase, and hibernate cant save duplicate PrimaryKey.

How i avoid this problem?

Any annotation? or trick?

2 Answers2

0

to avoid this problem you will have to fetch the Archivement from database and assign it to the new user you have created, for Ex :

//fetching the Archivement:
Archivements a=yourDaoClass.getArchivementById(id);

//creating a new user
Users u=new Users();
u.setName("someOne");

//assign the new user to the existing ashivement
List<User> users=a.getUsers();
users.add(u);
a.setUsers(users);
session.saveOrUpdate(a);

this must assign the existing Achivement to the new User.

Mohamed Nabli
  • 1,629
  • 3
  • 17
  • 24
  • Ty for answer but i test it and doest work. Same behaviour. Save method try save Archivements too.. And return a conflict Duplicate Primary key. – Yeray Ventura Garcia Apr 15 '16 at 10:45
  • int your user class u have declared a list of achivements right ?? – Mohamed Nabli Apr 15 '16 at 10:47
  • in user clase i have a @OneToMany(mappedBy="user",cascade = CascadeType.ALL) private Set archivements = new HashSet(); The ManyToMany works fine.. but i dont want that save archivements in DataBase, only. If i dont put Cascade.ALL then ArchivemetnsUSers doesnt persist – Yeray Ventura Garcia Apr 15 '16 at 11:00
  • i get other problems: nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.MyProject.pojo.Archivements.ArchivementsUser, could not initialize proxy - no Session On other hand, i think that isnt good idea save for Archivements, because y have other relationships with User ManyToMany, that i need create in the future... – Yeray Ventura Garcia Apr 15 '16 at 15:17
  • on your Users Class make the list of achivements with fetch type **EAGER** – Mohamed Nabli Apr 15 '16 at 17:01
  • ty for help but this havent sense. EAGER is default type of fetch, and your funtion is clear in this link http://stackoverflow.com/questions/2990799/difference-between-fetchtype-lazy-and-eager-in-java-persistence. – Yeray Ventura Garcia Apr 16 '16 at 19:47
0

finally, the problem was that i need get archivements, set archivements to user and save user instance in ONE TRANSACTION, for hibernate understand that these archivements registers exist in DataBase.