Spring Data JPA - 扩展类字段问题

时间:2018-04-09 06:46:58

标签: hibernate spring-boot jpa spring-data spring-data-jpa

我有一个带有sourceid字段的类'Source'。 'SourceName'类有sourceName字段,也可以重用于其他类,所以我创建了一个新类,而不是在每个类中重复这个字段。

@Entity
@Table(name = "SOURCE")
public class Source extends SourceName{

    @Id
    @Column(name="SOURCEID")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer sourceid;

    public Integer getSourceid() {
        return sourceid;
    }

    public void setSourceid(Integer sourceid) {
        this.sourceid = sourceid;
    }
}

public class SourceName {

    @NotNull
    @Column(name = "SOURCENAME")
    private String sourcename;

    public String getSourcename() {
        return sourcename;
    }
    public void setSourcename(String sourcename) {
        this.sourcename = sourcename;
    }
}

@PostMapping
public ResponseEntity<?> add(@RequestBody SourceName sourceName) {

    Source source = new Source();
    source.setSourcename("somevalue");

    sourceRepository.save(source);

    return new ResponseEntity<>(HttpStatus.CREATED);
}

表:('sourcename'字段不能为NULL且不能指定默认值)

CREATE TABLE `SOURCE` (
  `sourceid` int(11) NOT NULL AUTO_INCREMENT,
  `sourcename` varchar(45) NOT NULL,
  PRIMARY KEY (`sourceid`),
  UNIQUE KEY `sourcename_UNIQUE` (`sourcename`)
) ENGINE=InnoDB

如果我将sourcename字段直接保存在“Source”类下,那么它正常工作:

Hibernate: insert into source (sourcename) values (?)

如果我在“SourceName”类中保留sourcename,则会出现以下错误。我做错了吗?

Hibernate: insert into source values ( )    
SqlExceptionHelper   : Field 'sourcename' doesn't have a default value

1 个答案:

答案 0 :(得分:0)

您可以在超类javax.persistence.MappedSuperclass上使用注释SourceName并尝试。

@MappedSuperclass
public class SourceName {
...
}