Total Pageviews

Sunday, 18 March 2012

Get Auto Increment Id after persist

If you have entity marked with annotations @Id and @GeneratedValue(strategy = GenerationType.AUTO), you want get the Id after persist(), then use em.flush().

public int addEmployer(String name) {
        Employer e1 = new Employer();       
        e1.setName(name);
        em.persist(e1);
        em.flush();       
        return e1.getId();
    }

How to persist entity with auto increment Id

when create new entity class from database, if the primary key (for example "Id") with auto increment get annotation @NotNull. At this time, if you use entity manager try to persist an entity, neither set the Id value nor automaticly generate the Id.

Foe Example:

Employer e1 = new Employer();       
e1.setName(name);
em.persist(e1);

The above will get error

In the Employer entity class

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull.-----------------------------------------------------Delete it!!
@Basic(optional = false)
@Column(name = "ID")
private Integer id;

You will  fix the problem.

Saturday, 17 March 2012

Id Auto Increment in Java DB

Using Database Table grab structure  can get the following:

create table "APP".EMPLOYER
(
 ID INTEGER default AUTOINCREMENT: start 1 increment 1 not null primary key,
 NAME VARCHAR(256)
);

but  this can never be run in the SQL command window
To fix the problem, change the above to the following:

CREATE TABLE "APP"."EMPLOYER"
("ID" INT not null primary key         GENERATED ALWAYS AS IDENTITY         (START WITH 1, INCREMENT BY 1),  
"NAME" VARCHAR(256));