简体   繁体   中英

Sqlite JPA Primary Key error

Hello i have a Problem with Sqlite and JPA. I have the following table in Sqlite:

Section:
secID INTEGER Primary Key
secname TEXT

If I use Primary Key in Sqlite this Value will automatically updated when i insert a value like

INSERT INTO Section(secname) VALUES("Default");

In my Java Classes i have the following Class "Section":

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

    @Id
    @Column(name="\"secID\"")
    private int secID;

    @Column(name="\"secname\"")
    private String secname;
    + Getter and Setter
}

The table had by Default two values. If i try to insert a new value in the table with jpa like:

Section sec = new Section();
sec.setSecname("Test2");
tx.begin();
    em.persist(sec);
tx.commit();

it will be inserted with secID = 0. If i then try to insert a new Value i become an Error because at this time the secID = 1 and this secID already exists in the Table because of the two Values that are already in the Table (they have secID = 1 and secID = 2).

How can i avoid this Problem with JPA? I use EclipseLink.

Adding @GeneratedValue(strategy = GenerationType.IDENTITY) on your id mapping should do it.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="\"secID\"")
private int secID;

I don't think your second insert is colliding with the two values ( secID = 1 and 2) already in the table; I think it's colliding with the value you just inserted ( secID = 0).

You aren't explicitly setting secID anywhere, which means it's 0. So it's inserting 0, over and over.

Change the field secID in your class to be an Integer and not an int , and it should behave as the SQLite docs suggest , where, when "you try to insert a NULL into an INTEGER PRIMARY KEY column, the column will actually be filled with an integer that is one greater than the largest key already in the table." (Again, right now you are inserting 0, not null .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM