简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM