SpringBoot CRUD - PullRequest
       5

SpringBoot CRUD

0 голосов
/ 10 апреля 2020

Я застрял в своем проекте Springboot Crud, и мне нужны ваши подсказки. Проблема в том, что я хочу использовать GET со своей строковой переменной barcode, а также УДАЛИТЬ и PUT, используя переменную id int, но каким-то образом мне не удалось DELETE и PUT с переменной id, и я застрял с этим весь день. я опубликую свой код, и я приложу к каждой помощи помощь

Приложение. java

package com.javahelps.restservice;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.javahelps.restservice.entity.User;

import com.javahelps.restservice.repository.UserRepository;

import com.javahelps.restservice.repository.UserRepository2;

import com.javahelps.restservice.repository.UserRepository3;



@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    protected CommandLineRunner init(final UserRepository userRepository , UserRepository2 userRepository2,UserRepository3 userRepository3) {
        return null;



        };
    }

UserController. java

package com.javahelps.restservice.controller;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.web.ServerProperties.Session;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    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;


    import com.javahelps.restservice.entity.User;

    import com.javahelps.restservice.repository.UserRepository;
    import com.javahelps.restservice.repository.UserRepository3;

    import javassist.tools.web.BadHttpRequest;

    @RestController
    @RequestMapping(path = "/productnames")
    public class UserController {



        @Autowired
        private UserRepository repository;
        private UserRepository3 repository3;

        @GetMapping
        public Iterable<User> findAll() {
            return repository.findAll();
        }

        @GetMapping(path = "/{barcode}")
        public User find(@PathVariable("barcode") String barcode) {
            return repository.findOne(barcode);
        }

        @PostMapping(consumes = "application/json")
        public User create(@RequestBody User user) {
            return repository.save(user);
        }



        @DeleteMapping(path = "/{barcode}")
        public void delete(@PathVariable("barcode") String barcode) {
            repository.delete(barcode);
        }
        @DeleteMapping(path = "1/{id}")
        public void delete(@PathVariable("id") Integer id) {
            repository.delete(id);
        }
        @PutMapping(path = "/{barcode}")
        public User update(@PathVariable("barcode") String barcode, @RequestBody User user) throws BadHttpRequest {
            if (repository.exists(barcode)) {
                user.setBarcode(barcode);
                return repository.save(user);
            } else {
                throw new BadHttpRequest();
            }
        }
    }

UserRepository. java

package com.javahelps.restservice.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;

import com.javahelps.restservice.entity.User;
@RestResource(exported = false)
@Repository
public interface UserRepository extends JpaRepository<User,String> {

}

Пользователь. java

package com.javahelps.restservice.entity;

import java.sql.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity

@Table(name="ProductNames")
public class User {





    private int id;

    @Id
    private String barcode;
    private String name;
    private String category;
    private int qty;
    private Date dater;
    private Date datel;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    public String getBarcode() {
        return barcode;
    }

    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }

    public String getName() {
        return name;
    }

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

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Date getDater() {
        return dater;
    }

    public void setDater(Date dater) {
        this.dater = dater;

    }

    public Date getDatel() {
        return datel;
    }

    public void setDatel(Date datel) {
        this.datel = datel;

    }


    @Override
    public String toString() {
        return "User{" + "='" +", id='"+ id + '\'' +", name='"+ barcode + '\'' + ", name='" + name + '\'' + ", category='" + category + '\''
                + ", qty='" + qty + '\'' + ", dater='" + dater + '\''+", datel='" + datel + '\''    +'}';
    }
}

1 Ответ

0 голосов
/ 11 апреля 2020

Для удаления на основе идентификатора, поскольку ваш первичный ключ не является int id, вы должны написать приведенный ниже пользовательский код в своем интерфейсе, расширяющем JpaRepository.

А в вашем контроллере rest вы должны вызывать его как repository.deleteById(id);

@Repository
public interface UserRepository extends JpaRepository<User,String> {
    @Modifying
    @Transactional
    @Query(value="delete from User u where u.id= ?1")
    void deleteById(int id);
}

Точно так же вам, возможно, придется написать код и для вашего оператора обновления (для случая PUT). Надеюсь, это поможет.

...