更新查询,而不是选择+保​​存 [英] Update query instead of select + save

查看:56
本文介绍了更新查询,而不是选择+保​​存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用播放框架的JPA是否可以执行UPDATE sql查询?

Is it possible with JPA using play framework to execute an UPDATE sql query?

目前,我要做的是对实体进行更新:

For the moment what I do to make an update to an entity is:

  • 通过find()方法或find()方法中的选择查询来检索实体
  • 更改我想要的值
  • 在对象上调用save()方法

但是我猜它有2个查询:一个SELECT和一个UPDATE.

But I guess it makes 2 queries: a SELECT and an UPDATE.

是否有一种方法可以仅使用一个查询来完成所有操作?只有UPDATE查询吗?

Is there a way to do everything using only one query? Only an UPDATE query?

谢谢您的帮助

推荐答案

只要您使用的是API方法,我认为您不会遇到2查询问题.实体管理器不能只是开始更新实体.它必须先找到它们,检查它们的状态,然后决定是否确实需要更新,即是否进行了更改.

但是,您可以始终使用JPQL编写自己的参数化更新语句.您的find()很可能会使用与您的实体的主键匹配的ID或类似名称.
您可以将id传递给语句并直接更新.但是,如果ID不是来自用户输入而是来自先前的选择,则我只会这样做.换句话说,保证是现有实体,也是您真正想要的实体.

该查询可能看起来像这样:

As long as you're using the API methods, I don't think you'll get around your 2-queries problem. The entity manager can't just start updating entities. It has to find them first, check their state and then decide if an update is really necessary, i.e. if changes were made or not.

You could however, always write your own parametrized update statement using JPQL. Your find() will most likely use an id or something similar, which matches the primary key of your entity.
You could just pass the id into the statement and update directly. I would only do this however, if the id isn't coming from user input but rather from a previous select. In other words, guaranteed to be an existing entity and the one you really want.

The query could look something like this:

UPDATE MyTable SET MyValue = :newValue WHERE MyId = :id 

在其中传递newValue和id作为参数的地方.

Where you pass in newValue and id as a parameter.

但是,我宁愿让实体经理完成所有工作.您为什么仍然要在单个语句中执行此操作?除非您要执行大量操作,否则速度应该不是问题,因为这些简短而特定的语句通常很快.

However, I would rather let the entity manager do all the work. Why do you want to do it in a single statement anyway? Unless you're doing a ton of the operations, speed shouldn't be a problem as these short and specific statements are usually quite fast.

这篇关于更新查询,而不是选择+保​​存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