{{announcement.body}}
{{announcement.title}}

An Implementation of Spring Boot With Spring Data JPA

DZone 's Guide to

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.

· Java Zone ·
Free Resource

Get started building a Spring Boot application with Spring Data JPA.

This 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.

Java




x


1
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.

Java




xxxxxxxxxx
1
53


1
package com.company.xxapp.xx.config;
2
 
          
3
/**
4
 necessary imports
5
*/
6
 
          
7
@Configuration
8
@EnableTransactionManagement
9
@ComponentScan({"com.company.xxapp.xx.*"})
10
@EnableJpaRepositories(basePackages = {"com.company.xxapp.xx.*"},
11
        entityManagerFactoryRef = "domainEntityManager",
12
        transactionManagerRef = "domainTransactionManager")
13
public class DataSourceConfig{
14
 
          
15
    @Bean(name = "domainEntityManager")
16
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
17
        LocalContainerEntityManagerFactoryBean em  = new LocalContainerEntityManagerFactoryBean();
18
        em.setDataSource(dataSource());
19
        em.setPackagesToScan(new String[]{"com.company.xxapp.xx.domain"});
20
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
21
        em.setJpaVendorAdapter(vendorAdapter);
22
 
          
23
        Map<String, Object> properties = new HashMap();
24
 
          
25
        properties.put("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect");
26
        properties.put("hibernate.default_schema","XXX");
27
        properties.put("hibernate.proc.param_null_passing","true");
28
        em.setJpaPropertyMap(properties);
29
        return em;
30
    }
31
 
          
32
    @Bean
33
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
34
        return new PersistenceExceptionTranslationPostProcessor();
35
    }
36
 
          
37
    @Value("${spring.datasource.primary.jndi-name}")
38
    private String primaryJndiName;
39
 
          
40
    @Bean(name = "domainTransactionManager")
41
    public JpaTransactionManager getJpaTransactionManager() {
42
        return new JpaTransactionManager();
43
    }
44
 
          
45
 
          
46
    @Bean
47
    public DataSource dataSource() {
48
        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
49
        lookup.setResourceRef(true);
50
        return lookup.getDataSource(primaryJndiName);
51
    }
52
 
          
53
}



Let’s assume we have a customer table in our database.

Java




xxxxxxxxxx
1
15


1
SCHEMA.CUSTOMER
2
(
3
  NCUSTOMER_ID             NUMBER(20),
4
  VCUSTOMER_NAME           VARCHAR2(100 CHAR),
5
  VCUSTOMER_LNAME          VARCHAR2(50 CHAR),
6
  VCOMPANY_NAME            VARCHAR2(150 CHAR),
7
  NINDIVIDUAL_OR_COMPANY   NUMBER(1),
8
  DSUBSCRIPTION_DATE       DATE,
9
  VCREATED_BY              VARCHAR2(50 BYTE),
10
  VCREATED_MACHINE         VARCHAR2(50 BYTE),
11
  DCREATED_DATE            DATE,
12
  DMODIFIED_DATE           DATE,
13
  VMODIFIED_BY             VARCHAR2(50 BYTE),
14
  VMODIFIED_MACHINE        VARCHAR2(50 BYTE)
15
)



With its associated JPA Entity:

Java




xxxxxxxxxx
1
33


1
package com.company.xxapp.xx.domain;
2
 
          
3
import lombok.Getter;
4
import lombok.Setter;
5
 
          
6
import javax.persistence.*;
7
import java.io.Serializable;
8
import java.math.BigDecimal;
9
import java.util.Date;
10
 
          
11
 
          
12
@Getter
13
@Setter
14
@Entity
15
@Table(name="CUSTOMER",schema = "SCHEMA")
16
public class Customer extends BaseEntity implements Serializable {
17
 
          
18
    @Id
19
    @Column(name = "NCUSTOMER_ID")
20
    private Long customerId;
21
    @Column(name = "VCUSTOMER_NAME")
22
    private String customerName;
23
    @Column(name = "VCUSTOMER_LNAME")
24
    private String customerLname;
25
    @Column(name = "VCOMPANY_NAME")
26
    private String companyName;
27
    @Column(name = "NINDIVIDUAL_OR_COMPANY")
28
    private int indOrComp;
29
    @Column(name = "DSUBSCRIPTION_DATE")
30
    private Date subscriptionDate;
31
 
          
32
}
33
 
          



Java




xxxxxxxxxx
1
28


