如何用生成的ID检查记录的唯一性?

时间:2020-04-11 22:19:28

标签: java hibernate hashmap hql

我有课:

#navigating to search page
 try :
        elem4 = driver.find_element_by_xpath("//input[@type='checkbox']")
        elem4.click()
        time.sleep(15)

        elem5 = driver.find_element_by_xpath("//button[@type='submit']")
        elem5.click()
        time.sleep(15)

    except:
          pass

    try:
        elem = driver.find_element_by_id('filter-spc')
        elem.click()
    except:
          pass

如您所见,ID已生成,但是记录的唯一性必须由其他字段检查。为此,我使用HQL:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private int passport;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return passport == user.passport &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, passport);
    }
}

我如何应用集合来检查记录的唯一性?

1 个答案:

答案 0 :(得分:3)

您可以在字段passportname上添加唯一约束。 为此,您可以将这一行添加到类定义上方

@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })

所以会是这样:

@Entity
@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
public class User {
...