• Google Guava Örneği
  • Flutter, Dart?
  • Ignite ?
  • Yine yine yeniden?
Main Menu

Spring – Hibernate – RestFul Servis

Merhaba,
Bugün oldukça yaygınlaşan servis türü olan RestFul Servis türünü anlatmaya çalışacağım.
Ben biraz geç kalsam da bir çok büyük ve küçük projede kullanılmaya başlanmış.
Bu yazıda yalnızca Servis kısmını anlatacağım, ilerleyen günlerde Client kısmını da yazmayı planlıyorum.

** Yazıya başladıktan 1 saat sonra gelen bir telefon ile ufak bir proje yapmam gerekti. Projeyi rest ile yapacağım. 2-3 yazılık bir dizi olacak.
** Hayır işi olduğu için açık kaynak paylaşacağım hem buradan hemde gitHub'dan.

Spor salonlarında kullanılmak üzere bir web projesi olacak.
Kullanılan Teknolojiler;
RestFul - Spring - Hibernate - JasperReport.

Proje genel hatları.

RestFulService

pom.xml kısmı:

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>in.sercan</groupId>
<artifactId>RestfulGYM</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>Restful GYM</name>

<properties>
<springframework.version>4.2.0.RELEASE</springframework.version>
<jackson.version>2.5.3</jackson.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<!-- hibernate & postgress -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.1.Final</version>
</dependency>

<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.6.Final</version>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- hibernate & postgress -->

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>RestfulExampleProject</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>

<finalName>RestfulExampleProject</finalName>
</build>
</project>
Kullanacağımız model dosyası;
package in.sercan.model;

import java.io.Serializable;
import java.util.Date;
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.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
*
* @author Sercan.in
*/

@Entity
@Table(name = "member")
@SequenceGenerator(name = "member_seq_id", sequenceName = "member_seq_id", allocationSize = 1)
public class Member implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "member_seq_id")
@Basic(optional = false)
@Column(name = "id")
private Integer id;

@Column(name = "member_name")
private String memberName;

@Column(name = "member_surname")
private String memberSurname;

@Column(name = "member_fullname")
private String memberFullname;

@Column(name = "member_phone")
private String memberPhone;

@Column(name = "member_mail")
private String memberMail;

@Column(name = "member_reference")
private String memberReference;

@Column(name = "member_adress")
private String memberAddress;

@Column(name = "member_sex")
private String memberSex;

@Column(name = "member_age")
private String memberAge;

@Basic(optional = false)
@Column(name = "member_dateregistration")
@Temporal(TemporalType.TIMESTAMP)
private Date memberDateRegistration;

@Basic(optional = false)
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;

public Member() {
id = 0;
}

