Spring Boot ile Database Uygulaması Geliştirmek

Spring Boot, convention over configuration yaklaşımı ile, uygulama geliştirmeyi çok kolay bir hale getirdi. Normal bir spring uygulamasında bildiğiniz gibi karmaşık xml configürasyon dosyaları ile uğraşmak gerekiyordu. Spring Boot ise, bu yaklaşımın aksine, herşeyi ile hazır bir proje yapısı sunmaktadır. Spring Boot ile yeni bir proje oluşturduğunuzda, dependency Injection, JPA ve hibernate kütüphanelerini herhangi bir xml ayarı yapmaya gerek kalmadan kullanabilirsiniz.

Spring Boot’u daha iyi anlamak için ufak bir uygulama yapacağız. IDE olarak Intellij Idea kullanacağım. Sizler de aynı proje yapısını ister start.spring.io sitesinde projeyi oluşturup, oluşan dosyayı bilgisayarınıza indirerek ya da Spring Boot cli ile elde edebilirsiniz.

Bu uygulamamızda MySql veritabanını kullanacağız.

Bir Todo tablosu oluşturup onu listeleyen ve yeni kayıtlar ekleyebileceğimiz bir uygulama olacak.

Idea’yı açıp, File New Project diyelim.

springbootnewproj

Next butonuna tıkladıktan sonra gelen ekran:

springbootprojname

Build aracı olarak Maven’i seçiyorum. İlgili alanları doldurup tekrar next butonuna basıyorum.

springbootprojprop

Bu bir web projesi olacağı için web’i işaretliyorum. Spring’in default template engine Jsp bildiğiniz gibi, fakat bu uygulama için html 5 standartlarına uyumlu olan thymeleaf template engine’ı kullanacağım.

Sql kısmında da JPA (Java Persistence Api), MySQL ve H2 seçiyorum. Aslında H2’yi seçmeme gerek yok. Fakat daha sonra test kodlarında, in memory database olarak kullanmak istediğim için ekliyorum.

Tekrar Next butonuna tıkladığımızda son olarak proje adını default olarak bırakıp, finish butonuna tıklayalım. Projemiz oluşmuş oldu böylece.

Proje yapımız aşağıdaki şekilde oluştu:

springbootprojstructure

com.onbirkod paketinin içerisine iki yeni paket ekleyelim: models ve controllers.

models paketinin altına Todo sınıfımızı ekleyelim:

package com.onbirkod.models;

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

@Entity
@Table(name = "Todo")
public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotNull
    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Yine models paketinin altına TodoDao interface’ini ekleyelim, spring framework’un sağladığı CrudRepository interface’ını kullanıyorum. Spring Framework, yeni bir dal katmanı yazmama gerek kalmadan, veri sorgulama, kaydetme metodlarını bize hazır olarak sunuyor:

package com.onbirkod.models;

import org.springframework.data.repository.CrudRepository;

import javax.transaction.Transactional;

@Transactional
public interface TodoDao extends CrudRepository<Todo, Long> {
}

Modeli mümkün olduğunca basit tutuyorum. Id kolonu ve bir description alanından ibaret bir sınıf. Bu aşamadan sonra Controller sınıfımızı oluşturalım. controllers paketinin altına ekliyoruz:

package com.onbirkod.controllers;

import com.onbirkod.models.Todo;
import com.onbirkod.models.TodoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class TodoController {
    @Autowired
    private TodoDao todoDao;

    @RequestMapping("/")
    public String index(Model model, @ModelAttribute Todo todo) {

        todo = new Todo();

        List<Todo> todos = (List<Todo>) todoDao.findAll();

        model.addAttribute("todoList", todos);

        return "index";
    }

    @RequestMapping(value = "/indexpost", method = RequestMethod.POST)
    public String indexpost(Model model, @ModelAttribute Todo todo) {
        todoDao.save(todo);

        todo = new Todo();

        List<Todo> todos = (List<Todo>) todoDao.findAll();

        model.addAttribute("todoList", todos);

        return "redirect:/";
    }

}

Controller sınıfımızı oluşturduk. Son olarak da index.html dosyasını oluşturalım. Resources/templates paketinin altına ekleyelim:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Db app with Spring Boot</title>
</head>
<body>
<h3>Todo Versiyon 1.0.1</h3>
<div>
    <p>
        Kayıt ekleyebilirsiniz
    </p>
</div>
<hr/>
<div>
    <form action="#" th:action="@{/indexpost}" th:object="${todo}" method="post">
        <p>aktivite: <input type="text" th:field="*{description}" /></p>
        <p><input type="submit" value="Kaydet" /> <input type="reset" value="Reset" /></p>
    </form>
</div>
<hr/>
<div style="font-size: medium; font-weight: bold;">
    <ul>
        <li th:each="todo : ${todoList}"
            th:text="${todo.description}">Text</li>
    </ul>
</div>
</body>
</html>

Veritabanı bağlantı bilgilerimizi application.properties dosyasına girelim (Mysql url ve username/password değerlerini kendi veritabanınıza göre değiştirin):

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

# 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

Projemizin son haline bakalım:

springbootfinalstruct

Çalıştırıp, http://localhost:8080 adresine tarayıcımız ile bağlanalım:

springbootdemo

Sonuç

Spring Boot ile hazır gelen ayarlar sayesinde ve spring repository’sini kullanarak, web tabanlı bir veritabanı uygulamasını çok kısa bir sürede ve basitçe yapmış olduk. MySql editöründen baktığımızda tablomuzun otomatik olarak oluşturulduğunu görmüş oluruz. Gördüğünüz gibi, arka planda kullanılan hibernate kütüphanesi sayesinde herhangi bir sql cümlesi yazmamıza gerek kalmadı. Controller metodunda TodoDao tipinde bir objeye, Autowire özelliğini eklediğimiz için, dependency injection altyapısı objeyi otomatik olarak oluşturacaktır.

Güncelleme 23.10.2016

pom.xml dosyasını görmek isteyen arkadaşlar oldu:

<?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.onbirkod</groupId>
	<artifactId>springbootdbapp</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springbootdbapp</name>
	<description>Db Application with Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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


</project>

 

 

7 thoughts on “Spring Boot ile Database Uygulaması Geliştirmek”

  1. Geri bildirim: Vue.js (2) : Vue-resource Kullanarak Veri Çekmek - Yazılım Denemeleri

  2. “Apparently, to get version 5.1.33 of MySQL JDBC driver to work with UTC time zone, one has to specify the serverTimezone explicitly in the connection string.”

    hatasi veriyo yapılması gereken :
    application.properties sayfasındaki, spring.datasource.url degerini assagidaki gibi degiştirmek “db?” yazan yerdeki db yerine veritabani degerini yazmalisiniz

    spring.datasource.url=jdbc:mysql://localhost/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

Yorum bırakın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

Scroll to Top