java - 检测 Hibernate 中的重复行

标签 java hibernate

我将检查数据库中不存在的电子邮件,然后使用其他属性存储该行。

这是我的代码,可以检测重复的email值:

public boolean exists(String value) {
    customerDao.openSessionWithTransaction();
    Query query = customerDao.openSession().createQuery("from Customers where email=? ");
    query.setString(0, value);
    if (query.getFirstResult() != null) {
        return true;
    }
    return false;
}

getFirstResult() 始终返回 null,即使我检查重复的 email 值也是如此。

我已向 pojo 类声明了 uniuness 注释。

这是我的表格:

enter image description here

当我检查重复的电子邮件值时,只会发生 ConstraintViolationException

最佳答案

您可能需要这个:

public boolean exists(String value) {
    customerDao.openSessionWithTransaction();
    Query query = customerDao.openSession().createQuery("from Customers where email=? ");
    query.setString(0, value);
    if (query.uniqueResult()!= null) {
        return true;
    }
    return false;}

关于java - 检测 Hibernate 中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974689/

相关文章:

java - 如何在Java程序中启用和禁用KEY_WOW64_32KEY

java - 输入文本后如何从文本字段(密码)检索文本

java - java注释如何与spring一起工作,它们是在运行时还是在启动时扫描的?

java - Hibernate Session#merge 在收到带有 ID 的实体时是否应该插入?

java - 使用 JIT 编译器的 Collections.emptyList 和空 ArrayList 的性能

java - Eclipse 错误日志记录 - 由于从 GIT 导入而未显示?

java - Oracle 序列不会从 Java/Hibernate 递增

java - 失败 : alter table add constraint: Table doesn't exist on create

hibernate - 延迟加载在带有 Hibernate 的 JPA 中不起作用

java - JSF + hibernate : Collection is not associated with any session