0

I am using Spring 4 and have the following set up for my data model:

@Entity
@Table(name ="InstanceData")
public class InstanceData {

    private Long instanceDataId;
    private Long heapUsed; //in bytes
    private Long heapMax; //in bytes


    @Id
    @Column(name="InstanceDataId")
    @SequenceGenerator(name="DataSeq", sequenceName="DATA_SEQ")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="DataSeq")
    public Long getInstanceDataId() {
        return instanceDataId;
    }

    public void setInstanceDataId(Long id) {
        this.instanceDataId = id;
    }

    @Column(name="HeapUsed")
    public Long getHeapUsed() {
        return this.heapUsed;
    }
    public void setHeapUsed(Long heapUsed) {
        this.heapUsed = heapUsed;
    }

    @Column(name="HeapMax")
    public Long getHeapMax() {
        return this.heapMax;
    }
    public void setHeapMax(Long heapMax) {
        this.heapMax = heapMax;
    }

I let Hibernate create the schema automatically. I then try the following SQL (on the H2 db):

insert into instance_data (heap_used, heap_max) values (100, 100);

The error I get is: Error: NULL not allowed for column "INSTANCE_DATA_ID"; SQLState: 23502

My question is why doesn't it auto generate the primary key? How should I change my data model configuration so that the primary key is auto generated (starting at 1)? Thanks for your help.

I would like to understand why even though I am using the @GeneratedValue annotation, the primary key is not auto generated.

2 Answers2

0

Why are you using raw SQL? Just create a new object of class InstanceData, set fields heapUsed and heapMax and use Hibernate's save() method. Then id would be generated automatically.

Rafał P
  • 252
  • 1
  • 8
  • Right, I can do that from my app. But I would like pre-populate the db with initial values for testing and want to do it externally. My concern is when Hibernate creates the schema, it doesn't create it properly with the primary key being set to auto-increment. – Maciek Nicewicz Dec 03 '15 at 21:17
0

Annotate id getter like this

@Id
@Column(name="InstanceDataId")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getInstanceDataId() {
    return instanceDataId;
}

and if you dont want to create raw sql scheme you can build up something similar to this (ofcourse it works only using inmemory db)

@Component
@Transactional
public class DummyDbCreator {

    private SomeService someService;

    @Autowired
    public DummyDbCreator(SomeService someService) {
        this.someService = someService;
    }

    @PostConstruct
    public void initialInserts() {
         Some some = new Some();
         // some more entites
         // ...
         // and other entites
         someService.save(some);
    }
}

Add this class to some component scanned package or just declare it as a bean in your configuration

Oskar Dajnowicz
  • 1,700
  • 12
  • 16