20 November, 2013

Spring-boot JDBC sample

Simple Web+JDBC application.

With spring-boot you just do your business. Without overhead, without extra manipulations and configurations.
In example below:
  • UserRepository provides information about users from database via JdbcTemplate, plain SQL-queries and RowMapper.
  • UserController makes them accessible via HTTP.
In this example spring-boot automatically configures DataSource and JdbcTemplate according to application.properties file.

Sample urls:
  • http://localhost:8080/user/test
  • http://localhost:8080/user/user?id=2
  • http://localhost:8080/user/users?ids=1,3,5,7

Sources are minimalistic:
Application.java
package sb; 
 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
 
@EnableAutoConfiguration 
@Configuration 
@ComponentScan 
public class Application { 
 
    public static void main(String[] args) throws Throwable { 
        SpringApplication app = new SpringApplication(Application.class); 
        app.setShowBanner(false); 
        app.run(args); 
    } 
} 
User.java
package sb;

public class User {
    public long id;
    public String name;
    public String alias;

    public User(long id, String name) {
        this.id = id;
        this.name = name;
    }
} 
UserController.java
package sb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserRepository users;

    @RequestMapping("test")
    public String test() {
        log.info("Test");
        return "OK";
    }

    @RequestMapping("user")
    public User getUser(@RequestParam("id") long id) {
        log.info("Get user");
        return users.getUser(id);
    }

    @RequestMapping("users")
    public List<User> getUsers(@RequestParam("ids") long[] ids) {
        log.info("Get users");
        return users.getUsers(ids);
    }
} 
UserRepository.java
package sb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserRepository {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    protected JdbcTemplate jdbc;

    public User getUser(long id) {
        return jdbc.queryForObject("SELECT * FROM sb_user WHERE id=?", userMapper, id);
    }

    public List<User> getUsers(long[] ids) {
        String inIds = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(ids));
        return jdbc.query("SELECT * FROM sb_user WHERE id IN (" + inIds + ")", userMapper);
    }

    private static final RowMapper<User> userMapper = new RowMapper<User>() {
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User(rs.getLong("id"), rs.getString("name"));
            user.alias = rs.getString("alias");
            return user;
        }
    };

} 
application.properties
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://srv0/test
spring.datasource.username=test
spring.datasource.password=test 
build.gradle
buildscript { 
    repositories { 
        maven { url "http://repo.spring.io/libs-snapshot" } 
    } 
    dependencies { 
        classpath("org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M6") 
    } 
} 
 
apply plugin: "java" 
apply plugin: "spring-boot" 
 
buildDir = "out" 
 
jar { 
    baseName = "sb-jdbc" 
    version = "0.1" 
} 
 
repositories { 
    mavenCentral() 
    maven { url "http://repo.spring.io/libs-snapshot" } 
} 
 
dependencies { 
    def springBootVersion = '0.5.0.M6' 
 
    compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion") 
    compile("org.springframework.boot:spring-boot-starter-jdbc:$springBootVersion") 
 
    compile("org.postgresql:postgresql:9.2-1003-jdbc4") 
} 

3 comments:

Raizal I.N. Pregnanta said...

Your example is really simple
Thanks for it
The JPA and Hibernate things make my head overheated for my need-to-be-done-fast Final Project

Unknown said...

Thankyou!

Unknown said...

This was super simple and super helpful. Much appreciated!