Description
untuk penjelasan lengkapnya tentang contraints bisa dibaca disini , disini hanya akan sharing bagaimana cara membuat unique constraints di JPA.
How To
Disni saya akan mencontohkan membuat sebuath entity Person
public class Person implements Serializable { private Long id; private String name; private String password; private String email; private Long personNumber; private Boolean isActive; private String securityNumber; private String departmentCode; private Address address; //getters and setters }
1. Single Column
untuk single column kita bisa menggunakan @Column(unique=true) atau @UniqueConstraint, umunya orang lebih banyak pakai @Colunm(unique=true) karna lebih mudah dan jarang pakai @UniqueConstraint, biasanya dipakai untuk multiple unique.
public class Person implements Serializable { private Long id;
@Column(unique=true) private String name;
// other fields
}
2. Multiple Column
untuk multiple column kita menggunakan @UniqueContraint.
uniqueConstraints = {
@UniqueConstraint(name = "UniqueNumberAndAddress", columnNames = { "person_number", "address_id" }),
@UniqueConstraint(name = "UniqueNameAndEmail", columnNames = {"name", "email"})
})
public class Person implements Serializable { private Long id;
@Column(name="name")
private String name;
@Column(name="email")
private String email;
@Column(name="person_number")
private Long personNumber;
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;}
Komentar
Posting Komentar