gpt4 book ai didi

java - 热衷于使用 JPQL 更新某些记录?

转载 作者:行者123 更新时间:2023-12-02 13:02:06 25 4
gpt4 key购买 nike

我有这个代码:

public void uploadSaveGame(User user, String saveData)
{
EntityTransaction entr=em.getTransaction();
entr.begin();
TypedQuery<Save> query = em.createQuery("UPDATE WithSave2 SET savedata WHERE u.login = :user", Save.class);
query.setParameter("login", user);
query.setParameter("save", saveData);
em.getTransaction().commit();
}

我正在尝试更新列 saveData。这是我的类(class) WitSave2:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dke.ps.Tables;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author michal
*/
@Entity
@Table(name = "with_save2")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "WithSave2.findAll", query = "SELECT w FROM WithSave2 w")
, @NamedQuery(name = "WithSave2.findBySaveid", query = "SELECT w FROM WithSave2 w WHERE w.saveid = :saveid")
, @NamedQuery(name = "WithSave2.findByLogin", query = "SELECT w FROM WithSave2 w WHERE w.login = :login")
, @NamedQuery(name = "WithSave2.findBySavedata", query = "SELECT w FROM WithSave2 w WHERE w.savedata = :savedata")})
public class WithSave2 implements Serializable {

private static final long serialVersionUID = 1L;
@Column(name = "saveid")
@Id
private Integer saveid;
@Column(name = "login")
private String login;
@Column(name = "savedata")
private String savedata;

public WithSave2() {
}

public Integer getSaveid() {
return saveid;
}

public void setSaveid(Integer saveid) {
this.saveid = saveid;
}

public String getLogin() {
return login;
}

public void setLogin(String login) {
this.login = login;
}

public String getSavedata() {
return savedata;
}

public void setSavedata(String savedata) {
this.savedata = savedata;
}

}

更新列的查询是否正确?我不太确定,尤其是这一行:

query.setParameter("login", user);
query.setParameter("save", saveData);

有人可以帮助我吗?非常感谢:)

最佳答案

给你几件事:

  • 您必须为要更改的列分配一个新值(否则不是更新的语句)
  • 您必须运行查询..而不仅仅是定义它
  • 当您使用手动事务时,最好添加一些异常管理以防万一。
  • 执行批量更新时不需要 TypedQuery

    EntityTransaction entr=em.getTransaction();
    entr.begin();

    try{
    Query query = em.createQuery("UPDATE WithSave2
    SET savedata = :saveData WHERE u.login = :user", Save.class);
    query.setParameter("login", user);
    query.setParameter("save", saveData);

    query.executeUpdate();

    entr.commit();
    }catch(Exception e){
    entr.rollback();
    }

关于java - 热衷于使用 JPQL 更新某些记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44248265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com