Merhabalar hassas ruhlar ve diğerleri 🙂
Bu yazıda Spring Boot ile basit Crud işlemleri nasıl yapılır onu anlatmaya çalışacağım.
Örnek projenin kodlarına https://github.com/zeynepsit/spring-boot-thymeleaf-uygulama adresinden ulaşabilirsiniz.
Proje oluşturmak için http://start.spring.io adresini ziyaret edebilirsiniz.
Gerekli bilgileri girdikten sonra Generate Project diyerek projemizi indirelim.
Dosyamızın yapısını aşağıdaki gibi ayarlayalım
application.properties ayarlarını aşağıdaki gibi yapılandıralım.
spring.datasource.url = jdbc:mysql://localhost:3306/persons?useSSL=false spring.datasource.username = root spring.datasource.password = server.port = 8080 spring.jpa.show-sql = true spring.jpa.hibernate.ddl-auto = update spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
1)Maven dependencies
Projede kullanacağımız kütüphanelerin dependencylerini pom.xml dosyamıza eklemeliyiz.Ben extra Bootstrap ve jquery dependencylarını da ekledim.
<?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>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.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>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.0.0-alpha</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.1.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2. Model Class
Dilerseniz veritabanını oluşturduktan sonra model katmanını geliştirelim.
package com.persons.model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "person_information", catalog = "persons") @SuppressWarnings("serial") public class PersonInformation implements Serializable { private Integer id; private String name; private String age; private String hobby; @Basic @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Basic @Column(name = "NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column(name = "AGE") public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Basic @Column(name = "HOBBY") public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } }
@Entity anotasyonu ile veri tabanındaki tablolar temsil edilir.
@GeneratedValue ile ise primary key olan id nin otomatik olmasını sağlıyoruz.
3. Dao
Model sınıfını oluşturduktan sonra dilerseniz dao içerisine yeni bir interface oluşturalım.
Bu katmandaki metodlar temel CRUD işlemlerini yapan metodlarımız olucaktır.
package com.persons.dao; import java.util.List; import com.persons.model.PersonInformation; public interface PersonInformationDao { PersonInformation getPerson(Integer id); void save(PersonInformation person); List<PersonInformation> getPersonInformationList(); void updatePerson(PersonInformation person); void deletePerson(PersonInformation person); }
Şimdi bu sınıfın implemente edildiği PersonInformationDaoImpl sınıfını oluşturalım.
package com.persons.dao; import com.persons.model.PersonInformation; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class PersonInformationDaoImpl implements PersonInformationDao { @Autowired private EntityManager entityManager; private Session getSession() { return entityManager.unwrap(Session.class); } @Override public void save(PersonInformation person) { getSession().save(person); } @SuppressWarnings("unchecked") @Override public List<PersonInformation> getPersonInformationList() { return getSession().createCriteria(PersonInformation.class).list(); } @Override public PersonInformation getPerson(Integer id) { PersonInformation PersonInformation = (PersonInformation)getSession().get(PersonInformation.class, id); return PersonInformation; } @Override public void updatePerson(PersonInformation person) { getSession().update(person); } @Override public void deletePerson(PersonInformation person) { getSession().delete(person); } }
4. Service
Service dizini altına interface ve classımızı oluşturalım.
package com.persons.service; import java.util.List; import com.persons.model.PersonInformation; public interface PersonInformationService { PersonInformation getPerson(Integer id); public void save(PersonInformation person); List<PersonInformation> getPersonInformationList(); void updatePerson(PersonInformation person); void deletePerson(PersonInformation person); }
package com.persons.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.persons.dao.PersonInformationDao; import com.persons.model.PersonInformation; @Service @Transactional public class PersonInformationServiceImpl implements PersonInformationService { @Autowired private PersonInformationDao personsDao; @Override public void save(PersonInformation person) { personsDao.save(person); } @Override public List<PersonInformation> getPersonInformationList() { return personsDao.getPersonInformationList(); } @Override public PersonInformation getPerson(Integer id) { return personsDao.getPerson(id); } @Override public void updatePerson(PersonInformation person) { personsDao.updatePerson(person); } @Override public void deletePerson(PersonInformation person) { personsDao.deletePerson(person); } }
5. Controller
Şimdi de controllerımızı oluşturalım.
package com.persons.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.persons.model.PersonInformation; import com.persons.service.PersonInformationService; @Controller public class PersonsController { @Autowired private PersonInformationService personInformationService; @RequestMapping(value = "/index", method = RequestMethod.GET) public String inde(Model model) { List<PersonInformation> personInformation = personInformationService.getPersonInformationList( ); model.addAttribute("personInformation", personInformation); return "index"; } @RequestMapping(value="/edit/{id}", method=RequestMethod.GET) public String editTeamPage(Model model,@PathVariable("id") Integer id) { PersonInformation persons = personInformationService.getPerson(id); model.addAttribute("persons", persons); return "edit"; } @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST) public String edditingMusteri(@PathVariable int id, PersonInformation prs) { PersonInformation persons = personInformationService.getPerson(id); persons.setName(prs.getName()); persons.setAge(prs.getAge()); persons.setHobby(prs.getHobby()); personInformationService.updatePerson(persons); return "redirect:/index/"; } @RequestMapping(value = "/personDelete/{id}", method = RequestMethod.GET) public String deleteAjandaNotlar(@PathVariable("id") Integer id) { PersonInformation persons=personInformationService.getPerson(id); personInformationService.deletePerson(persons); return "redirect:/index/"; } @RequestMapping(value = "/add", method = RequestMethod.GET) public String indet(Model model) { model.addAttribute("personInformation", new PersonInformation()); return "add"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addMusteriNot(HttpServletRequest request, @ModelAttribute("PersonInformation") PersonInformation newPerson, BindingResult result) { PersonInformation persons = new PersonInformation(); persons.setId(newPerson.getId()); persons.setName(newPerson.getName()); persons.setAge(newPerson.getAge()); persons.setHobby(newPerson.getHobby()); personInformationService.save(persons); return "redirect:/index"; } }
Controller sınıfımızı @Controller anatasyonu olarak belirtelim.
Method attiributenin aldığı değerler;
- RequestMethod.GET : GET ile sunucuya istekte bulunup ilgili sayfaya ulaşırız
- RequestMethod.POST : POST ile istek yollayıp ilgili veritabanı işlemlerini gerçeklerştirdik.
6.View
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}" /> <body> <div class="container"> <div class="card"> <div class="card-block"> <table class="table table-striped table-hover table-bordered"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Hobby</th> </tr> </thead> <tbody th:each="person : ${personInformation}"> <tr> <td th:text="${person.name}"></td> <td th:text="${person.age}"></td> <td th:text="${person.hobby}"></td> <td><a th:href="@{'/edit/' +${person.id}}" class="btn btn-primary">Edit</a> <a class="btn btn-warning " th:href="@{'/personDelete/' + ${person.id}}" title="Sil" >Delete</a> </td> </tbody> </table> <a th:href="@{/add}" class="btn btn-primary">New Person</a> </div> </div> </div> <th:block th:include="commons/javascript_url :: javascript_url"></th:block> </body> </html>
Aşağıdaki gibi bir görüntü oluşacaktır.
Şimdi add.html ve edit.html sayfalarımızı oluşturalım.
add.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}" />
<body>
<div class="container">
<div class="card">
<div class="card-block">
<form th:action="@{/add}" method="post" th:object="${personInformation}">
<div class="form-row">
<div class="form-group col-md-12">
<div class="form-group">
<label >
edit.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}" /> <body> <div class="container"> <div class="card"> <div class="card-block"> <form th:action="@{'/edit/' +${persons.id}}" method="post"> <div class="form-row"> <div class="form-group col-md-12"> <div class="form-group"> <label > Bootstrap ve javascript'in URL adreslerini commons dosyasına belirtelim.
<html xmlns:th="http://www.thymeleaf.org"> <div th:fragment="javascript_url"> <script type="text/javascript" src="webjars/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="webjars/bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </div> </html>
Application=>run dedikten sonra araç çubuğuna aşağıdaki adresi yazalım.
Aşağıdaki görüntü karşılayacaktır bizi.
Umarım faydalı olmuştur.Keyifli çalışmalar dilerim,sevgiler.
Spring Boot İle Rest Servis Uygulama Örneği