0

ZK + OpenJPA + Java DB(Derby) insert data got error for auto-increment field

asked 2009-03-31 14:34:44 +0800

kingsz1 gravatar image kingsz1
81 1 3

Hi, i used ZK with OpenJPA to save data into Java DB. But got error when inserting a row with not setting auto-increment field value. this might not a ZK problem, but I just want anyone here can help me sort out this problem.

I create the database table by:

DROP TABLE USERS;

Create TABLE USERS(
  ID INT generated by default as identity PRIMARY KEY,
  NAME VARCHAR(20) NOT NULL,
  LOGINID VARCHAR(20) NOT NULL,
  PASSWORD VARCHAR(32) NOT NULL,
  AGE INT NOT NULL
);

INSERT INTO USERS values(default,'Mr Zhang','Zhang3','zzz333',18);
INSERT INTO USERS values(default,'Mr Lee','Li4','Lii4',28);

In derby use default for the auto-increment field and above code works well to insert the data row.

I created the entity bean by Netbeans as:

@Entity
@Table(name = "USERS")
@NamedQueries({@NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"), @NamedQuery(name = "Users.findById", query = "SELECT u FROM Users u WHERE u.id = :id"), @NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name = :name"), @NamedQuery(name = "Users.findByLoginid", query = "SELECT u FROM Users u WHERE u.loginid = :loginid"), @NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"), @NamedQuery(name = "Users.findByAge", query = "SELECT u FROM Users u WHERE u.age = :age")})
public class Users implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
...

In ZK page, i got componment's value by:

void AddIt()
{
    //get values from zk textbox componments
    Users newUser = new Users ();
    newUser.setName(tbName.value);
    newUser.setLoginid(tbLoginid.value);
    newUser.setPassword(tbPassword.value);
    newUser.setAge(Integer.parseInt(tbAge.value));

    //call to Insert() in controller.java
    ContDAO.Insert(newUser);
}

I was not setting the field "ID" with setter setID(). Actually I had not idea how to set its value for this auto-increment field.

In the controller bean:

    //DAO operations
    public void Insert(Users urs) {
        final EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(urs);
            em.getTransaction().commit();
        } finally {
            em.close();
        }
    }

When run the project, it display error message as:
The field "id" of instance "entity.Users[id=null]" contained a null value; the metadata for this field specifies that nulls are illegal.

Please help for this problem. Thanks a lot.

delete flag offensive retag edit

5 Replies

Sort by » oldest newest

answered 2009-03-31 21:20:47 +0800

terrytornado gravatar image terrytornado flag of Germany
9393 3 7 16
http://www.oxitec.de/

updated 2009-03-31 21:29:06 +0800

@kingsz1,

Try this.

DROP TABLE USERS;

Create TABLE USERS(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT users_pk PRIMARY KEY,
  NAME VARCHAR(20) NOT NULL,
  LOGINID VARCHAR(20) NOT NULL,
  PASSWORD VARCHAR(32) NOT NULL,
  AGE INT NOT NULL
);

INSERT INTO USERS (ID, NAME, LOGINID, PASSWORD, AGE) values(default,'Mr Zhang','Zhang3','zzz333',18);
INSERT INTO USERS (ID, NAME, LOGINID, PASSWORD, AGE) values(default,'Mr Lee','Li4','Lii4',28);

not tested:
------------
in your usersDAOImpl you can do by creating a new USERS object following
that it's not null either pre-initialize.

	@Override
	public Users create() {
		Users users = new Users();
		users.setId(Integer.MIN_VALUE);

		return users;
	}


Stephan

link publish delete flag offensive edit

answered 2009-04-01 10:51:33 +0800

kingsz1 gravatar image kingsz1
81 1 3

Thank you. this way:

users.setId(Integer.MIN_VALUE);

then get error message:

The generated value processing detected an existing value assigned to this field: entity.Users.id. This existing value was either provided via an initializer or by calling the setter method. You either need to remove the @GeneratedValue annotation or modify the code to remove the initializer processing.

link publish delete flag offensive edit

answered 2009-04-01 11:13:41 +0800

terrytornado gravatar image terrytornado flag of Germany
9393 3 7 16
http://www.oxitec.de/

updated 2009-04-01 11:22:08 +0800

Hmmm, sorry more i cannot do. Hope others find a solution.

Cause this problems i'm working not with autoIncrement Fields.
I work with a sequence or PKField table.

Stephan

PS: Have you an initializer ???

link publish delete flag offensive edit

answered 2009-04-01 11:46:56 +0800

kingsz1 gravatar image kingsz1
81 1 3

Thank you again. this way is ok:

Create table:

DROP TABLE USERS;
DROP TABLE OPENJPA_SEQUENCE_TABLE;

CREATE TABLE OPENJPA_SEQUENCE_TABLE (ID SMALLINT NOT NULL, SEQUENCE_VALUE BIGINT, PRIMARY KEY (ID));

Create TABLE USERS(
  ID INT generated by default as identity CONSTRAINT USERS_pk PRIMARY KEY,
  NAME VARCHAR(20) NOT NULL,
  LOGINID VARCHAR(20) NOT NULL,
  PASSWORD VARCHAR(32) NOT NULL,
  AGE INT NOT NULL
);

The entity bean, change little:

// @GeneratedValue(strategy = GenerationType.IDENTITY)
    @GeneratedValue(strategy = GenerationType.AUTO)

DO NOT insert row before running project, otherwise error

>>org.apache.openjpa.persistence.RollbackException: The transaction has been rolled back.  See the nested exceptions for details on the errors that occurred.
>>org.apache.openjpa.persistence.EntityExistsException: The transaction has been rolled back.  See the nested exceptions for details on the errors that occurred.
>>org.apache.openjpa.persistence.EntityExistsException: 语句异常终止,因为它导致“USERS”上所定义的“USERS_PK”标识的唯一或主键约束或唯一索引中出现重复键值。 {prepstmnt 28122412 INSERT INTO USERS (ID, AGE, LOGINID, NAME, PASSWORD) VALUES (?, ?, ?, ?, ?) [params=(int) 1, (int) 12, (String) bbb, (String) aaaa, (String) cc]} [code=-1, state=23505]
[SQL: -1, 23505]

From the message, we know the openjpa handling primary key from 1. Therefore if we insert any row before running the project, it causes the ID field has same value 1 in rows.

I am wondering how to set the openjpa to handle primary key by adding 1 to the last ID value.

link publish delete flag offensive edit

answered 2009-04-01 11:53:53 +0800

terrytornado gravatar image terrytornado flag of Germany
9393 3 7 16
http://www.oxitec.de/

Hmmm, i think Select max(ID) +1 from users

Stephan

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2009-03-31 14:34:44 +0800

Seen: 1,878 times

Last updated: Apr 01 '09

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More