Search code examples
javaangularrestmicroservices

How to update specific entity/row in jpa entity manager


I would like someone to help me on how to update row with entity manager. Here is a table ex, in angular where data is sent to rest service: app.html

<tr *ngFor="let myCar of cars$ | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
            <td>{{ (p - 1) * count + i + 1 }}</td>
            <td>{{myCar.name}}</td>
            <td>{{myCar.price}}</td>
            <td><button type="submit" class="btn btn-secondary" (click)="fillForm(myCar)">
                    <i class="glyphicon glyphicon-edit"></i>Edit
                </button></td>
</tr>

carsDTO.java

@Id
@Column(name = "name")
private String name;

@Column(name = "price")
private String price;

service.java

public carsDTO updateCar(carDTO cars){
  TypedQuery<myquerycalss> query = entitymanager.createNamedQuery("sqlName", 
  myquerycalss.class);
  // I need help to complete this update method
  // Maybe no need to first find by id, the row gets update based on @id 
  // on the name
}

resource.java

@PUT
@Path("/updatecars")
public Response updateCar(){
    // no preblem here
}

Note: You can see that in the app.html I have ID generated but my jave class just name and price variables.

What is the best approach to update a chosen entity, that is, fields of database record, in my service.java? My resouces url is without parameter, that is URL: .../updatecars


Solution

  • Your resource needs to receive the car selected and changed in the frontend. You can change it to receive inside the request body, using this:

    @RequestMapping(method = RequestMethod.PUT, value = "/updatecars")
    public Response updateCar(@RequestBody() carDTO car){
        // here you call the service, passing the car as parameter
        service.updateCar(car);
    }
    

    Inside your angular component, you have to put the car selected in the http request. Something like this:

    saveCar(car: carDTO){
        return this.httpBase.put(this.url, car, this.options)
            .map(dados => dados.json());  // handle the return here....
    }
    

    Inside your service:

    public carsDTO updateCar(carDTO cars) {
        TypedQuery<myquerycalss> query = entitymanager.createNamedQuery("sqlName", myquerycalss.class);
        query.setParameter("name", cars.getName());
        query.setParameter("price", cars.getPrice());
        query.executeUpdate();
        ...
    }
    

    I'm assuming that your named query SQL is like this:

    UPDATE cars SET price = :price WHERE name = :name