gpt4 book ai didi

java - 调用与 EntityManager 合并时的 PersistenceException 和 IllegalArgumentException

转载 作者:行者123 更新时间:2023-11-30 10:27:03 25 4
gpt4 key购买 nike

我正在尝试使用自定义对象调用 Entitymanager.merge(),但我不断收到以下错误:

javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of my.package.model.offer.Cost.id
java.lang.IllegalArgumentException: Can not set int field my.package.model.offer.Cost.id to java.lang.String

好像调用不到Cost.id的getter,莫名其妙返回的是String,应该是int.

这是我的模型类成本:

@Entity
public class Cost implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Lob
@Column(length = 65535)
private String description;

public Cost(String description) {
this.description = description;
}

public Cost() {
}

public int getId() {
return id;
}

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

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}
}

这是我的 Controller (ManagedBean),它尝试调用 EntityManager.persist():

@ManagedBean(name = "offerController")
@SessionScoped
public class OfferController {
@PersistenceContext
private EntityManager em;

private Offer offerCurrent = new Offer();

public String saveCosts() {
offerCurrent.setCosts(costsCurrent);
try {
utx.begin();
offerCurrent = em.merge(offerCurrent);
utx.commit();
} catch (NotSupportedException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RollbackException e) {
e.printStackTrace();
} catch (HeuristicMixedException e) {
e.printStackTrace();
} catch (HeuristicRollbackException e) {
e.printStackTrace();
}
return Links.OFFERS.getLink();
}
}

这是我的 JSF 页面上的按钮,它调用方法 saveCosts():

<p:commandButton action="#{offerController.saveCosts()}" value="Save" />

什么会导致这个问题,有什么办法可以解决吗?

最佳答案

您尝试合并一个新对象。 EntityManager#merge 仅允许用于现有对象(根据手册:IllegalArgumentException - 如果实例不是实体或者是已删除的实体)。插入必须使用 EntityManager#persist 完成。我怀疑,您更改了代码。所以我不知道原来的问题是什么。

OfferController 是 SessionScoped,你在使用 http-sessions 吗? Offer 必须在 session 开始时插入(使用 persist),并且必须与以后的使用合并。

关于java - 调用与 EntityManager 合并时的 PersistenceException 和 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45455242/

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