JavaEE workshop #3

Kuba Hejda

(Lombok, JPA, spring-data-jpa, DTO)

Previous workshop

  • IoC/DI
  • Bean, Configuration
  • Multitier architecture
  • JSON, REST - Statelessness, Operations, HttpStatus

Content

  • Little more on beans, autowiring and lifecycle
  • JPA
  • spring-data-jpa
  • Lombok
  • DTO

Beans

  • Their lifecycle is being operated by the container
  • Custom functionality can be injected around the initialization and destruction of the bean
  • Next to the other beans we can let Spring populate property values from config file

Beans

  • DI can be done via 3 mechanisms:
    • Injection to property
    • Injection via setter
    • Injection via constructor
  • Beans can be autowired 
    • byType
    • byName
    • byConstructor
  • Default autowiring type is byType, when more than 1 bean of the type is found, then @Qualifier annotation helps distinguish which one we want to inject
  • object/relational mapping facility for managing relational data in Java application
  • consists of four areas:

    • The Java Persistence API

    • The query language

    • The Java Persistence Criteria API

    • Object/relational mapping metadata

JPA Providers

JPA architecture

JPA Architecture

EntityManagerFactory This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.
EntityManager It is an Interface, it manages the persistence operations on objects. It works like factory for Query instance.
Entity Entities are the persistence objects, stores as records in the database.
EntityTransaction It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
Persistence This class contain static methods to obtain EntityManagerFactory instance.
Query This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

JPA mapping - annotations

@Entity Specifies to declare the class as entity or a table.
@Table     Specifies to declare table name.
@Basic Specifies non constraint fields explicitly.
@Embedded Specifies the properties of class or an entity whose value instance of an embeddable class.
@Id Specifies the property, use for identity (primary key of a table) of the class.
@GeneratedValue Specifies, how the identity attribute can be initialized such as Automatic, manual, or value taken from sequence table.
@Transient Specifies the property which in not persistent i.e. the value is never stored into database.

JPA mapping - annotations

@Column Used to specify column or attribute for persistence property.
@SequenceGenerator  used to define the value for the property which is specified in @GeneratedValue annotation. It creates a sequence.
@TableGenerator Used to specify the value generator for property specified in @GeneratedValue annotation. It creates a table for value generation.
@AccessType Used to set the access type. If you set @AccessType(FIELD) then Field wise access will occur. If you set @AccessType(PROPERTY) then Property wise assess will occur.
@JoinColumn Used to specify an entity association or entity collection. This is used in many- to-one and one-to-many associations.

JPA mapping - annotations

@UniqueConstraint Used to specify the field, unique constraint for primary or secondary table.
@ColumnResult References the name of a column in the SQL query using select clause.
@ManyToMany,
@ManyToOne,
@OneToMany,
@OneToOne
Used to define a many-to-many relationship between the join Tables.
@NamedQueries Used for specifying list of named queries.
@NamedQuery Used for specifying a Query using static name.

Java bean validation - JSR-303

  • constraints in the form of annotations placed on a field, method, or class
  • Hibernate validator  - reference implementation 1.1
public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}

JPA - bean conventions

  • Bean contains the default constructor.

  • Non-Boolean property contains getter and setter methods.

  • Boolean property contain setter and is method.

  • Getter method of any property should start with small lettered ‘get’ (java method convention).

  • Setter method of any property should start with small lettered ‘set’ (java method convention).

JPA Entity Lifecycle

  • managed vs detached
  • entity updates in active transaction are persisted
  • lazy loading works only in active transaction

JPA - JPQL

  • Java Persistence Query Language defined in JPA specification.
  • based on SQL syntax
  • won’t affect the database directly
  • SQL works directly against relational database tables, JPQL works with Java classes and instances
  • aggregate functions (COUNT, SUM, AVG, MIN, MAX)
  • BETWEEN, LIKE
Query query = entitymanager.createQuery("Select UPPER(e.ename) from Employee e ORDER BY e.ename ASC");
List<String> list = query.getResultList();

JPA - criteria API

  • alternative way for defining JPA queries
  • useful for building dynamic queries
EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Country> cq = cb.createQuery(Country.class);
Root<Country> country = cq.from(Country.class);
cq.select(country);
TypedQuery<Cuntry> q = em.createQuery(cq);
List<Country> allCountries = q.getResultList()

JPA links

Spring boot + data-jpa

<!-- https://mvnrepository.com/artifact/org.springframework.boot
             /spring-boot-starter-data-jpa -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.4.0</version>
</dependency>
#application.properties

#spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

spring.datasource.url=jdbc:postgresql://localhost/ita2022
spring.datasource.username=ita2022
spring.datasource.password=ita2022

Lombok

  • Widely used 3rd party library for generating the boiler-plate code
  • Helps create more readable and smaller code
  • Website
  • @Getter, @Setter, @AllArgsConstructor, @RequiredArgsConstructor, @EqualsAndHashCode, @ToString, @Builder, ...
  • Every annotation has various settings
  • Data transfer object
  • Represent input and output of exposed API
  • Why ?
    • security
    • clear cut of transaction
    • different data representation
    • split representation logic from internal domain (entity)
  • How ?
  • Where ?
    • service layer

DTO

Proxy pattern

  • Used to wrap existing behavior with the custom one
  • Very very very widely used in Spring

Q & A

ITA 08 - Workshop 03

By IT-absolvent

ITA 08 - Workshop 03

Workshop #3

  • 309