gpt4 book ai didi

java - 提交前检查重复键?

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:23 25 4
gpt4 key购买 nike

我正在寻找一种解决方案,在使用 JPAContainer 提交 BeanFieldGroup 之前检查重复键。有一些不使用 CriteriaQuery 的解决方案吗?例如,当我执行提交时,有某种方法可以检查 key 是否已存在于数据库中并返回异常?

我正在尝试这个

@Entity
@Table(name="curriculum")
public class Curriculum implements Serializable{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Long idCurriculum;

@Email
@NotEmpty
@NotNull
@Size(max=250)
@Column(unique=true)
private String email;
}

/** BeanFieldGroup */
private final BeanFieldGroup<Curriculum> binder = new BeanFieldGroup<Curriculum>(Curriculum.class);
private final Curriculum bean = new Curriculum();


/** datasources */
private final CustomJPAContainer<Curriculum> datasource = new CustomJPAContainer<Curriculum>(Curriculum.class);


private VerticalLayout buildLayout(){
vLayout = new VerticalLayout();
vLayout.setMargin(true);
vLayout.setSpacing(true);
binder.setItemDataSource(bean);
Field<?> field = null;

//email unique key on database
field = binder.buildAndBind("Email", "email", TextLower.class);
email = (TextLower)binder.getField("email");
email.setWidth("350px");
email.setMaxLength(250);
vLayout.addComponent(email);
return vLayout;

}

@Override
public void buttonClick(ClickEvent event) {
if((event.getButton()) == btnSalvar){
try {
binder.commit();
} catch (CommitException e) {
Notification.show(e.getMessage(),
Type.ERROR_MESSAGE);
}

try {
datasource.addEntity(binder.getItemDataSource().getBean());
} catch(Exception e) {
Notification.show(e.getMessage(),
Type.ERROR_MESSAGE);
return;
}
}

提交后我做: datasource.addEntity(binder.getItemDataSource().getBean());如果 datasource.addEntity() 不起作用并且执行通用异常。

如何在提交之前检查电子邮件字段是否已存在于数据库中而不使用 CriteriaQuery,有办法吗?

有什么想法吗?

最佳答案

这个怎么样(根据Svetlin Zarev的建议):

binder.addCommitHandler(new CommitHandler()
{
@Override
public void preCommit(CommitEvent commitEvent) throws CommitException
{
String email = (String) commitEvent.getFieldBinder().getField("email").getValue();

EntityManager em = /* retrieve your EntityManager */;

List<?> results = em.createQuery("select idCurriculum from Curriculum where email = ?")
.setParameter(1, email)
.getResultList();

if (results.size() > 0)
throw new CommitException("Email already exists");
}

@Override
public void postCommit(CommitEvent commitEvent) throws CommitException { }
});

关于java - 提交前检查重复键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23268048/

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