使用@namedquery 更新查询无法正常工作
Posted
技术标签:
【中文标题】使用@namedquery 更新查询无法正常工作【英文标题】:update query using @namedquery does not work properly 【发布时间】:2021-03-11 13:39:52 【问题描述】:这是我的 DUsers 类:
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
@Entity
@Table(name = "d_users")
@NamedQueries(
@NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findAll",
query = "select e from DUsers e"),
@NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findById",
query = "select e from DUsers e "
+ "where e.oAuthId = :id "),
@NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findByOAuthId",
query = "select e from DUsers e "
+ "where e.oAuthId = :oAuthId "),
@NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findByEmail",
query = "select e from DUsers e "
+ "where e.email = :email "),
@NamedQuery(name="bonsai.dropwizard.dao.d.DUsers.confirm",
query = "update DUsers set status = 'HELLO' where oAuthId = :id")
)
public class DUsers implements IDdbPojo
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
private String oAuthId;
private String oAuthType;
private String firstName;
private String secondName;
private String city;
private String phone;
private String email;
private String profileLink;
private String profilePic;
private String status;
private String notificationToken;
private boolean confirmed;
private String password;
private String notes;
private java.util.Date created_timestamp;
private java.util.Date updated_timestamp;
.. getters and setters on-going
如您所见,我已经定义了几个@NamedQueries
,它们都可以正常工作,除了最后一个需要update
我的数据库。为了运行这个查询,我定义了两个函数:
private void confirmMailDAO(String id)
namedQuery("bonsai.dropwizard.dao.d.DUsers.confirm").setParameter("id", id);
public void confirmMailInternal(String id)
Session session = sessionFactory.openSession();
try
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
try
confirmMailDAO(id);
transaction.commit();
catch (Exception e)
transaction.rollback();
throw new RuntimeException(e);
finally
session.close();
ManagedSessionContext.unbind(sessionFactory);
在此之后,我定义了一个路径,后跟一个 POST 请求,该请求应该更新我的数据库,但遗憾的是它没有。
@POST
@Path("/confirm/id")
public void confirmMail(@NotNull @PathParam("id") String id)
DUsers user = AppConfig.getInstance().getdUsersDAO().findByIdInternal(id);
if (user == null)
throw new NotAuthorizedException("Error");
AppConfig.getInstance().getdUsersDAO().confirmMailInternal(id);
有人知道我哪里错了吗?
【问题讨论】:
【参考方案1】:您在命名查询中设置了参数但忘记执行它。
将session
传递给您的方法并执行如下:
private void confirmMailDAO(Session session, String id)
Query query = session.getNamedQuery("bonsai.dropwizard.dao.d.DUsers.confirm").setParameter("id", id);
query.executeUpdate();
【讨论】:
天哪,我花了一整天的时间在这上面工作。非常感谢:) 很高兴它有帮助。以上是关于使用@namedquery 更新查询无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章
使用 @NamedQuery 和 'SELECT OBJECt(var) FROM EntityName var 实现查询
NamedQuery:外部化实体后的 IllegalArgumentException(未找到查询)