-
Notifications
You must be signed in to change notification settings - Fork 59
SpringData JPA
Spring has a SpringData JPA module which could provide additional convenience comparing the classic combination of JPA and Hibernate.
This topic has been separated into several parts:
- Create Schema
- Data Entity (Java POJO)
- DAO (Data Access Object)
- Application Starter
- How to Use
- References
There are 2 ways to create a table in database which will map to a data entity class in Java:
Create a schema.sql file and add the CREATE TABLE
statement into this file to define table schema. And put it the classpath resources directory ("src/resources" for this project). When your application is starting, Spring will execute the SQL statements in the schema.sql file, which will create a new table or update the existing table based on the CREATE TABLE
statement.
Example of schema.sql
CREATE TABLE IF NOT EXISTS licenses (
license_id VARCHAR(100) PRIMARY KEY NOT NULL,
organization_id TEXT NOT NULL
-- omit more columns --
);
-- you can define more statements if needed --
Enable Hibernate ddl-auto option in the application configuration file (application.properties file or application.yml). When your application is starting, Spring will automatically create tables in database based on the data entity classes. You can also update a table (add a column or remove a column) by updating the corresponding entity class (add a field or remove a field).
Example of application.properties
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
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 */
}
To define a DAO, you just need to define an interface. The magic is you don't have to implement 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. SpringData JPA will automatically generate the proxy/concrete class, implement those functions and generate SQL query. (For the naming convention, see Supported keywords inside method names)
@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);
}
In the application starter class, you need to add 2 more annotations to let Spring know which package needs to be scanned.
-
@EntityScan
: Let Spring know which package contains all the data entity classes. -
@EnableJpaRepositories
: Let Spring know which package contains all the DAO interfaces.
@SpringBootApplication
@EntityScan(basePackages = {"com.thoughtmechanix.licenses.entity"})
@EnableJpaRepositories(basePackages = {"com.thoughtmechanix.licenses.repository"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
You can call the methods directly through your DAO interface with the @Autowired
annotation. Like:
@Service
public class LicenseService {
@Autowired
private LicenseRepository licenseRepository;
public List<License> getLicensesByOrg(String organizationId) {
return licenseRepository.findByOrganizationId(organizationId); // call customized query
}
public void updateLicense(License license){
licenseRepository.save(license); // call basic crud operations
}
/* omit other functions */
}
- Overview
- Getting Started
-
Technical Essentials
- Autowired
- SpringData JPA
- Configuration File Auto-loading
- Configuration Encryption
- Service Discovery with Eureka
- Resiliency Patterns with Hystrix
- Configure Hystrix
- Service Gateway with Zuul
- Zuul Filters
- Protect Service with Spring Security and OAuth2
- Use JWT as Access Token
- Store Clients and Users' Credentials to DB
- Integrate with Message Queue (Kafka)
- Integrate with Redis
- Tune Logging
- Log Aggregation
- Send Trace to Zipkin
- Build Runnable Jar
- Core Application Logic
- Components