【发布时间】:2018-10-20 04:11:21
【问题描述】:
当我尝试使用 POST REST API 持久化数据时出现 .ConstraintViolationException。
原因:org.postgresql.util.PSQLException:错误:“id”列中的空值违反非空约束 详细信息:失败行包含(null,John Doe,你好吗?,我很好)。
我正在使用 @GeneratedValue(strategy = GenerationType.IDENTITY) 从 Hibernate 自动生成“id”,我不确定是否缺少 application.properties 中的任何配置。我正在使用 Postgres 数据库。
我尝试使用 GenerationType.AUTO,但我从 postgres 收到 hibernate_sequence missing 错误。
谢谢!
使用 Postman POST REST API 输入
{
"personName": "John Doe",
"question": "How are you?",
"response": "I am fine"
}
questionnaries.sql
CREATE TABLE questionnaries(
id BIGINT PRIMARY KEY,
personName VARCHAR(255) NOT NULL,
question VARCHAR(255) NOT NULL,
response VARCHAR(255) NOT NULL
);
Questionnarie.java #
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "questionnaries")
public class Questionnarie {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "personname")
@NotNull
private String personname;
@Column(name = "question")
@NotNull
private String question;
@Column(name = "response")
@NotNull
private String response;
public Questionnarie() {}
public Questionnarie(@NotNull String personname, @NotNull String question, @NotNull String response) {
super();
this.personname = personname;
this.question = question;
this.response = response;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPersonname() {
return personname;
}
public void setPersonname(String personname) {
this.personname = personname;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}}
application.properties
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.jndi-name=java:jboss/datasources/test_data_source
# ===============================
# = JPA / HIBERNATE
# ===============================
# Show or not log for each sql query
spring.jpa.show-sql=true
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
【问题讨论】:
标签: java postgresql hibernate spring-boot jpa