C
C
Chvalov2018-05-08 18:27:47
Hibernate
Chvalov, 2018-05-08 18:27:47

How to correctly implement updating and saving content in Spring-Boot?

entity
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;

@Entity
@Table(name = "projects")
public class Projects {

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

    @Size(min=4, max=128)
    @NotBlank()
    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description" , nullable = true)   // TODO Text
    private String description;

    @Temporal(TemporalType.TIMESTAMP)
    @CreationTimestamp
    @Column(name = "created", nullable=false, updatable=false)
    private Date createDate;

    @Temporal(TemporalType.TIMESTAMP)
    @UpdateTimestamp
//    @LastModifiedDate
    @Column(name = "updated", nullable=false, updatable=true)
    private Date updateDate;

    public Projects() {
    }

    public Projects(@Size(min = 5, max = 128) @NotBlank() String name, String description, Date createDate, Date updateDate) {
        this.name = name;
        this.description = description;
        this.createDate = createDate;
        this.updateDate = updateDate;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

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

    public Date getCreateDate() {
        return createDate;
    }

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

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

}
Repositories
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import spoofing.Entity.Projects;

import java.util.List;

@Repository
public interface ProjectsRepository extends JpaRepository<Projects, Long> {

    // Поиск по названию проекта
    List<Projects> findByName(String name);

}
ProjectsService
import spoofing.Entity.Projects;
import java.util.List;

public interface ProjectsService {

    Projects addProjects(Projects projects);
    void delete(long id);
    List<Projects> getByName(String name);
    Projects getById(long id);
    Projects editProjects(Projects Projects);
    List<Projects> getAll();

}
ProjectsServiceImpl
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spoofing.Entity.Projects;
import spoofing.Repositories.ProjectsRepository;
import spoofing.Service.ProjectsService;

import java.util.List;

@Service
public class ProjectsServiceImpl implements ProjectsService {

    @Autowired
    private ProjectsRepository projectsRepository;

    @Override
    public List<Projects> getAll() {
        return projectsRepository.findAll();
    }

    @Override
    public List<Projects> getByName(String name) {
        return projectsRepository.findByName(name);
    }

    @Override
    public Projects addProjects(Projects projects) {
        Projects savedProjects = projectsRepository.saveAndFlush(projects);
        return savedProjects;
    }

    @Override
    public Projects editProjects(Projects projects) {
        return projectsRepository.saveAndFlush(projects);
    }

    @Override
    public void delete(long id) {
        projectsRepository.deleteById(id);
    }

    @Override
    public Projects getById(long id) {
        return projectsRepository.getOne(id);
    }

}
ProjectsController - RestController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import spoofing.Entity.Projects;
import spoofing.Service.ProjectsService;

import java.util.List;

@RestController
@RequestMapping("/api/projects")
public class ProjectsController {

    @Autowired // TODO - нужен ли здесь автоваринг ???
    private ProjectsService projectsService;

    @GetMapping("/all")
    public List<Projects> findAll() {
        return projectsService.getAll();
    }

    @GetMapping("/find/{name}")
    public List<Projects> findByName(@PathVariable final String name) {
        return projectsService.getByName(name);
    }

    @PostMapping("/save")
    public Projects save(@RequestBody final Projects projects) {
        projectsService.addProjects(projects);
        return projectsService.getById(projects.getId());
    }

    @PutMapping("/edit/{id}")
    public Projects edit(@RequestBody final Projects projects) {    // @PathVariable long id,
        // Example - https://www.djamware.com/post/59be51e780aca768e4d2b140/tutorial-of-building-java-rest-api-using-spring-boot-and-mongodb
        projectsService.editProjects(projects);
        return projectsService.getById(projects.getId());
    }

    // TODO Сделать валидацию и ответы
    // Пример - http://websystique.com/spring-boot/spring-boot-rest-api-example/
    @DeleteMapping("delete/{id}")
    public void delete(@PathVariable("id") long id) {   //ResponseEntity<Void>
        projectsService.delete(id);
        //return ResponseEntity.status(HttpStatus.OK).build();
    }

}
The situation is as follows, if a POST request is sent nameand descriptiona api/projects/savenew record is created in the database, but if you add an id to the request, then the record in the database is updated, what to do in this situation ?? (Check that ID == NULL ?)
I also don’t know how easy it is to update a record in the database by id so that I don’t pass ID api/projects/edit/{id}in the request body

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question