
Spring Boot's layered architecture promotes separation of concerns and modularity through distinct layers, each with specific responsibilities.
Handles user interactions and HTTP request processing.
Components:
@Controller or @RestControllerNote: Should remain thin, focusing only on request handling, validation, and responses
Contains the application's core business logic.
Components:
@ServiceManages database and external data source interactions.
Components:
@Repository annotationEnables database handling via Java, bridging the gap between databases and SQL.
Key Points:
1. JPA is the specification, Hibernate is an implementation
2. Hibernate predates and influenced JPA
3. Hibernate ORM is a mature implementation
A logical container managing entity instances between application and database.
Features:
1. Entity Management: First-level cache
2. Identity Management: Ensures unique entity identity
3. Dirty Checking: Automatic change detection
4. Lazy Loading: On-demand entity fetching
5. Write-Behind: Optimized database writes
Part of Spring Data family, simplifying JPA-based repository implementation.
@Service
public class UserService {
@PersistenceContext
private EntityManager entityManager;
public User findById(Long id) {
return entityManager.find(User.class, id);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
public interface UserRepository extends JpaRepository<User, Long> {
// Automatic methods:
// save(Entity)
// findById(ID)
// findAll()
// delete(Entity)
// count()
// exists(ID)
}
@Service
public class UserService {
@Autowired
UserRepository userRepository;
// CREATE
public User createUser(User user) {
return userRepository.save(user);
}
// READ
public Optional<User> findUser(Long id) {
return userRepository.findById(id);
}
}
A contract specifying required method implementations without providing the implementation itself - essentially a blueprint for classes.