【问题标题】:JPA @Column annotation on getters not working吸气剂上的 JPA @Column 注释不起作用
【发布时间】:2016-01-12 03:48:59
【问题描述】:

这是场景

@Transient
private Map<String, String> choices = null;

@Column(name = "choices", nullable = false)
public String getChoices() {
    return gson.toJson(choices);
}

在插入记录时它说

java.sql.SQLException: 字段 'choices' 没有默认值

我的调试 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

【问题讨论】:

    标签: java mysql spring hibernate jpa


    【解决方案1】:

    在创建表中,您已将选项列标记为不为空。 choices text COLLATE utf8_bin NOT NULL, 因此例外。

    当您保留 Question 实体类时,您不会提供选择的值,因此它们不会包含在生成的 sql 中。要么提供选择的值,要么删除数据库中列上的非空约束。


    注释一个属性javax.persistence.Transient 在JPA 中将其标记为非持久性,并且不会包含在生成的SQL 中。

    【讨论】:

    • 您好 Rohit,感谢您的回复。我有你的cmets。但这里的问题是我希望该列不是 Null,并且这里的插入查询不采用选择字段的值。我正在为选项设置值,但由于某些配置问题,JPA 不接受此字段。请帮助我..
    • 我有一个以地图为参数的二传手。
    • 我不想使用该变量为我的表格字段提供值。相反,我使用 getter 方法将变量的值转换为特定类型并将其提供给 JPA。
    【解决方案2】:

    您可以简单地使用 JPA 注释 @MapKey(请注意,JPA 注释与 Hibernate 不同,Hibernate @MapKey 映射一个包含映射键的数据库列,而 JPA 的注释映射要用作map 的键)。使用映射作为:

    @javax.persistence.MapKey(name = "choices ")
    private Map<String, String> choices = new HashMap<String, String>(); 
    
    public String getChoices() {
        return gson.toJson(choices);
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2011-06-11
    • 2017-01-26
    • 1970-01-01
    相关资源
    最近更新 更多