topcan5
topcan5

Reputation: 1707

Spring Data JPA: persist a nested object

I have a USER(id, role_id, first, last) object, which contains a ROLE(id, role_name) object. ROLE are predefined in the DB, the data looks like: 0, user; 1, admin; 3 superadmin... What is the best way to persist (save) a USER and add role_id to the user based on the role_name? When creating the user, I know the role_name, but not the role id. Do I need to query the role id first then add it to the USER object? I am sure there is a smarter way to do it in Spring Data JPA. Please help, thanks.

Upvotes: 0

Views: 1829

Answers (1)

rikica
rikica

Reputation: 351

You do have repositories configured, right?

Assuming you have RoleRepository extends JpaRepository<Role, Long> interface you can define method Role findByRoleName(String roleName) and fetch Role object, attach it to newly created User object and persist that user via user repository.
Of course, you have to have valid relationship in User class, let's say @OneToMany(cascade=ALL, mappedBy="user") private Set<Role> roles.
cascade annotation property is configurable of course.

Even better would be if you'd load all roles at application startup in memory since you have them predefined, store them into Map and fetch from map when needed.

Upvotes: 2

Related Questions