Skip to content
Advertisement

Spring JPA-I get error that object is not persisted even though i have persisted it

I am using Spring boot-I have 3 classes User,Role and UserRole.I have pesisted both role object and user object but i get error that role object is not persisted.The mappings- between User and UserRole is OneToMany ,between Role and UserRole OneToMany.In the UserServiceImpl class i have persisted Role object roleRepository.save(userRole.getRole()); Error is-

JavaScript

Advertisement

Answer

Couple of issues here.

The first (and the question) issue and the reason why you are getting a “Transient state error” is because you are trying to save an entity with entities attached to it that are NOT yet managed by hibernate.

Have a read of: Entity Lifecycle Model in Hibernate

JavaScript

So you are somewhere trying to save a UserRole with a Role that is not yet managed.

When you call new on an entity, it is in a Transient state. Hibernate doesn’t know how to handle it. It doesn’t have a database ID and is not part of the context for hibernate to manage (make the relevent queries etc).

To make an entity managed you need to save it via the repo. I.e. roleRepo.save(role) You will then notice it then has an Id and is now managed by hibernate.

JavaScript

This service above doesn’t maybe do what you expect. You are getting the Roles and saving them. You then don’t replace the Role in UserRole with the managed one back from the repo. Maybe this would work?

JavaScript

So when it goes on to save the User:

JavaScript

The UserRoles (which are still transient) have a managed Role at least. The Cascade.ALL should do what you expect (I am unsure mind!) and save the transient UserRoles because Cascade.ALL will save the children UserRoles.

https://www.baeldung.com/jpa-cascade-types

=============================

The second issue, not causing the problem in question, but you may want to go have a think about:

At the moment you have: User 1 : M UserRole UserRole M : 1 Role

1 User has many UserRoles. 1 Role has many UserRoles.

The modelling here just smells off.

Usually you’d have some Role entities/database entries that can be related to a user via ManyToMany relationship.

User signs up, is given the “USER” role in their Set<Role> userRoles rather than creating a new Role for each user with “USER” as a field.

So a user has a relationship to a role via a “join table” UserRole.

Spring can already create a join table for you. You do not really need the UserRole entity in your code as it stands as it just holds a FK_User and FK_Role.

Basically, you want: User M:M Role I.e. a user can have many roles.

Simply use the @ManyToMany annotation for a Many:Many relationship between user and roles. To add a role you search the database for Role findByRoleName And add that managed entity to the user’s roles and then persist the user.

ManyToMany Baeldung

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement