这就是场景
@Transient
private Map<String, String> choices = null;
@Column(name = "choices", nullable = false)
public String getChoices() {
return gson.toJson(choices);
}
插入记录时显示
java.sql.SQLException: Field 'choices' doesn't have a default value
我的调试 SQL
DEBUG SQL:109 -
insert
into
question
(description, id)
values
(?, ?)
此处选项字段被忽略。
数据库详细信息:
CREATE TABLE `question` (<br/>
`id` varchar(50) COLLATE utf8_bin NOT NULL,<br/>
`description` varchar(1000) COLLATE utf8_bin NOT NULL,<br/>
`choices` text COLLATE utf8_bin NOT NULL,<br/>
`answers` varchar(100) COLLATE utf8_bin NOT NULL<br/>
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;<br/>
<br/>
ALTER TABLE `question`<br/>
ADD PRIMARY KEY (`id`);<br/>
有人可以帮助我为什么这些字段被忽略吗? 谢谢。
[更新] 实体类:
@Entity
@Table(name = "question")
public class Question {
@Id
private String id = null;
@Column(name = "description", nullable = false)
private String description = null;
@Transient
@Column(name = "choices", nullable = false)
private Map<String, String> choices = null;
public String getChoices() {
return gson.toJson(choices);
}
@Transient
private Set<String> answers = null;
@Transient
private Gson gson = new GsonBuilder().create();
public Question() {
this.id = UUID.randomUUID().toString();
}
...
}//End of class
最佳答案
在创建表中,您已将选择列标记为不为空。 选择文本 COLLATE utf8_bin NOT NULL,
因此出现异常。
当您保留 Question 实体类时,您不提供选项值,因此它们不会包含在生成的 sql 中。要么提供选择值,要么删除数据库中列的非空约束。
<小时/>注释属性javax.persistence.Transient
将其标记为JPA中的非持久性,并且不会包含在生成的SQL中。
关于java - JPA @Column 注释 getter 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735271/