JPA — Quick Notes
What is JPA?
- JPA defines the mapping of the Java class to the table inside the database using things like entities, relationships.
- All the entities are stored inside a separate package PROJECT_NAME.entity
- To manage your entities in JPA we use something called as “Entity Manager.”
@Table: The table annotation helps you to map your object to your table.
@Entity: We define a Java class as an entity. This annotation specifies that something has to be persisted inside the database.
@Id: We can make any data member of the Java class as a primary key of the table by putting this annotation on the top of it. Using @GeneratedValue annotation along with the @Id annotation we can make the field to auto-generate the value for itself.(auto-increment of the primary key)
@Column: This annotation is used to map the data member of the Java class to some specific attribute in the database.
@Repository: Repository indicates something which interacts with the database.
@Transactional: Instead of implementing transaction management in each method, what JPA provides is a simple interface to do declarative transaction management. The way we can do that is by saying @Transactional.
You can also establish relationships between the different entities using @OneToOne, @OneToMany, etc.
- Once we have created an entity, we would need to be able to save this to a database.
- How do we store entities to the database and retrieve them from the database?
- The way we would do that is by using something called an entity manager.
- We need to create a save method that will accept a particular entity and will save the entity on to the database.
- Entity Manager provides a method called persist that can be used to make an instance managed and persistent.
- When I say something.persist(“Jack”), what it does is it saves it to the database and also starts tracking it in the persistence context.
- Jack is now inside the persistence context.
- So whatever changes I make to the Jack are now being tracked by the persistence context. Important thing to understand is entity manager only tracks those objects which are persisted through it.
- Only those things which are in the persistence context are tracked by the entity manager.
- So we need to put an annotation so that this is @Autowired.
Command Line Runner
There’s a concept called command line runner. This command line runners are typically executed when the Spring context launches up.