2

Hello I have a Problem with JPA and SQLite.

I have a table called Category in SQLite. This is the Structur of this table:

Category:
catID INTEGER Primary Key
catName TEXT

Now i'm trying to insert a new Category via JPA. This is my method to do this:

public void insertCategory(EntityManager em, String catName) {
    Category cat = new Category();
    cat.setCatName(catName);
    em.getTransaction().begin();
        em.persist(cat);
        em.flush();
    em.getTransaction().commit();
}

Now I have an Execption at em.flush(). The Exception says

Null or zero primary key encountered in UnitOfWork clone

I know this happens because of the Object cat. The catID is still null. The class looks like:

@Entity
@Table(name="Category")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="catName")
    private String catName;

    @Id
    @Column(name="catID")
    private Integer catID;
    + Getter and Setter
}

SQLite increments the Primary Key automatically when not given in the query. How can i inform my Program about the Primary Key to run without getting this Exception??

Kevin
  • 785
  • 2
  • 10
  • 32

1 Answers1

1

Thank you Mick Mnemonic for your help. The last answer you give helped me. I had to generate my database new and add the autoincrement Argument to my Primary Keys. Then the sqlite_sequence Table was generated. Now i can insert Entitys in my database via JPA without getting any Exception.

This is my Generator Annotation:

@GeneratedValue(generator="sqlite")
@TableGenerator(name="sqlite", table="sqlite_sequence", 
                pkColumnName = "name", valueColumnName = "seq",
                pkColumnValue = "Section", initialValue = 1,
                allocationSize = 1)

the last two Arguments are necessary because jpa seems to add +50 to the value in the sqlite_seq table and SQLite begins the Autoincrement value at 1.

Kevin
  • 785
  • 2
  • 10
  • 32
  • I wanted to stop by to say thanks as this help me solve an issue I always having on my Java project. I'd recommend postings a revision to this with a sample entity so that other users who come after we'll see where these annotations are supposed to go. – Cody Nov 08 '18 at 13:53