【问题标题】:How to update specific entity/row in jpa entity manager如何在 jpa 实体管理器中更新特定实体/行
【发布时间】:2020-01-24 15:59:07
【问题描述】:

我希望有人帮助我了解如何使用实体管理器更新行。这是一个表格,以角度形式将数据发送到休息服务: 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 中更新所选实体(即数据库记录的字段)的最佳方法是什么?我的资源 url 没有参数,即 URL: .../updatecars

【问题讨论】:

    标签: java angular rest microservices


    【解决方案1】:

    您的资源需要接收在前端选择和更改的汽车。 您可以使用以下方法将其更改为在请求正文中接收:

    @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);
    }
    

    在您的角度组件中,您必须将所选汽车放入 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
    

    【讨论】:

    • 角度部分没有问题。请问“...”是什么意思,你能举个例子吗?谢谢
    • 我包含了服务方法,并举了一个例子。我假设您的 SQL 具有这些参数。请在您的问题中发布您的 SQL...
    • 我不确定他是否可以在 id 上没有类似内容的情况下直接更新,因为在这种情况下 id 是字符串 stackoverflow.com/questions/18622716/…
    • @henriqueor 我的 SQL 看起来:UPDATE carTable ct SET ct.PRICE = price WHERE ct.NAME = name。这和你的例子很像。
    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2014-09-06
    • 2016-11-16
    相关资源
    最近更新 更多