Wednesday 21 December 2016

Spring Data JPA Using SpringBoot


If you are looking for how to integrate spring data jpa using spring boot, you are at right place.

This tutorial will guide you to create sample application which will use spring data jpa and spring boot.

Let's get started.

What you need :

1. Java 1.8
2. Maven
3. IntelliJ
4. MySQL

Note: You can use any other Java IDE like EClipse etc and skip the project creation steps below which is created specific for IntelliJ.

Step 1: Create project in IntelliJ






































Next Give Artifact Name






































Give Project name






































This will create maven project as shown below
































Step 2: Update pom.xml with below dependancies

xml version="1.0" encoding="UTF-8"?><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.example</groupId>
    <artifactId>spring-data</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


Step 3: Test mySQL connection

In IntelliJ goto
Views =>  Tool Windows => Database

Open MySql Datasource window and enter database connection details as shown
































Click Test Connection



Step 4: Create application.properties in resources folder which gives jpa connection details

# DataSource settings: set here your own configurations for the database
# connection. In this example we have "spring_db" as database name and
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3306/spring_db
spring.datasource.username = root
spring.datasource.password = root

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

#change port
server.port=8090
NOTE: 
1. Note that server.port= property is used for changing default tomcat 8080 port.
Using the hibernate configuration ddl-auto = update the database schema will be automatically created (and updated), creating tables and columns, accordingly to java entities found in the project.
See here for other hibernate specific configurations.
You project structure should look something like this


Note: Here Application.java class is at root of all sub-packages. It is because @SpringBootApplication annotation is equivalent to  @Configuration, @EnableAutoConfiguration and @ComponentScan with their default values. And @ComponentScan search component in current & sub packages.
If you have Application.java in different package structure, you have to provide your own custom annotation with proper package for @ComponentScan .

Step 5: Create Application.java with @SpringBootApplication annotation.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

//@Configuration
//@EnableAutoConfiguration
//@ComponentScan({"controller"})
@SpringBootApplication
@EnableJpaRepositories({"com.example.model"})
@EntityScan("com/example/model")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Note: Many Spring Boot developers (Spring) always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

Step 6: Create User Entity
package com.example.model;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@Entity@Table(name="Users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @NotNull
    private String name;
    @NotNull
    private String email;
    public User() {
    }
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public long getId() {
        return id;
    }
}





Step 7: Create User Dao
package com.example.model;
import org.springframework.data.repository.CrudRepository;
import javax.transaction.Transactional;
@Transactionalpublic interface UserDao extends CrudRepository {
    public User findByEmail(String email);
}
For More examples click here

Step 8: Create Controller
a. Create MainController
package com.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MainController { 
   @RequestMapping("/")
    public String index() {
        return "This application is created using spring data jpa and spring boot";
    }
}
b. Create UserController
package com.example.controller;
import com.example.model.User;
import com.example.model.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
    @Autowired 
       private UserDao userDao;
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @RequestMapping(value = "/create/{name}", method = RequestMethod.POST)
    public User create(@PathVariable("name") String name,@RequestParam(name="email") String email) {
        User user = null;
        try {
            user = new User(name,email);
            userDao.save(user);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return user;
    }

    /**     * GET /get-by-email  --> Return the user by email.     */ 
    @RequestMapping(value = "/get-by-email", method = RequestMethod.GET)
    public User getByEmail(@RequestParam(name="email") String email) {
        User user = null;
        try {
            user = userDao.findByEmail(email);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return user;
    }
}

Now Run your Application.java & test 
Get Any rest client plugin for browser 
Url for create : http://localhost:8090/create/John?email=john@gmail.com
(In above url, name is @PathVariable & email is @RequestParam)
Check record in database select your database Open mysql command prompt
You can also call GET endpoint to see result GET URL : http://localhost:8090/get-by-email?email=john@gmail.com
Now you have your running spring-data application 
Thanks for visiting... :)
Code for above application is present at https://github.com/aliqamer/springDataJpa