I have a table generated using liquibase as follows
<createTable tableName="MyTable">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="a" type="VARCHAR(255)"/>
<column name="b" type="VARCHAR(255)"/>
<column name="c" type="BIGINT"/>
<column name="fk_id" type="BIGINT"/>
</createTable>
Then I have a native query that I use to persist this object
EntityManager em = session.getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
em.createNativeQuery(
"INSERT INTO MyTable (a, b, c, fk_id)"
+ " VALUES ( :a, :b, :c, :fk_id)")
.setParameter("a", myObj.geta().toString())
.setParameter("b", myObj.getb().toString())
.setParameter("c", myObj.getc()))
.setParameter("fk_id",
myObj.getOtherObj().getId)
.executeUpdate();
em.getTransaction().commit();
em.close();
I have set the JPA annotation to autoincrement this ID as follows
@Id
@JsonProperty
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
Yet the ID is null in the database, what have I missed? I also tried inserting a null value in place of the primary key but it still does not auto increment it to a value?
Also tried changing it to
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
@Column(name = "id", updatable = false, nullable = false)
private Long id;
That didnt seem to work
Also tried using GenerationType.Table and GenerationType.SEQUENCE
Here is the SQl that I see
Hibernate:
/* dynamic native SQL query */ INSERT
INTO
MyTable
(a, b, c, d, fk_id)
VALUES
(?, ?, ?, ?, ?)
I then log the persisted entity to see if it gets an auto incremented ID
INFO [2019-02-25 16:24:11,611] Successfully persisted myObj: 'null:FK_table{its values} other stuff gets saved'
Notice that the ID column is null.
I also explicitly set the ID to null before executing the query but still no luck I tried executing the same query using a different mysql client and that seems to work