如何将数据发布到数据库中最新添加的资源/记录中?

时间:2019-06-26 21:47:56

标签: angular typescript rest http

我想使用POST方法将特定数据发布到数据库中的现有记录。我要插入的行是空的。每次我发布东西都会创造新记录。最简单的方法是什么?

我将Angular用于前端,将Glassfish RESTful服务器用作后端。

打字稿文件:

export class MenuComponent implements OnInit {

  public codeValue: string;
  baseurl =  'http://localhost:8080/aquadine-jee/resources/restaurant';

// Empty array of menu list
  codeList = [];

  // List of Mcdonalds menu
  codeListMcd = [
    {menu: 'Hamburger menu'},
    {menu: 'Big mac menu'},
    {menu: 'Quarter Pounder menu'},
    {menu: 'Maestro burger menu'},
    {menu: 'Big Tasty menu'}
  ];

  // List of Kentucky Fried chicken menu
  codeListKfc = [
    {menu: 'Chicken burger menu'},
    {menu: 'Chicken bucket menu'},
    {menu: 'Spicy chicken menu'},
    {menu: 'Tender chicken menu'},
    {menu: 'Chicken nuggets menu'}
  ];

  // List of Burger King menu
  codeListBk = [
    {menuid: 1, menu: 'Whopper burger menu', price: 3.50},
    {menuid: 2, menu: 'Texas Bacon king menu', price: 5.50},
    {menuid: 3, menu: 'Double Steakhouse menu', price: 5.50},
    {menuid: 4, menu: 'Chili Cheese burger menu', price: 6.50},
    {menuid: 5, menu: 'Chicken Tendercrisp menu', price: 6.50}
  ];

  // List of Dominos pizza menu
  codeListDp = [
    {menuid: 1, menu: 'Pizza Shoarma menu', price: 3.50},
    {menuid: 2, menu: 'Pizza Roasted veggie menu', price: 5.50},
    {menuid: 3, menu: 'Pizza Bbq mixed grill menu', price: 5.50},
    {menuid: 4, menu: 'Pizza Hawaii menu', price: 6.50},
    {menuid: 5, menu: 'Pizza Americana menu', price: 6.50}
  ];

  // List of New York pizza menu
  codeListNyp = [
    {menu: 'Pizza Double Tasty menu'},
    {menu: 'Pizza Mixed Grill menu'},
    {menu: 'Pizza Margherita menu'},
    {menu: 'Pizza BBQ Meatlovers'},
    {menu: 'Pizza Downtown Doner menu'}
  ];


  @ViewChild('f', {static: true}) form: NgForm;

  menu = {
    menuid: ' ',
    menu: ' ',
    price: ' '
  };



  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: 'my-auth-token'
    })
  };



  constructor(private http: HttpClient) {
  }

  // Get the selected restaurant and fill the datalist with data
  ngOnInit() {
    this.http.get('http://localhost:8080/aquadine-jee/resources/restaurant')
      .subscribe(
        val => {
          const restStr = val;
          console.log(restStr);
          console.log(restStr[0].menu);
          // @ts-ignore
          const restNaam = JSON.stringify(restStr[restStr.length - 1].name);
          console.log(restNaam);
          if (restNaam.toString() === '"Mcdonalds"') {

            this.codeList = this.codeListMcd;

          } else if (restNaam.toString() === '"Kentucky Fried Chicken"') {
            this.codeList = this.codeListKfc;
          } else if (restNaam.toString() === '"Burger King"') {
            this.codeList = this.codeListBk;
          } else if (restNaam.toString() === '"Dominos pizza"') {
            this.codeList = this.codeListDp;
          } else if (restNaam.toString() === '"New York Pizza"') {
            this.codeList = this.codeListNyp;
          }
        }
      );


  }

// Method to POST the menu data to the backend
  public saveMenu(e): void {

    const menu = e.target.value;
    const list = this.codeList.filter(x => x.menu === menu)[0];


    this.menu.menu = list.menu;



    // HttpHeader to give the content type
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };

