提交前检查重复密钥?

时间:2014-04-24 11:49:14

标签: java jpa vaadin7

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

我正在尝试这个

@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;
        }
    }

在make commit之后我做了:datasource.addEntity(binder.getItemDataSource()。getBean());如果datasource.addEntity()不起作用并执行一般的异常。

如何在不使用CriteriaQuery的情况下检查数据库中是否已存在电子邮件字段,有没有办法?

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这个怎么样(根据 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 { }
});

答案 1 :(得分:0)

将您的数据库更改为具有唯一索引。当您尝试插入重复数据时,它将引发异常。