public Member(Integer id, String memberName, String memberSurname, String memberFullname, String memberPhone, String memberMail, String memberReference, String memberAddress, String memberSex, String memberAge, Date memberDateRegistration, Date createDate) {
this.id = id;
this.memberName = memberName;
this.memberSurname = memberSurname;
this.memberFullname = memberFullname;
this.memberPhone = memberPhone;
this.memberMail = memberMail;
this.memberReference = memberReference;
this.memberAddress = memberAddress;
this.memberSex = memberSex;
this.memberAge = memberAge;
this.memberDateRegistration = memberDateRegistration;
this.createDate = createDate;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getMemberName() {
return memberName;
}

public void setMemberName(String memberName) {
this.memberName = memberName;
}

public String getMemberSurname() {
return memberSurname;
}

public void setMemberSurname(String memberSurname) {
this.memberSurname = memberSurname;
}

public String getMemberFullname() {
return memberFullname;
}

public void setMemberFullname(String memberFullname) {
this.memberFullname = memberFullname;
}

public String getMemberPhone() {
return memberPhone;
}

public void setMemberPhone(String memberPhone) {
this.memberPhone = memberPhone;
}

public String getMemberMail() {
return memberMail;
}

public void setMemberMail(String memberMail) {
this.memberMail = memberMail;
}

public String getMemberReference() {
return memberReference;
}

public void setMemberReference(String memberReference) {
this.memberReference = memberReference;
}

public String getMemberAddress() {
return memberAddress;
}

public void setMemberAddress(String memberAddress) {
this.memberAddress = memberAddress;
}

public String getMemberSex() {
return memberSex;
}

public void setMemberSex(String memberSex) {
this.memberSex = memberSex;
}

public String getMemberAge() {
return memberAge;
}

public void setMemberAge(String memberAge) {
this.memberAge = memberAge;
}

public Date getMemberDateRegistration() {
return memberDateRegistration;
}

public void setMemberDateRegistration(Date memberDateRegistration) {
this.memberDateRegistration = memberDateRegistration;
}

public Date getCreateDate() {
return createDate;
}

public void setCreateDate(Date createDate) {
this.createDate = createDate;
}

@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (this.id != null ? this.id.hashCode() : 0);
hash = 79 * hash + (this.memberName != null ? this.memberName.hashCode() : 0);
hash = 79 * hash + (this.memberSurname != null ? this.memberSurname.hashCode() : 0);
hash = 79 * hash + (this.memberFullname != null ? this.memberFullname.hashCode() : 0);
hash = 79 * hash + (this.memberPhone != null ? this.memberPhone.hashCode() : 0);
hash = 79 * hash + (this.memberMail != null ? this.memberMail.hashCode() : 0);
hash = 79 * hash + (this.memberReference != null ? this.memberReference.hashCode() : 0);
hash = 79 * hash + (this.memberAddress != null ? this.memberAddress.hashCode() : 0);
hash = 79 * hash + (this.memberSex != null ? this.memberSex.hashCode() : 0);
hash = 79 * hash + (this.memberAge != null ? this.memberAge.hashCode() : 0);
hash = 79 * hash + (this.memberDateRegistration != null ? this.memberDateRegistration.hashCode() : 0);
hash = 79 * hash + (this.createDate != null ? this.createDate.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Member other = (Member) obj;
if ((this.memberName == null) ? (other.memberName != null) : !this.memberName.equals(other.memberName)) {
return false;
}
if ((this.memberSurname == null) ? (other.memberSurname != null) : !this.memberSurname.equals(other.memberSurname)) {
return false;
}
if ((this.memberFullname == null) ? (other.memberFullname != null) : !this.memberFullname.equals(other.memberFullname)) {
return false;
}
if ((this.memberPhone == null) ? (other.memberPhone != null) : !this.memberPhone.equals(other.memberPhone)) {
return false;
}
if ((this.memberMail == null) ? (other.memberMail != null) : !this.memberMail.equals(other.memberMail)) {
return false;
}
if ((this.memberReference == null) ? (other.memberReference != null) : !this.memberReference.equals(other.memberReference)) {
return false;
}
if ((this.memberAddress == null) ? (other.memberAddress != null) : !this.memberAddress.equals(other.memberAddress)) {
return false;
}
if ((this.memberSex == null) ? (other.memberSex != null) : !this.memberSex.equals(other.memberSex)) {
return false;
}
if ((this.memberAge == null) ? (other.memberAge != null) : !this.memberAge.equals(other.memberAge)) {
return false;
}
if (this.id != other.id &amp;amp;amp;&amp;amp;amp; (this.id == null || !this.id.equals(other.id))) {
return false;
}
if (this.memberDateRegistration != other.memberDateRegistration &amp;amp;amp;&amp;amp;amp; (this.memberDateRegistration == null || !this.memberDateRegistration.equals(other.memberDateRegistration))) {
return false;
}
if (this.createDate != other.createDate &amp;amp;amp;&amp;amp;amp; (this.createDate == null || !this.createDate.equals(other.createDate))) {
return false;
}
return true;
}

@Override
public String toString() {
return "Member{" + "id=" + id + ", memberName=" + memberName + ", memberSurname=" + memberSurname + ", memberFullname=" + memberFullname + ", memberPhone=" + memberPhone + ", memberMail=" + memberMail + ", memberReference=" + memberReference + ", memberAddress=" + memberAddress + ", memberSex=" + memberSex + ", memberAge=" + memberAge + ", memberDateRegistration=" + memberDateRegistration + ", createDate=" + createDate + '}';
}

}
Dao;
package in.sercan.dao;

import in.sercan.model.Member;
import in.sercan.service.SessionProvider;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;

/**
*
* @author Sercan.in
*/
public class MemberDao extends BaseDao&amp;amp;lt;Member&amp;amp;gt; {

public MemberDao(SessionProvider sp) {
super(sp);
}

public List&amp;amp;lt;Member&amp;amp;gt; fetchMemberList() {
List&amp;amp;lt;Member&amp;amp;gt; list = new ArrayList&amp;amp;lt;Member&amp;amp;gt;();
Query q = getSession().createQuery("SELECT M FROM Member as M");
list = q.list();
return list;
}

public List&amp;amp;lt;Member&amp;amp;gt; fetchMemberById(Integer id) {
List&amp;amp;lt;Member&amp;amp;gt; list = new ArrayList&amp;amp;lt;Member&amp;amp;gt;();
Query q = getSession().createQuery("SELECT M FROM Member as M WHERE id=:id");
q.setInteger("id", id);
list = q.list();
return list;
}

public void deleteMember(Integer id) {
Query q = getSession().createQuery("DELETE FROM Member WHERE id=:id");
q.setInteger("id", id);
q.executeUpdate();
}

public void deleteAll() {
Query q = getSession().createQuery("DELETE FROM Member");
q.executeUpdate();
}
}

Response ( Mesaj );

package in.sercan.model;

