SpringData Rest etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
SpringData Rest etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

18 Temmuz 2023 Salı

SpringData Rest findAll İşlemi

Giriş
findAll işlemi için repository ismi yazılır. 

Örnek
Şöyle yaparız
http://localhost:8080/people  
Örnek
Elimizde şöyle bir kod olsun
@Entity
@Table(name="tb_Student")
public class Student {
  ...
}

public interface StudentRepo extends JpaRepository<Student, Integer>{
}
İstek gönderelim. URL'de repository'nin çoğul hali kullanılıyor
http://localhost:8080/students
Çıktı şöyle
{
  "_embedded" : {
    "students" : [ {
      "firstName" : "Avans",
      "lastName" : "MA",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/api/students/1"
        },
        "student" : {
          "href" : "http://localhost:8080/api/students/1"
        }
      }
    }, {
      "firstName" : "Abhi",
      "lastName" : "WE",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/api/students/2"
        },
        "student" : {
          "href" : "http://localhost:8080/api/students/2"
        }
      }
    }, 
    ...
   ]
}

23 Eylül 2020 Çarşamba

SpringData Rest Kullanımı

Giriş
Tüm @RepositoryRestResource olarak işaretli repository sınıflarını tarar ve HATEOAS formatında çıktı verir. Açıklaması şöyle. @RepositoryRestResource Anotasyonu yazısına bakabilirsiniz.
By default, Spring Data REST will export ALL top-level, public interface repositories. You only need @RepositoryRestResource to either NOT export an interface, or to alter the details of the endpoint.
Enpoint'lerin ismi repository arayüzünün çoğul hale getirilmiş halidir.

Maven
Şu satırı dahil ederiz
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency>

1. Resource Discoverability İçin Kullanılacak URL
Örneği application.properties dosyası şöyle olsun
spring.data.rest.base-path=myapi
Bu durumda 
"localhost:8080/myapi" adresine gittiğimizde SpringData Rest tarafından bilinen rest endpoint'leri görebiliriz. Eğer base-path tanımlı değilse "http://localhost:8080/" adresini kullanırız

Örnek
Şöyle yaparız
spring.data.rest.base-path=/api

2. Ne Zaman Spring Data Rest yerine Custom Service Kullanmalı?
Ne zaman Custom Service yazmalı ve ne zaman Spring Data Rest kullanmalı sorusu hep kafa karıştırıyor. Bu sorunun cevaplarından birisi şöyle. Eğer sadece basit CRUD benzeri işler REST üzerinden yapacaksak Spring Data Rest yeterli. Açıklaması şöyle
Spring Data is an additional convenient mechanism for interacting with database entities, organizing them in a repository, extracting data, changing it. in some cases, it will be enough to declare the interface and method in it, without implementing it. P.S and it's a good choice if you're creating a simple crud
3. Repository İçin URL Örnekleri
- findAll işlemi için repository ismi yazılır.
findAll işlemi yazısına taşıdım

- findById, Delete, Post , Put işlemleri için Repository'den sonra id yazılır. Şöyle yaparız.
http://localhost:8080/people/1

- http://localhost:8080/myendpoint/search şeklinde yazarsak repository sınıfındaki custom Query'ler gösterilir.

- http://localhost:8080/people/search/findByLastName?name=Baggins şeklinde yazarsak findByLastName metodunu parametreler ile çağırırız.

3. URI Template Kullanımı
- Eğer sayfalama istemiyorsak Repository nesnemizi JpaRepository, PaginsAndSortingRepository yerine CrudRepository 'den kalıtmak gerekir.
- Veya spring.data.rest.default-page-size değeri değiştirilebilir. Varsayılan sayfa büyüklüğü 20

Page ve Size Parametreleri
- ?size=10 yazarsak sayfa büyüklüğü değiştirilir.
- ?page=1 yazarsak kaçıncı sayfayı isteğimizi belirtiriz.

Sort Parametresi
?sort= şeklinde yaparız.

Projection 
Parametresi
Örnek ver

4. İlişki Kuralları
Açıklaması şöyle.
1) If you do not define a Repository for the child type, a link will not be generated, and it will instead be embedded in the parent object. Of course, this only is useful if you don't need a Repository for that object.

2) FetchType.EAGER will eagerly load the child object. Since the object is already loaded, there is no reason to provide a link to it, so spring-data-rest will embed the object. Make sure to put this on the side with the single object, not the Collection

8 Aralık 2019 Pazar

SpringData Rest @RepositoryRestResource Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
Maven
Maven'da şöyle yaparız.
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
Kullanım
Şöyle yaparız
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface ProductionOrders extends CrudRepository<ProductionOrder, Long> {

}
collectionResourceRel  Alanı
Eğer bu repository JSON formatına çevrilirse kullanılacak nesne ismini belirtir.

