[Spring] Saving a Java Object with JPA
JPA로 자바 오브젝트로 저장하기?
- Hibernate/JPA CRUD (4)
Sample App Features
- Create a new Student
- Read a Student
- Update a Student
- Delete a Student
Student Data Access Object
- Responsible for interfacing with the database
- This is a common design pattern: DataAccessObject(DAO)
- Our DAO needs a JPA Entity Manager
- JPA Entity Manager is the main component for saving/retrieving entities
JPA Entity Manager
- Our JPA Entity Manager needs a Data Source
- The Data Source defines database connection info
- JPA Entity Manager and Data Source are automatically created by Spring Boot
- Based on the file: application.properties(JDBC URL, user id, password, etc…)
- We can autowire/inject the JPA Entity Manager into out Student DAO
Student DAO
- Step 1: Define DAO interface
- Step 2: Define DAO implementation
- Inject the entity manager
- Step 3: Update main app
Step 1: Define DAO interface
public interface StudentDAO {
void save(Student theStudent);
}
Step 2: Define DAO implementation
Step 3: Update main app
Spring @Transactional
- Spring provides an @Transactional annotation
- Automagically begin and end a transaction for your JPA code
- No need for you to explicitly do this in your code
- This Spring magic happens behind the scenes
Specialized Annotation for DAOs
- Spring provides the @Repository annotation
- Applied to DAO implementations
- Spring will automatically register the DAO implementation
- thanks to component-scanning
- Spring also provides translation of any JDBC related exceptions
Transactions 간략히 보기
The @Transactional annotation is the metadata that specifies the semantics of the transactions on a method. We have two ways to rollback a transaction: declarative and programmatic.
In the declarative approach, we annotate the methods with the @Transactional annotation. The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions, and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions.
출처 : 유데미, luv2code.com, https://www.baeldung.com/transaction-configuration-with-jpa-and-spring
댓글남기기