1
package com.company.xxapp.xx.domain;
2
 
          
3
import lombok.Getter;
4
import lombok.Setter;
5
 
          
6
import javax.persistence.Column;
7
import javax.persistence.MappedSuperclass;
8
import java.util.Date;
9
 
          
10
 
          
11
@Getter
12
@Setter
13
@MappedSuperclass
14
public abstract class BaseEntity {
15
 
          
16
        @Column(name = "VCREATED_BY")
17
        protected String createdBy;
18
        @Column(name = "DCREATED_DATE")
19
        protected Date createdDate;
20
        @Column(name = "VCREATED_MACHINE")
21
        protected String createdMachine;
22
        @Column(name = "VMODIFIED_BY")
23
        protected String modifiedBy;
24
        @Column(name = "DMODIFIED_DATE")
25
        protected Date modifiedDate;
26
        @Column(name = "VMODIFIED_MACHINE")
27
        protected String modifiedMachine;
28
 
          



Our query would be like below if we want to get 1000 corporate customers that subscribed on a given date.

SQL




xxxxxxxxxx
1


 
1
SELECT NCUSTOMER_ID,  VCUSTOMER_NAME, VCUSTOMER_LNAME,
2
       VCOMPANY_NAME, NINDIVIDUAL_OR_COMPANY, DSUBSCRIPTION_DATE
3
  FROM SCHEMA.CUSTOMER CUST
4
 WHERE     DSUBSCRIPTION_DATE >= :paramDate
5
       AND NINDIVIDUAL_OR_COMPANY = :paramIndOrComp
6
       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.

Java




xxxxxxxxxx
1
12


 
1
package com.company.xxapp.xx.repository;
2
 
          
3
/**
4
 necessary imports
5
*/
6
 
          
7
public interface ICustomerRepository extends CrudRepository<Customer,String> {
8
 
          
9
   List<Customer> findTop1000BySubscriptionDateGreaterThanEqualAndIndOrComp (Date subsDate, int indOrComp);
10
 
          
11
}
12
 
          



 Now, we able to list our records like this.

Java




xxxxxxxxxx
1
28


 
1
package com.company.xxapp.xx.service;
2
 
          
3
/**
4
 necessary imports
5
*/
6
 
          
7
@Slf4j
8
@Service
9
public class CustomerService implements ICustomerService {
10
 
          
11
 
          
12
    @Autowired
13
    private ICustomerRepository customerRepository;
14
 
          
15
 
          
16
    @Override
17
    public void getCustomers() {
18
 
          
19
        try {
20
               List<Customer> poolList = customerRepository. findTop1000BySubscriptionDateGreaterThanEqualAndIndOrComp( GeneralUtils.getDateWithoutTime( new Date(), 0 ), CustomerEnum.CORPORATE.getType());
21
 
          
22
        } catch (Exception ex) {
23
            log.error( "CustomerService exception occured {}", ExceptionUtils.getStackTrace(ex));
24
        }
25
 
          
26
    }
27
 
          
28
  }



Also, we will be able to implement general CRUD operations like below without extra effort.

Java




xxxxxxxxxx
1


 
1
package com.turkcelltech.company.xxapp.repository;
2
 
          
3
/**
4
 necessary imports
5
*/
6
 
          
7
public interface ICustomerRepository extends CrudRepository<Customer,String> {
8
}



I also try to sample a native query call and also how to call a stored procedure with Spring Data below.

Java




xxxxxxxxxx
1
20


 
1
package com.turkcelltech.trace.collector.repository;
2
 
          
3
/**
4
 necessary imports
5
*/
6
 
          
7
import org.springframework.data.jpa.repository.Query;
8
import org.springframework.data.repository.CrudRepository;
9
 
          
10
public interface ICustomerLiteRepository extends CrudRepository<Customer,Long> {
11
 
          
12
    @Query(value = "SELECT NCUSTOMER_ID,  VCUSTOMER_NAME, VCUSTOMER_LNAME," +
13
        "       VCOMPANY_NAME, NINDIVIDUAL_OR_COMPANY, DSUBSCRIPTION_DATE" +
14
        "  FROM SCHEMA.CUSTOMER CUST" +
15
        " WHERE     DSUBSCRIPTION_DATE >= :paramDate" +
16
        "       AND NINDIVIDUAL_OR_COMPANY = :paramIndOrComp" +
17
        "       AND ROWNUM < 1000", nativeQuery =  true)
18
List<Customer> getCustomers(Date subsDate, int indOrComp);
19
 
          
20
}



 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.

Java




xxxxxxxxxx
1
19


 
1
package com.compmany.xxapp.xx.repository;
2
 
          
3
/**
4
 necessary imports
5
*/
6
 
          
7
import org.springframework.data.jpa.repository.query.Procedure;
8
import org.springframework.data.repository.CrudRepository;
9
import org.springframework.data.repository.query.Param;
10
 
          
11
import java.math.BigDecimal;
12
import java.sql.Date;
13
 
          
14
public interface ICustomerTypeRepository extends CrudRepository<CustomerTypeProc,Long> {
15
 
          
16
    @Procedure(name  = "isIndOrComp")
17
    int inProvision(@Param("p_customer_id") Long customerId,
18
                    @Param("p_customer_type") Integer customerType);
19
}



I hope everything goes well, thanks a lot...

Further Reading

Using the Spring Data JPA

Spring Boot With Spring Data JPA

Topics:
crud, java, spring boot, spring data jpa, sql, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}