Skip to content

Commit

Permalink
Jdbc template
Browse files Browse the repository at this point in the history
  • Loading branch information
FelipeRodrigues21 committed Jul 31, 2019
1 parent c89b56e commit ed93ee3
Show file tree
Hide file tree
Showing 19 changed files with 132 additions and 6 deletions.
30 changes: 26 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import org.flywaydb.gradle.task.FlywayMigrateTask

buildscript {
ext {
springBootVersion = "2.0.6.RELEASE"
Expand All @@ -15,6 +17,7 @@ buildscript {

plugins {
id "java"
id "org.flywaydb.flyway" version "5.2.4"
}

apply plugin: 'org.springframework.boot'
Expand All @@ -23,16 +26,35 @@ repositories {
mavenCentral()
}

dependencies {
compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
compile("org.springframework.boot:spring-boot-starter-jdbc:$springBootVersion")

compile("mysql:mysql-connector-java:6.0.6")

testCompile("org.springframework.boot:spring-boot-starter-test:$springBootVersion")
testCompile("org.mockito:mockito-core:2.23.4")
}

def developmentDbUrl = "jdbc:mysql://localhost:3306/tracker_dev?user=tracker&useSSL=false&useTimezone=true&serverTimezone=UTC&useLegacyDatetimeCode=false"
bootRun.environment([
"WELCOME_MESSAGE": "hello",
"SPRING_DATASOURCE_URL": developmentDbUrl,
])

def testDbUrl = "jdbc:mysql://localhost:3306/tracker_test?user=tracker&useSSL=false&useTimezone=true&serverTimezone=UTC&useLegacyDatetimeCode=false"
test.environment([
"WELCOME_MESSAGE": "Hello from test",
"SPRING_DATASOURCE_URL": testDbUrl,
])

dependencies {
compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
testCompile("org.springframework.boot:spring-boot-starter-test:$springBootVersion")
testCompile("org.mockito:mockito-core:2.23.4")
flyway {
url = developmentDbUrl
user = "tracker"
password = ""
locations = ["filesystem:databases/tracker/migrations"]
}

task testMigrate(type: FlywayMigrateTask) {
url = testDbUrl
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
86 changes: 86 additions & 0 deletions src/main/java/io/pivotal/pal/tracker/JdbcTimeEntryRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package io.pivotal.pal.tracker;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import javax.sql.DataSource;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

public class JdbcTimeEntryRepository implements TimeEntryRepository {

JdbcTemplate jdbcTemplate;

public JdbcTimeEntryRepository(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

@Override
public TimeEntry create(TimeEntry any) {
KeyHolder generatedKeyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(connection -> {
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO time_entries (project_id, user_id, date, hours) " +
"VALUES (?, ?, ?, ?)",
Statement.RETURN_GENERATED_KEYS

);

statement.setLong(1, any.getProjectId());
statement.setLong(2, any.getUserId());
statement.setDate(3, Date.valueOf(any.getDate()));
statement.setInt(4, any.getHours());

return statement;
}, generatedKeyHolder);

return find(generatedKeyHolder.getKey().longValue());
}

@Override
public TimeEntry find(long timeEntryId) {
return jdbcTemplate.query("select id, project_id, user_id, date, hours from time_entries where id=?", new Object[]{timeEntryId},
extractor);
}

@Override
public List<TimeEntry> list() {
return jdbcTemplate.query("SELECT id, project_id, user_id, date, hours FROM time_entries", mapper);
}

@Override
public TimeEntry update(long eq, TimeEntry timeEntry) {
jdbcTemplate.update("update time_entries set project_id = ?, user_id = ?, date = ?, hours = ? where id = ?",
timeEntry.getProjectId(),
timeEntry.getUserId(),
Date.valueOf(timeEntry.getDate()),
timeEntry.getHours(),
eq);

return find(eq);
}

@Override
public void delete(long timeEntryId) {
jdbcTemplate.update("delete from time_entries where id=?", timeEntryId);

}

private final RowMapper<TimeEntry> mapper = (rs, rowNum) -> new TimeEntry(
rs.getLong("id"),
rs.getLong("project_id"),
rs.getLong("user_id"),
rs.getDate("date").toLocalDate(),
rs.getInt("hours")
);

private final ResultSetExtractor<TimeEntry> extractor =
(rs) -> rs.next() ? mapper.mapRow(rs, 1) : null;

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@SpringBootApplication
public class PalTrackerApplication {
Expand All @@ -12,8 +15,8 @@ public static void main(String[] args) {
}

@Bean
public TimeEntryRepository timeEntryRepository(){
return new InMemoryTimeEntryRepository();
public TimeEntryRepository timeEntryRepository(DataSource dataSource){
return new JdbcTimeEntryRepository(dataSource);
}

}
15 changes: 15 additions & 0 deletions src/test/java/test/pivotal/pal/trackerapi/TimeEntryApiTest.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package test.pivotal.pal.trackerapi;

import com.jayway.jsonpath.DocumentContext;
import com.mysql.cj.jdbc.MysqlDataSource;
import io.pivotal.pal.tracker.PalTrackerApplication;
import io.pivotal.pal.tracker.TimeEntry;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -12,10 +14,12 @@
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDate;
import java.util.Collection;
import java.util.TimeZone;

import static com.jayway.jsonpath.JsonPath.parse;
import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -32,6 +36,17 @@ public class TimeEntryApiTest {
private final long userId = 456L;
private TimeEntry timeEntry = new TimeEntry(projectId, userId, LocalDate.parse("2017-01-08"), 8);

@Before
public void setUp() throws Exception {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUrl(System.getenv("SPRING_DATASOURCE_URL"));

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("TRUNCATE time_entries");

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}

@Test
public void testCreate() throws Exception {
ResponseEntity<String> createResponse = restTemplate.postForEntity("/time-entries", timeEntry, String.class);
Expand Down

0 comments on commit ed93ee3

Please sign in to comment.