An Implementation of Spring Boot With Spring Data JPA
Check out this tutorial on how to get started building a Spring Boot application with Spring Data JPA.
Join the DZone community and get the full member experience.
Join For FreeThis guide includes my interest in how you can handle complex CRUD operations such a simple way with Spring Data JPA and using native queries in case of needs.
In this tutorial, I am using the Oracle database along with Spring Data. Besides, it will be helpful if you have a server dependency for Weblogic.
You may also like: Using the Spring Data JPA
First, we should define our JNDI name in our Spring Boot Project’s application.properties file. We must pay attention to the JNDI name we define in our properties file. It must be the same within our Weblogic’s DataSources JNDI Name.
spring.datasource.primary.jndi-name=TEST-JNDI
Then, in our DataSourceConfig
class, we have some configurations about our JNDI and we define which classes to scan under our project's package as domain objects.
xxxxxxxxxx
package com.company.xxapp.xx.config;
/**
necessary imports
*/
"com.company.xxapp.xx.*"}) ({
basePackages = {"com.company.xxapp.xx.*"}, (
entityManagerFactoryRef = "domainEntityManager",
transactionManagerRef = "domainTransactionManager")
public class DataSourceConfig{
name = "domainEntityManager") (
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{"com.company.xxapp.xx.domain"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = new HashMap();
properties.put("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect");
properties.put("hibernate.default_schema","XXX");
properties.put("hibernate.proc.param_null_passing","true");
em.setJpaPropertyMap(properties);
return em;
}
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
"${spring.datasource.primary.jndi-name}") (
private String primaryJndiName;
name = "domainTransactionManager") (
public JpaTransactionManager getJpaTransactionManager() {
return new JpaTransactionManager();
}
public DataSource dataSource() {
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
lookup.setResourceRef(true);
return lookup.getDataSource(primaryJndiName);
}
}
Let’s assume we have a customer table in our database.
xxxxxxxxxx
SCHEMA.CUSTOMER
(
NCUSTOMER_ID NUMBER(20),
VCUSTOMER_NAME VARCHAR2(100 CHAR),
VCUSTOMER_LNAME VARCHAR2(50 CHAR),
VCOMPANY_NAME VARCHAR2(150 CHAR),
NINDIVIDUAL_OR_COMPANY NUMBER(1),
DSUBSCRIPTION_DATE DATE,
VCREATED_BY VARCHAR2(50 BYTE),
VCREATED_MACHINE VARCHAR2(50 BYTE),
DCREATED_DATE DATE,
DMODIFIED_DATE DATE,
VMODIFIED_BY VARCHAR2(50 BYTE),
VMODIFIED_MACHINE VARCHAR2(50 BYTE)
)
With its associated JPA Entity:
xxxxxxxxxx
package com.company.xxapp.xx.domain;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
name="CUSTOMER",schema = "SCHEMA") (
public class Customer extends BaseEntity implements Serializable {
name = "NCUSTOMER_ID") (
private Long customerId;
name = "VCUSTOMER_NAME") (
private String customerName;
name = "VCUSTOMER_LNAME") (
private String customerLname;
name = "VCOMPANY_NAME") (
private String companyName;
name = "NINDIVIDUAL_OR_COMPANY") (
private int indOrComp;
name = "DSUBSCRIPTION_DATE") (
private Date subscriptionDate;
}
xxxxxxxxxx
package com.company.xxapp.xx.domain;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.util.Date;
public abstract class BaseEntity {
name = "VCREATED_BY") (
protected String createdBy;
name = "DCREATED_DATE") (
protected Date createdDate;
name = "VCREATED_MACHINE") (
protected String createdMachine;
name = "VMODIFIED_BY") (
protected String modifiedBy;
name = "DMODIFIED_DATE") (
protected Date modifiedDate;
name = "VMODIFIED_MACHINE") (
protected String modifiedMachine;
Our query would be like below if we want to get 1000 corporate customers that subscribed on a given date.
xxxxxxxxxx
SELECT NCUSTOMER_ID, VCUSTOMER_NAME, VCUSTOMER_LNAME,
VCOMPANY_NAME, NINDIVIDUAL_OR_COMPANY, DSUBSCRIPTION_DATE
FROM SCHEMA.CUSTOMER CUST
WHERE DSUBSCRIPTION_DATE >= :paramDate
AND NINDIVIDUAL_OR_COMPANY = :paramIndOrComp
AND ROWNUM < 1000
We can query our records with that SQL but we can also query like below in a simpler way and our codebase will be consistent with our Repository
class.
xxxxxxxxxx
package com.company.xxapp.xx.repository;
/**
necessary imports
*/
public interface ICustomerRepository extends CrudRepository<Customer,String> {
List<Customer> findTop1000BySubscriptionDateGreaterThanEqualAndIndOrComp (Date subsDate, int indOrComp);
}
Now, we able to list our records like this.
xxxxxxxxxx
package com.company.xxapp.xx.service;
/**
necessary imports
*/
public class CustomerService implements ICustomerService {
private ICustomerRepository customerRepository;
public void getCustomers() {
try {
List<Customer> poolList = customerRepository. findTop1000BySubscriptionDateGreaterThanEqualAndIndOrComp( GeneralUtils.getDateWithoutTime( new Date(), 0 ), CustomerEnum.CORPORATE.getType());
} catch (Exception ex) {
log.error( "CustomerService exception occured {}", ExceptionUtils.getStackTrace(ex));
}
}
}
Also, we will be able to implement general CRUD operations like below without extra effort.
xxxxxxxxxx
package com.turkcelltech.company.xxapp.repository;
/**
necessary imports
*/
public interface ICustomerRepository extends CrudRepository<Customer,String> {
}
I also try to sample a native query call and also how to call a stored procedure with Spring Data below.
xxxxxxxxxx
package com.turkcelltech.trace.collector.repository;
/**
necessary imports
*/
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface ICustomerLiteRepository extends CrudRepository<Customer,Long> {
value = "SELECT NCUSTOMER_ID, VCUSTOMER_NAME, VCUSTOMER_LNAME," + (
" VCOMPANY_NAME, NINDIVIDUAL_OR_COMPANY, DSUBSCRIPTION_DATE" +
" FROM SCHEMA.CUSTOMER CUST" +
" WHERE DSUBSCRIPTION_DATE >= :paramDate" +
" AND NINDIVIDUAL_OR_COMPANY = :paramIndOrComp" +
" AND ROWNUM < 1000", nativeQuery = true)
List<Customer> getCustomers(Date subsDate, int indOrComp);
}
If you need to call Stored Procedure
it is also similar to querying a table. We create our Entity
like a database table and Repository
class to call it.
xxxxxxxxxx
package com.compmany.xxapp.xx.repository;
/**
necessary imports
*/
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigDecimal;
import java.sql.Date;
public interface ICustomerTypeRepository extends CrudRepository<CustomerTypeProc,Long> {
name = "isIndOrComp") (
int inProvision( ("p_customer_id") Long customerId,
"p_customer_type") Integer customerType); (
}
I hope everything goes well, thanks a lot...
Further Reading
Opinions expressed by DZone contributors are their own.
Comments