gpt4 book ai didi

java - Hibernate删除操作不更新MySql

转载 作者:行者123 更新时间:2023-11-29 12:22:35 26 4
gpt4 key购买 nike

我的删除操作不是删除数据库中的重新编码。

我的实体类:

    @Entity  
@Table(name= "User")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;
private String userName,password,type,fullName;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

public String getFullName() {
return fullName;
}
public void setFullName(String fName) {
this.fullName = fName;
}

@Column(name = "USER_ID")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}



}

@Entity
@Table(name= "Cart")
public class Cart {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;
private String userName;
private String itemSkus;
private String itemsQuantity;


public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID")
public String getUserName() {
return userName;
}
public void setUserName(String uName) {
this.userName = uName;
}

public String getItems(){
return this.itemSkus;
}

public void setItems(String items){
this.itemSkus=items;
}


public String getItemsQuantity(){
return this.itemsQuantity;
}

public void setItemsQuantity(String itemsQ){
this.itemsQuantity=itemsQ;
}



}

购物车的DAO类方法如下:

public int deleteCart(String userID){
Session currentSession=sessionObject.getSession();
//String query="from Cart Where userName :uName";
String query="DELETE FROM Cart where userName = :uName";

Query queryResult = currentSession.createQuery(query);
queryResult.setParameter("uName", userID);

int result = queryResult.executeUpdate();

System.out.println("Cart delete result "+result);

return result;
}

我尝试在 MySQL 工作台中运行查询,表更新得很好。仅在 hibernate 状态下才不会更新。

我最终在更新查询结果中得到了一些结果。

最佳答案

将查询放入事务中,开始它,执行删除查询,最后提交事务并回滚 发生错误或异常时:

public int deleteCart(String userID){

Session currentSession=sessionObject.getSession();
Transaction tr= currentSession.beginTransaction();
//String query="from Cart Where userName :uName";
try{
String query="DELETE FROM Cart where userName = :uName";

Query queryResult = currentSession.createQuery(query);
queryResult.setParameter("uName", userID);

int result = queryResult.executeUpdate();
tr.commit();

System.out.println("Cart delete result "+result);

return result;
} catch (Exception ex) {
tr.rollback();
return null;
}
}

关于java - Hibernate删除操作不更新MySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799067/

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