exported Alanı
false yaparsak SpringData Rest bu repository sınıfı görmezden gelir.

path Alanı
Rest Endpoint için kullanılacak ismi belirtir.
Örnek
Elimizde şöyle bir kod olsun.
@RepositoryRestResource(path = "tuple", collectionResourceRel = "tuple")
public interface TupleRepository extends JpaRepository<Tuple, Integer> {

  @RestResource(path = "findAllByAnr", rel = "findAllByAnr")
  List<Tuple> findAllByAnr(@Param("anr") String anr);

}
Şöyle yaparız.
http://localhost:8081/tuple/search/findAllByAnr?anr=somevalue
Bulk Insert
SpringData Rest Bulk Insert işlemini desteklemiyor.

Bidiretional OneToMany İlişki Yaratmak
SpringData Rest bidirectional ilişkileri yönetmiyor. Elimizdeki parent nesne şöyle olsun
@Data
@Entity
@Table(name = "POTATO")
public class PotatoEntity {
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger id;

    @Column(name = "FIRSTNAME")
    private String firstname;

    @Column(name = "LASTNAME")
    private String lastname;

    @OneToMany(mappedBy = "potato", cascade = CascadeType.PERSIST)
    private List<DetailPotatoEntity> detailPotatoList;
}
Many nesne şöyle olsun
@Data
@Entity
@Table(name = "DETAIL_POTATO")
public class DetailPotatoEntity {
    @Id
    @Column(name = "ID")
    private BigInteger id;

    @Column(name = "WEIGHT")
    private BigDecimal weight;

    @Column(name = "HEIGHT")
    private BigDecimal height;

    @JoinColumn(name = "POTATO_ID", nullable = false)
    @ManyToOne
    @JsonBackReference(value = "potato-detailPotato")
    private PotatoEntity potato;
}
Şu veriyi post edelim
{
  "firstname":"patate",
  "lastname":"potato",
  "detailPotatoList": [
    {
      "weight":12,
      "height":13
    }
  ]
}
İlişkiyi kodda kurmak gerekiyor. Parent sınıfta şöyle yaparız.
@PrePersist
public void prePersist() {
    detailPotatoList.forEach(detailPotato-> detailPotato.setPotato(this));
}
ManyToOne İlişkiye Many Nesne Post Etmek
Örnek
Elimizde şöyle bir kod olsun. Post nesnesi ilişkinin "One" tarafını temsil eder.
@Entity
public class Post {

    @Id
    @GeneratedValue
    private long id;
    private String author;
    private String content;
    private String title;

    @OneToMany
    private List<Comment> comments;

    // Standard getters and setters...
}
Elimizde şöyle bir kod olsun. Comment nesnesi ilişkinin "Many" tarafını temsil eder.
@Entity
public class Comment {

    @Id
    @GeneratedValue
    private long id;
    private String author;
    private String content;

    @ManyToOne
    private Post post;

    // Standard getters and setters...
}
Many tarafa yeni bir Comment eklemek için şöyle yaparız.
http://{server:port}/comment METHOD:POST

{"author":"abc","content":"PQROHSFHFSHOFSHOSF", "post":"http://{server:port}/post/1"}
Aynı şeyi farklı bir şekilde de çözebiliriz. Önce bir comment nesnesi yaratmak için şöyle yaparız.
curl -X POST -H "Content-Type: application/json" $url 
{  // your payload // … }

201 Created
Location: $comment_url
Daha sonra bu sefer PUT ile Comment nesnesi Post nesnesine eklenir. Şöyle yaparız. Birden fazla Comment nesnesini Post nesnesine tek bir PUT ile ekleme imkanı da var.
curl -X PUT -H "Content-Type: text/uri-list" $association_url
$comment_url

204 No Content
Örnek
Elimizde şöyle bir kod olsun. Container nesnesi ilişkinin "One" tarafını temsil eder.
@javax.persistence.Entity
@Table(name = "CONTAINER")
public class Container implements Serializable {
  ...
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "container", cascade = CascadeType.ALL)
  private List<Item> items;
}
Elimizde şöyle bir kod olsun. Record nesnesi ilişkinin "Many" tarafını temsil eder.
@javax.persistence.Entity
@Table(name = "ITEM")
public class Record implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "ID")
  private Long id;

  @Basic
  private Long value;
  @Basic
  private Date date;

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "CONTAINER_ID")
  private Container container;
}
Many tarafa yeni bir Record eklemek için şöyle yaparız.
POST { "value" : 666, "date" : "2016-01-31T23:00:00.000+0000",
  "container":"http://localhost:8080/container/1"}