/**
*
* @author Sercan.in
*/
public class Response {

private int status;

private String message;

public Response() {
status = 0;
message = "HATA !";
}

public Response(int status, String message) {
this.status = status;
this.message = message;
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

MemberService;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package in.sercan.service;

import in.sercan.model.Member;
import in.sercan.model.Response;
import java.util.List;

/**
*
* @author Sercan.in
*/
public interface MemberService {

List&amp;amp;lt;Member&amp;amp;gt; findById(Integer id);

Response saveMember(Member member);

Response deleteMemberById(Integer id);

List&amp;amp;lt;Member&amp;amp;gt; findAllMembers();

Response deleteAllMembers();

}

MemberServiceImpl

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package in.sercan.service;

import in.sercan.model.Member;
import in.sercan.model.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
*
* @author Sercan.in
*/
@Service("memberService")
@Transactional
public class MemberServiceImpl extends BaseService implements MemberService {

private static final AtomicLong counter = new AtomicLong();

public List&amp;amp;lt;Member&amp;amp;gt; findAllMembers() {
List&amp;amp;lt;Member&amp;amp;gt; memberList = new ArrayList&amp;amp;lt;Member&amp;amp;gt;();
try {
memberList = getDaoFactory().getMemberDao().fetchMemberList();
} catch (Exception e) {
e.printStackTrace();
}

return memberList;
}

public Response saveMember(Member member) {
Response response = new Response();
try {
beginTransaction();
getDaoFactory().getMemberDao().merge(member);
response.setStatus(1);
response.setMessage("Kayıt Başarılı");
commitTransaction();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeSession();
}
return response;

}

public Response deleteMemberById(Integer id) {
Response response = new Response();
try {
getDaoFactory().getMemberDao().deleteMember(id);
response.setStatus(1);
response.setMessage("Silme başarılı");

} catch (Exception e) {
e.printStackTrace();
}
return response;
}

public Response deleteAllMembers() {
Response response = new Response();
try {
getDaoFactory().getMemberDao().deleteAll();
response.setStatus(1);
response.setMessage("Silme başarılı");
} catch (Exception e) {
e.printStackTrace();
}
return response;
}

public List&amp;amp;lt;Member&amp;amp;gt; findById(Integer id) {
return getDaoFactory().getMemberDao().fetchMemberById(id);
}

}

MemberController;

package in.sercan.controller;

import in.sercan.model.Member;
import in.sercan.model.Response;
import in.sercan.service.MemberService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
*
* @author Sercan.in
*/
@RestController
public class MemberController {

@Autowired
MemberService memberService;

@RequestMapping(value = "/", method = RequestMethod.GET)
public String helloWorld() {
return "index";
}

/**
*
* Tüm müşterileri listeler
*
* @return
*/
@RequestMapping(value = "/members", method = RequestMethod.GET)
public ResponseEntity&amp;amp;lt;List&amp;amp;lt;Member&amp;amp;gt;&amp;amp;gt; listAllMember() {
List&amp;amp;lt;Member&amp;amp;gt; members = memberService.findAllMembers();
return new ResponseEntity&amp;amp;lt;List&amp;amp;lt;Member&amp;amp;gt;&amp;amp;gt;(members, HttpStatus.OK);
}

/**
*
* Kullanıcıdan gelen id'ye göre müşteri listeler
*
* @param id
* @return
*/
@RequestMapping(value = "/member/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&amp;amp;lt;List&amp;amp;lt;Member&amp;amp;gt;&amp;amp;gt; getMember(@PathVariable("id") Integer id) {
List&amp;amp;lt;Member&amp;amp;gt; members = memberService.findById(id);
return new ResponseEntity&amp;amp;lt;List&amp;amp;lt;Member&amp;amp;gt;&amp;amp;gt;(members, HttpStatus.OK);
}

/**
* Kullannici olusturur
*
* @param member
* @return
*/
@RequestMapping(value = "/member/saveMember", method = RequestMethod.POST)
public ResponseEntity&amp;amp;lt;Response&amp;amp;gt; createUser(@RequestBody Member member) {
Response response = memberService.saveMember(member);
return new ResponseEntity&amp;amp;lt;Response&amp;amp;gt;(response, HttpStatus.OK);
}

@RequestMapping(value = "/member/test/{adi}", method = RequestMethod.POST)
public String save(@PathVariable("adi") String adi) {
return adi;
}

/**
* Müşteri siler
*
* @param id
* @return
*/
@RequestMapping(value = "/member/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity&amp;amp;lt;Response&amp;amp;gt; deleteMember(@PathVariable("id") Integer id) {
Response response = memberService.deleteMemberById(id);
return new ResponseEntity&amp;amp;lt;Response&amp;amp;gt;(response, HttpStatus.OK);
}

/**
* Tum kullanicilari siler
*
* @return
*/
@RequestMapping(value = "/member/deleteAll", method = RequestMethod.DELETE)
public ResponseEntity&amp;amp;lt;Response&amp;amp;gt; deleteAllMembers() {
Response response = memberService.deleteAllMembers();
return new ResponseEntity&amp;amp;lt;Response&amp;amp;gt;(response, HttpStatus.OK);
}

}

 

Testleri için Chorome'un Postman eklentisini kullanıyoruz;
/members

MemberList

/member/saveMember

saveAndUpdateMember

/member/delete/{id}

deleteMember

Program genel hatları ile bu şekilde.
Sorusu olan yorum olarak yazabilir.
Standart dosyaları yazmadım paylaşıyor olacağım.

BURADAN PROJE DOSYALARINI İNDİREBİLİRSİNİZ

gitHub

Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>