gpt4 book ai didi

java - @UniqueConstraint 的 Spring boot/Hibernate 问题

转载 作者:行者123 更新时间:2023-11-30 02:40:22 24 4
gpt4 key购买 nike

我有 Spring boot 1.4.3 + Hibernate 5.0.11 + H2 数据库。当我尝试将 @UniqueConstraint 与某些值一起使用时,我的应用程序启动失败。就这个。响应类用 @UniqueConstraint 标记,列名称为“调查”和“用户”

@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 时,它才起作用。

有什么想法可以处理这个问题吗?

最佳答案

唯一约束中的列名称不应以逗号分隔,而应以数组中的分隔字符串值(请参阅 http://docs.oracle.com/javaee/6/api/javax/persistence/UniqueConstraint.html ):

@Table(
name="EMPLOYEE",
uniqueConstraints=
@UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})
)

关于java - @UniqueConstraint 的 Spring boot/Hibernate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41932173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com