// Array with data assigned to a const
    const data = {
      menu: list.menu
    };



    console.log(data)
    const myJsonString = JSON.stringify(data);
    console.log(myJsonString.valueOf());
    console.log(JSON.stringify(data) + 'test1234568910');




    this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant', JSON.parse(myJsonString.valueOf()), httpOptions)
      .subscribe( // subscribe to observable http.post
        res => {
          console.log('response' + ' ' + res); // log results otherwise log error
        },
        err => {
          console.log('Error occured');
        }
      );

我正在尝试将数据发布到此链接中最新/最新添加的记录中

'http://localhost:8080/aquadine-jee/resources/restaurant'

后端代码:

package nl.aquadine.model;

import javax.persistence.*;



//@NamedQueries({
//  @NamedQuery(name = "Restaurant.findOne", query = "select m from Restaurant m where m.id = :id"),
//  @NamedQuery(name = "Restaurant.getAll", query = "select m from Restaurant m")
//})
/**
 * @author Fethi
 */
@Entity
@Table(name = "restaurant")
public class Restaurant {

  @Id
  @GeneratedValue
  private Long restaurantId;

  private String name;
  private String address;
  private String menu;

  public Restaurant(){

  }

  public Restaurant(String name, String address) {
    this.name = name;
    this.address = address;
    this.menu = menu;
  }

  public Long getRestaurantId() {
    return restaurantId;
  }

  public void setRestaurantId(Long restaurantId) {
    this.restaurantId = restaurantId;
  }

  public String getName() {
    return name;
  }

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

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public String getMenu() {
    return menu;
  }

  public void setMenu(String menu) {
    this.menu = menu;
  }
}

package nl.aquadine.rest;


import nl.aquadine.model.Restaurant;

import nl.aquadine.service.Impl.RepositoryServiceImpl;
import nl.aquadine.service.RepositoryService;


import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

/**
 * @author Fethi
 */


@Path("restaurant")
public class RestaurantResource {


  private RepositoryService repositoryService;

  public RestaurantResource() {
    repositoryService = RepositoryServiceImpl.getInstance();
  }

  @GET
  @Produces("application/json")
  public Response all(){
    List<Restaurant> all = repositoryService.getAllRestaurants();
    return  Response
      .status(200)
      .header("Access-Control-Allow-Origin", "*")
      .entity(all)
      .build();
  }


  @GET
  @Path("/{id}")
  @Consumes("application/json")
  public Response getRestaurant(@PathParam("id") Integer id){
    Restaurant restaurant = repositoryService.find(id);
    return Response
      .status(200)
      .entity(restaurant)
      .build();
  }


  @GET
  @Path("/name{restaurantName}")
  @Consumes("application/json")
  public Response getAllRestaurantNames(@PathParam("restaurantName") String restaurantName){
    Restaurant restaurantNames = repositoryService.getAllRestaurantNames(restaurantName);
    return Response
      .status(200)
      .entity(restaurantNames)
      .build();
  }


  @Produces(MediaType.APPLICATION_JSON)
  public List<Restaurant> getAllRestaurants(){
    return repositoryService.getAllRestaurants();
  }


  /**
   * Saves restaurant JSON
   * @param restaurant
   * @return response
   */
  @POST
  @Consumes("application/json")
  public Response save(Restaurant restaurant){
    System.out.println("TESTING");
    repositoryService.save(restaurant);
    return Response
            .status(201)
            .build();
  }

  @PUT
  @Consumes("application/json")
  public void update(Restaurant restaurant) {
    repositoryService.update(restaurant);
  }

  @DELETE
  @Path("/{id}")
  @Consumes("application/json")
  public void delete(@PathParam("id") Integer id) {
    Restaurant restaurant = repositoryService.find(id);
    repositoryService.delete(restaurant);
  }


}

1 个答案:

答案 0 :(得分:0)

原因是您使用的是 HTTP POST 请求来更新现有记录。这导致创建新记录,而不是更新现有记录。如我所见,URL用于创建和更新是相同的。要区分创建或更新,您应该使用 HTTP PUT 。如下更改代码。

this.http.put('http://localhost:8080/aquadine-jee/resources/restaurant', JSON.parse(myJsonString.valueOf()), httpOptions)
  .subscribe(res => {
      console.log('response' + ' ' + res); // log results otherwise log error
    },
    err => {
      console.log('Error occured');
    });
  • 最好是可以移动服务类的API调用。
  • 学习Rest API。