Molay
Molay

Reputation: 1404

Spring Data JPA - extends class fields issue

I have a class 'Source' with sourceid field. 'SourceName' class has sourceName field which can be reused for other classes also, so i created a new class instead of repeating this field in each class.

@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);
}

Table: ('sourcename' field cannot be NULL and cannot assign a default value)

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

It's working fine if i keep sourcename field directly under 'Source' class:

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

Getting below error if i keep sourcename in 'SourceName' class. Am i doing anything wrong ?

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

Upvotes: 2

Views: 1919

Answers (1)

You can use annotation javax.persistence.MappedSuperclass on the Super class SourceName and try.

@MappedSuperclass
public class SourceName {
...
}

Upvotes: 4

Related Questions