我有Spring boot 1.4.3 + Hibernate 5.0.11 + H2数据库。 当我尝试将@UniqueConstraint与某些值一起使用时,我的应用程序启动失败。就这个。响应类用@UniqueConstraint标记,其中包含columnNames" survey"和"用户"
@Entity
@Table(name = "responses", uniqueConstraints = {@UniqueConstraint(columnNames = {"survey, user"}, name = "responses_survey_user_idx")})
public class Response extends BaseEntity
{
@NotNull
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "survey", nullable = false)
private Survey survey;
@NotNull
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "user", nullable = false)
private User user;
@NotNull
private String answers;// json serialized
}
调查班:
@Entity
@Table(name = "surveys", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"}, name = "surveys_name_idx")})
public class Survey extends BaseEntity{
@NotNull
@SafeHtml
@Length(min = 3)
private String name;
@NotNull
@SafeHtml
@Length(min = 3)
private String description;
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "survey")
private List<Response> responses;
}
用户类:
@Entity
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = "login", name = "users_unique_email_idx")})
public class User extends BaseEntity {
@NotEmpty
@SafeHtml
private String login;
@NotEmpty
@Length(min = 8)
@SafeHtml
private String password;
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "user")
private List<Response> responses;
}
我得到的错误是:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to create unique key constraint (survey, user) on table responses: database column 'survey, user' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
我试图在Response类中更改列的名称,但它没有帮助。 它只在我在这个类中删除@UniqueConstraint时才有效。
有任何想法如何解决这个问题?
答案 0 :(得分:2)
唯一约束中的列名不应以逗号分隔,而应在数组中单独使用String值(请参阅http://docs.oracle.com/javaee/6/api/javax/persistence/UniqueConstraint.html):
@Table(
name="EMPLOYEE",
uniqueConstraints=
@UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})
)