JPA唯一属性未呈现

时间:2015-03-10 10:35:24

标签: java hibernate jpa

我有一个简单的pojo,其email属性在数据库表中应该是唯一的:

@Entity
public class Customers implements Serializable {
@Id
@GeneratedValue
private Integer cID;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String password;

//getters/setters/constructors
...
}

这是jsf表单bean:

@ManagedBean
@SessionScoped
public class RegistrationBean implements Serializable {

private String username;
private String password;
private String email;

//getters/setters

public String registeration() {
    Customers newCustomer = new Customers(email, username, password);
    CustomerService customerService = new CustomerService();
    if (customerService.persistCustomer(newCustomer) == true) {
        return "Succ?faces-redirect=true";
    }
    return "fail?faces-redirect=true";
   }
}

这是我的form

enter image description here

(按钮操作是registeration()

但我尝试了两次相同的email s,并且存储成功!

enter image description here

为什么它不显示有关相同email的任何错误?

2 个答案:

答案 0 :(得分:1)

@Column(unique = true)会导致JPA-Implementations在自动创建表时在数据库列上创建唯一约束。 如果在创建表后添加此Annotation参数,则它不起作用。您可能希望手动将唯一约束添加到列中,或者让JPA-Implementation重新创建表。

答案 1 :(得分:-1)

试试这个

@Entity
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"EMAIL"}))
public class Customers implements Serializable {
...