Thursday, 27 December 2018

Spring Data JPA

Spring Data JPA

·               What is Spring Data
·               Configurations
·               Domain/Entities
·               Persistent Identity
·               Identifier Generation
·               Customizing the Entity Object
·               Entity Relationships
·               EntityManager & Persistent Context
·               Repository and Repository Hierarchy 
·               User Defined Repository
·               Defining Query methods
·               Pageable
·               Query creation : Custom Queries and Named Queries 
·               Disadvantages
What and Why?

Spring data is high level spring source project whose purpose is to unify and ease access to different kind of persistence stores, both relational DB and NoSQL data stores.
Features:
Powerful repository and custom object mapping abstractions.
Dynamic query derivation from repository method names.
Implementation domain base classes providing basic properties.
Several modules such as: Spring data JPA, Spring Data Mongo DB, Spring Data REST, Spring data Cassandra ,Domain/Entities
•An entity is a plain old java object (POJO)
Requirements:
·              annotated with the javax.persistence.Entity annotation
·              public or protected, no-argument constructor
·              the class must not be declared final
·              no methods or persistent instance variables must be declared final

Entities may extend both entity and non-entity classes
Persistent instance variables must be declared private, protected
import javax.persistence.*;
@Entity
public class User {
   private String email;
   private String name;
}
Persistent Identity Each entity must have a unique object identifier (persistent identifier)

Identifier (id) in entity = primary key in database
Example :
import javax.persistence.*;
public class User { 
 @Id
   private Long id;
}
Identity Generation

Identifiers can be generated in the database by specifying @GeneratedValue on the identifier
Four pre-defined generation strategies:
1.           AUTO,
2.           IDENTITY,
3.           SEQUENCE,
4.           TABLE
Specifying strategy of AUTO indicates that the provider will choose a strategy
Example:
import javax.persistence.*;
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
}
Customizing the Entity Object

In most of the cases, the defaults are sufficient
By default the table name corresponds to the unqualified name of the class
Customization:
@Entity
@Table(name = "user")
public class User {}
The defaults of columns can be customized using the @Column annotation
@Column(nullable = true, unique = true)
private String email;
@Column(name = "full_name", nullable = false, length = 25)
private String name;

Entity Relationship

There are four types of relationship multiplicities:
1.           @OneToOne
2.           @OneToMany
3.           @ManyToOne 
4.           @ManyToMany
The direction of a relationship can be:
bidirectional – owning side and inverse side
unidirectional – owning side only
Supports cascading updates/deletes
You can declare performance strategy to use with fetching related rows
FetchType :
LAZY, EAGER
Managing Entities - JPA

Entities are managed by the entity manager

The entity manager is represented by javax.persistence.EntityManager instances
ach EntityManager instance is associated with a persistence context
A persistence context defines the scope under which particular entity instances are created, persisted, and removed

persistence context is a set of managed entity instances that exist in a particular data store Entities keyed by their persistent identity
Only one entity with a given persistent identity may exist in the persistence context
Entities are added to the persistence context, but are not individually removable (“detached”)
Controlled and managed by EntityManager
–Contents of persistence context change as a result of operations on EntityManager API
Few Configurations for Spring data
DB and ORM configurations.

spring.datasource.url = jdbc:sqlserver://localhost:1433;databaseName=aup
spring.datasource.username = sa
spring.datasource.password = test@1234
spring.datasource.driverClassName = com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.database = SQLSERVER
#spring.jpa.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.dialect = org.hibernate.dialect.SQLServerDialect
Few configurable annotations:
  @EnableTransactionManagement
  @EnableJpaRepositories(basePackages={"com.test.db.repo"})
  @EntityScan(basePackages={"com.test.db"})

Repository and Repository Hierarchy

The goal of the repository abstraction of Spring Data is to reduce the effort to implement data access layers for various persistence stores significantly.
The central marker interface
 Repository<T, ID extends Serializable>
Hierarchy :
Interface JpaRepository<TID>
interface PagingAndSortingRepository<TID>
interface CrudRepository<TID>
interface Repository<TID>
User Defined Repository

Spring Data Repository, you’ll have three options:
Using of a CRUD operations that implemented by the Spring Data infrastructure
Defining of a query methods and
Manually implementing your own custom repositories
Example :
public interface UserRepository extends JpaRepository<User, Long> {
}


Defining Query methods

Query methods implemented in spring data repositories will be used for creating the dynamic queries.
public interface UserRepository extends JpaRepository<User, Long> {
   User findByEmail(String email);
   List<User> findAllByName(String name); 
 }
Pageable

Pageable pageable = new PageRequest(010);
Sort.Order order1 = new Sort.Order(Sort.Direction.ASC"id");
Sort.Order order2 = new Sort.Order(Sort.Direction.DESC"name");
Sort sort = new Sort(order1, order2);
pageable = new PageRequest(010, sort);
pageable = new PageRequest(010new Sort(Sort.Direction.DESC"name"));
OR
Pageable pageable = new PageRequest(page, count, Direction.ASC, sortColumn);
propertyRepository.findAll(pageable);
Query creation : Custom Queries

•@Query annotation is used to defining the custom queries in spring data.
•Supports JPQL and native SQL.
•@Param method arguments to bind query parameters.
•Supports SpEL expression.
•Like expression supported inside @Query annotation.
•@Query annotation, this will take the precedence over @NamedQuery


Examples :
@Query("select u from User u where u.name=?1")
User findByUserName(String name);
@Query("select u from User u where u.name like%:name%")
User findByUserName(@Param("name") String name);
@Query(value = "select * from user where name=?1", nativeQuery = true)
User findByUserName(String name);
Query creation : Named Queries

Named query are the static queries.
•The named queries are defined in the single place at entity class itself with each query has its unique name.
•@NamedQuery annotation can be applied only at the class level.
•Named queries have the global scope.
•If you have to define more than one named queries the use @NamedQueries
•All the named queries are validated at application start-up time and there is no failure at run time.
Example :
@NamedQuery(name = "User.findByNameNamed", query = "SELECT u FROM User u WHERE LOWER(u.name) = LOWER(?1)")
@Table(name = "user")
public class User {
…..
}


Query creation : Modifying Queries

@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);



No comments:

Post a Comment