我希望有人帮助我了解如何使用实体管理器更新行。这是一个表格,以 Angular 表示,其中数据发送到休息服务: 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
}
注意:您可以在 app.html 中看到我生成了 ID,但我的 jave 类只是名称和价格变量。
在我的 service.java 中更新所选实体(即数据库记录字段)的最佳方法是什么?我的资源网址不带参数,即网址:.../updatecars
最佳答案
您的资源需要接收在前端选择和更改的汽车。 您可以使用以下命令将其更改为在请求正文中接收:
@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);
}
在你的 Angular 组件中,你必须将在http请求中选择的汽车放入其中。像这样的事情:
saveCar(car: carDTO){
return this.httpBase.put(this.url, car, this.options)
.map(dados => dados.json()); // handle the return here....
}
在您的服务中:
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();
...
}
我假设您的命名查询 SQL 如下所示:
UPDATE cars SET price = :price WHERE name = :name
关于java - 如何更新jpa实体管理器中的特定实体/行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081792/