Skip to content

SpringData JPA

Wuyi Chen edited this page Feb 20, 2019 · 14 revisions

Spring has a SpringData JPA module which could provide additional convenience comparing the classic combination of JPA and Hibernate.

Data Entity

First you need to define a data entity class (Java POJO) which will map to a database table.

@Entity
@Table(name = "licenses")
public class License{
    @Id
    @Column(name = "license_id", nullable = false)
    private String licenseId;

    @Column(name = "organization_id", nullable = false)
    private String organizationId;
   
    /* omit setters and getters */
}

DAO (Data Access Object)

To define a DAO, you just need to define an interface, the magic is you don't have to implements the methods defined in this DAO interface.

  • By extending the CrudRepository interface, your DAO will contain basic CRUD operations (save, findOne, findAll, delete, deleteAll, exists and count) automatically. You don't have to implement those functions and you can use those functions directly.
  • For customized queries, you just need to define functions in this DAO interface based on the naming convention. You don't have to implements those functions and SpringData JPA will automatically implements those functions and generate SQL query.
@Repository
public interface LicenseRepository extends CrudRepository<License, String>  {
    // query by organizationId
    public List<License> findByOrganizationId(String organizationId);
    // query by organizationId and licenseId
    public License       findByOrganizationIdAndLicenseId(String organizationId, String licenseId);
}
Clone this wiki locally