Spring Boot JPA - What is JPA, Entity, Repository

 Database 

Spring Boot uses JPA (Java Persistence API) to map Java objects to tables in the database. Mapping an object to a table in a database is called ORM(Object Relational Mapping) and JPA is one of Java's way of achieving ORM. JPA is not dependent on specified database language, so that users can associate many different databases using JPA. 

JPA

Data persistence is the ability to maintain data between application executions.  Persistence is vital for  applications that are developed for enterprises. JPA is a collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle corporation. To reduce the burden of writing codes for relational object management, a programmer follows the JPA framework, which allows easy interaction with the database instance. JPA standardizes the task of object-relational mapping by using annotations or XML to map objects into one or more tables of a database. 

Creating Database Scheme automatically 

From the application.properties, we can set up database scheme automatically by configuring hubernat.hbm2ddl.auto . Various methods to create database scheme are as follows.
  • create: delete original table and create new table (drop + create) 
  • create-drop: similar to create, but it will drop the table when application stops 
  • update: only changes made will be applied 
  • validate: check if entity and table is mapped correctly 
  • none: don't do any 
In initial development phase we might use create or update. But when we are distributing out application, we should use the option validate or none. 

Defining Entity in Spring Boot 


@Entity
@Table(name = "Example")
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ExampleEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(length = 100, nullable = false)
private String content;
}

  • Each entity must have @Entity and @Id annotations.
    • @Entity specifies that the class is an entity and is mapped to a database table. 
    • @Id specifies the primary key of an entity and the @GeneratedValue provides for the specification of generation strategies for the values of primary keys. 
    • @Table specifies the name of the database table name to be used.
  • GeneratedValue strategy 
    • IDENTITY generation: expects values generated by an identity column in the database, meaning they are auto-incremented.
    • AUTO generation(default): the persistence provider will determine values based on the type of the primary key attribute(number or UUID) 
    • SEQUENCE generation: this generation uses sequences if they're supported by our database, and switches to table generation if they aren't. 
    • TABLE generation: uses an underlying database table that holds segments of identifier generation values. 
Mapping annotations 
  • @Column(): configures the column that will be mapped to the field 
    • name: name of the column that will be mapped to the field 
    • insertable, updatable: readonly 
    • nullable: to allow null values or not 
    • unique: specifies whether the column is unique 
    • columnDefinition, length, precision, scale... 
  • @Temporal(): maps date  
    • @Temporal(TemporalType.DATE) -> date 
    • @Temporal(TemporalType.TIME) -> hours
    • @Temporal(TemporalType.TIMESTAMP) -> date and hours
  • @Enumerated: maps enumerated values 
    • Default is EnumType.ORDINAL -> use ENumType.STRING instead 
  • @Lob: maps to CLOB, BLOB 
    • Return type can be either String or byte[] 
  • @Transient: do not map this field
  • @Id
    • IDENTITY: database will automatically assign id 
    • SEQUENCE: use database's sequence object 
    • TABLE: create a table for key mapping and use that table to generate id
    • AUTO: default and generation method depends on the database  

Defining a repository 


@Repository
public interface ExampleRepository extends JpaRepository<ExampleEntity, Long> {

}

  • Types of Repository
    • JpaRepository: An interface that extends PagingAndSortingRepository and CrudRepository. It also provides JPA related methods such as flushing the persistence context and delete records in a batch. 
    • CrudRepository: Provides CRUD functions 
    • PagingAndSortingReposiroty: Provides methods to do pagination and sort records.
  • Functions provided by CRUD
    • save() : save an iterable of entities
    • findOne() : get a single entity based on passed primary key value 
    • findAll() : get an iterable of all available entities in the database 
    • count() : return the count of total entities in a table 
    • delete() : delete an entity based on the passed object 
    • exists() : verify if an entity exists based on the passed primary key value 

Many to One 

The difference between relating objects Vs relating tables in a database is that, when we relate objects, we reference the object to be related. In tables, we use foreign key to relate tables. And tables can related each other in both directions using a single foreign key. However each objects must create fields to relate in both directions. To overcome this differences, there are ways to map objects bidirectionally. 
  • Only a single object is the owner of the relationship. 
  • The owner will manage foreign keys. 
  • The object which is not an owner will use mappedBy attribute.
  • The object which is not an owner can only read. 

Comments

Popular posts from this blog

Structures of JAVA

What is URI(URN, URL)

Spring Boot JPA - Pagination

Java Data Structures VS Python, C/C++ Data Structures

Design Pattern - Proxy