如何使用生成的 id 检查记录的唯一性?
How to check the uniqueness of a record with the generated id?
我有一个class:
@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);
}
}
可以看到,id生成了,但是记录的唯一性还得通过其他字段校验。为此,我使用 HQL:
Query query = session.createQuery("from Pilot where name:=name and passport=:passport");
如何应用集合来检查记录的唯一性?
您可以在字段 passport
和 name
上添加唯一约束。
为此,您可以将此行添加到 class 定义
上方
@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
所以会变成这样:
@Entity
@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
public class User {
...
我有一个class:
@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);
}
}
可以看到,id生成了,但是记录的唯一性还得通过其他字段校验。为此,我使用 HQL:
Query query = session.createQuery("from Pilot where name:=name and passport=:passport");
如何应用集合来检查记录的唯一性?
您可以在字段 passport
和 name
上添加唯一约束。
为此,您可以将此行添加到 class 定义
@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
所以会变成这样:
@Entity
@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "passport" }) })
public class User {
...