This really seems like a simple problem, but I can't find any solutions posted anywhere.
The basic gist is that I have a Derby(10.4.2.1) database that contains a table with a primary key that is an IDENTITY. I then create a JPA annotated class to represent that table and try to insert it into the table via an EntityManager.persist. I get a failure "Attempt to modify an identity column". Does anyone know what I'm doing wrong/how to get around this?
createTable.sql
Code:
CREATE TABLE JUNKS (
JUNK_ID BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY,
JUNK_NAME VARCHAR(50) NOT NULL,
CONSTRAINT PK_JUNKS PRIMARY KEY (JUNK_ID)
);
Junk.java
Code:
package com.xxx.peristence.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
*/
@Entity(name="Junks")
@Table(name="JUNKS")
public class Junk {
private long id;
private String name;
public Junk() { }
public Junk(long id, String name) {
this.id = id;
this.name = name;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="JUNK_ID", nullable=false, insertable=true, updatable=false)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
@Column(name="JUNK_NAME", length=50, nullable=false)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
JunkTest.java
Code:
package com.xxx.peristence.model;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.junit.Test;
public class JunkTest {
@Test
public void test1() throws Exception {
EntityManager em = Persistence.createEntityManagerFactory("TestConfigurationManagement-ejbPU").createEntityManager();
em.getTransaction().begin();
Junk j = new Junk(0L, "ttttt");
em.persist(j);
em.getTransaction().rollback();
}
}
persistence.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="TestConfigurationManagement-ejbPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/configurationManagement"/>
<property name="hibernate.connection.username" value="admin"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>