I'm just getting into the world of JPA and one thing that seems a little confusing to me is what Repository classes responsibilities are vs. the responsibility of the Entity classes.
For example, if I have associations defined between two entities, should the adding/removing of the child object happen in the parent's repository or entity class?
Also, should saving just be handled by the entityManager.persist method calls in a Service or should there be a custom save method in the repository class?
Thanks!
Note: The examples below are taken from Spring Data JPA documentation.
An Entity
is your domain object, which often corresponds to a row in the table. I said often because an Entity
can be part of a row, or rows from multiple tables joined together. In the context of relational databases, an Entity
corresponds to a relation. Here's an example:
@Entity
public class User {
@Id
@GeneratedValue
Long id;
String lastname;
... // Other fields, such as the user role, as well as getters and setters
}
A Repository
is an object which provides basic CRUD operation on one Entity
. Here's an example:
public interface UserRepository extends JpaRepository<User,Long> {
@Query("select u from #{#entityName} u where u.lastname = ?1")
List<User> findByLastname(String lastname);
}
A Service
is an object which operates on one or more Repository
objects, providing application-specific logic, and addressing cross-cutting concerns such as transaction management. Here's an example:
@Service
class UserManagementImpl implements UserManagement {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
@Autowired
public UserManagementImpl(UserRepository userRepository,
RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
@Transactional
public void addRoleToAllUsers(String roleName) {
Role role = roleRepository.findByName(roleName);
for (User user : userRepository.findAll()) {
user.addRole(role);
userRepository.save(user);
}
}
JPA is often used with three modules:
- the Entity itself
- the Service
- the Repository
The Entity basically doesn't have any responsibility and its just a POJO (Plain Old Java Object) with fields and getters and setters.
The Service is responsible for doing the CRUD (Create Read Update Delete) Operations, so it accesses the EntityManager or in Hibernate the SessionFactory and performs the inserts and stuff.
The Repository often just provides the same methods as the Service and delegates to the Service. But in case you need to have something done with the objects from the database before you use them or before you write them, it is done in the Repository. You could also implement caching there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With