Spring boot and MySql gossips!

In this post I will try to show how spring boot makes it so simple to integrate with a database server.

  1. Let’s get started. Jump to Spring Initialize (http://start.spring.io/) to generate our project.
  2. Add few dependencies which will be required to build our application. Dependencies includes Web for REST, MySQL for JDBC Driver and JPA for persistence. And generate project.
  3. Once you have the downloaded project in your system, open your favorite IDE and import the project. And resolve all dependencies we included. Once dependencies are resolved we are good to code our requirement.
  4. First we need a model which will act as an Entity for us and help use saving data in our Database.
    package com.javatab.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import java.io.Serializable;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    @Entity //Tells it's the entity which will be stored in DB
    public class User implements Serializable{
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id; // Column: ID, primary generated by JPA
        private String name; // Column: Name
    
        public User() {
        }
    
        public User(String name) {
            this.name = name;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
  5. We will create a repository by extending JpaRepository which is provide by spring data module. It will give some very simple yet powerful sql query implementation out of the box. You needn’t to write. Please refer documentation here
    package com.javatab.repository;
    
    import com.javatab.model.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    }
  6. Let’s go ahead and save our data in database called user. Before that make sure you have mySql database server installed. To do that we will CommandLineRunner which is interface provided by Spring boot which will run as soon as application starts.
    package com.javatab;
    
    import com.javatab.model.User;
    import com.javatab.repository.UserRepository;
    import org.apache.tomcat.util.http.fileupload.util.Streams;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.Arrays;
    import java.util.stream.Stream;
    
    @SpringBootApplication
    public class SpringBootMysqlApplication implements CommandLineRunner{
    
       @Autowired
       private UserRepository repository;
    
       public static void main(String[] args) {
          SpringApplication.run(SpringBootMysqlApplication.class, args);
       }
    
       @Override
       public void run(String... args) throws Exception {
    
          Stream.of("Dyser", "Josh", "Phil")
                .forEach(user -> repository.save(new User(user)));
    
          repository.findAll().forEach(System.out::println);
       }
    }
  7. Last we will make our datasource configuration. What to do? Shall we create JavaConfig or XML configuration. Wait!!! Spring boot does that for us, No? Yes !!!! Spring boot does it for us and we just need to make pass some properties to our application.yml or application.properties in resource directory in classpath.spring-boot-mysql - [~-Project-spring-boot-tutorials-spring-boot-mysql] - [spring-boot-mysql_main] - ~-Project-spring-boot-tutorials-spring-boot-mysql-src-main-resources-application.yml - IntelliJ IDEA 2016.1_025
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/user
        username: root
        password: root
      jpa:
        hibernate:
          ddl-auto: create
  8. Or if you are using application.properties we can make same configure this way
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/todo
    spring.datasource.username=root
    spring.datasource.password=root
    spring.jpa.hibernate.ddl-auto=update

Lets run our application. Open terminal, go to project directory and run ./gradlew clean runBootSelection_023Yeah we have got our data in console.

Source Code on GitHub

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s