JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Spring Data JPA with Spring Boot Applications - MySql example - example


This page gives an example to configure Spring Boot application with Spring Data JPA along with MySql Database.

Include below dependencies in your pom.xml file:

1) spring-boot-starter-data-jpa

2) MySQL Driver

3) HikariCP 2.6 (to maintain connection pool)

Here is the example pom.xml for your reference:

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.java2novice.springboot</groupId>
	<artifactId>spring-boot-tutorials</artifactId>
	<packaging>jar</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
	    <!-- include Spring data JPA dependencies, exclude default tomcat pool-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- MySql JDBC driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>

        <!-- HikariCP connection pool -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.0</version>
        </dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- Package as an executable jar/war -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Entity Class - Employee

Employee Class
package com.java2novice.springboot.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

@Entity
public class Employee {

	@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
    @SequenceGenerator(sequenceName = "emp_seq", allocationSize = 1, name = "emp_seq")
	@Column(name = "emp_id")
    private Long empId;

	private String name;

	private Integer age;

	private Integer salary;

	public Long getEmpId() {
		return empId;
	}

	public void setEmpId(Long empId) {
		this.empId = empId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Integer getSalary() {
		return salary;
	}

	public void setSalary(Integer salary) {
		this.salary = salary;
	}
}

You can have your DB datasource related configurations at application.properties file as shown below:

application.properties
# Oracle DB Settings
spring.datasource.url=jdbc:mysql://localhost/emp_db?useSSL=false
spring.datasource.username=my_prod_user
spring.datasource.password=my_db_password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# HikariCP settings

spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.maximum-pool-size=50

Create Spring Data CrudRepository:

EmployeeDao
package com.java2novice.springboot.dao;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.java2novice.springboot.models.Employee;

public interface EmployeeDao extends CrudRepository<Employee, Long>{

	List<Employee> findByName(String name);
}

Spring Boot Starter

SpringBootWebApplication
package com.java2novice.springboot;

import javax.sql.DataSource;
import org.springframework.transaction.annotation.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.java2novice.springboot.dao.EmployeeDao;

@SpringBootApplication
public class SpringBootWebApplication implements CommandLineRunner{

	private static Logger logger = LoggerFactory.getLogger(SpringBootWebApplication.class);

	@Autowired
    private DataSource dataSource;

	@Autowired
	private EmployeeDao employeeDao;

	public static void main(String[] args) throws Exception {

		SpringApplication.run(SpringBootWebApplication.class, args);
	}

	@Transactional(readOnly = true)
    @Override
    public void run(String... args) throws Exception {

		System.out.println(employeeDao.findByName("Java2Novice").size());
	}
}
<< Previous Program | Next Program >>

Spring-Boot Examples

  1. Spring-Boot initial setup.
  2. Spring-Boot hello world example
  3. What is spring-boot-starter-parent in Spring-Boot pom.xml file?
  4. What is @SpringBootApplication annotation in spring boot?
  5. What is application.properties in spring boot?
  6. What is @ConfigurationProperties annotation in spring boot?
  7. Spring Boot @ConfigurationProperties example
  8. Spring Boot @ConfigurationProperties Property Validation
  9. Difference between @ConfigurationProperties and @Value
  10. Spring boot web application configurations.
  11. How to run spring boot application through command line?
  12. How to run spring boot as a standalone application (non-web)?
  13. Spring boot property resolution order.
  14. Spring Boot – Profile based properties example.
  15. How to configure logback (SLF4J) logging to spring boot applications?
  16. How to update application context path in spring boot?
  17. How to disable spring logo banner in spring boot?
  18. Spring Data JPA with Spring Boot Applications - Oracle - example
  19. Spring Data JPA with Spring Boot Applications - MySql example
  20. How to configure Spring Boot to show Hibernate SQL Query in logs?
  21. Spring Boot – List all Beans loaded in the ApplicationContext
  22. How to load external property files into Spring Boot application?
  23. How to rename application.properties file in Spring Boot application?
  24. How to configure multiple DataSources (Databases) with Spring Boot and Spring Data?
Knowledge Centre
Java class can be private?
We can not declare top level class as private. Java allows only public and default modifier for top level classes in java. Inner classes can be private.
Famous Quotations
Be yourself; everyone else is already taken.
-- Oscar Wilde

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2017 by Nataraja Gootooru. All Rights Reserved.