views:

1077

answers:

2

Hi.I have a j2ee application using hibernate with annotation. How do I annotate the Id field in my pojo class to set it as auto increment or auto generated. and in adding the bean do I leave that field in my bean null?

+4  A: 
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

In some cases the AUTO strategy is resoved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

It seems SEQUENCE + specifying the sequence name worked for you.

Bozho
my id is of type string. what will i set to it. Because I get this error.Caused by: javax.el.ELException: org.hibernate.exception.SQLGrammarException: could not get next sequence value
cedric
autoincrement means it is a number which is incremented. A String cannot be incremented. Make the column int
Bozho
myid column in the database is of type number. And i already changed my id in my pojo to int. i get the error sequence does not exist
cedric
you didn't say what your database is. Try setting it to IDENTITY, rathen than AUTO.
Bozho
imusing oracle database. when i set it to identity it gives this errorCaused by: org.hibernate.MappingException: Dialect does not support identity key generationHere's my dialect<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
cedric
ok, then try TABLE :)
Bozho
For Oracle, SEQUENCE is the closest thing to autoincrement. You have to create the sequence ahead of time unless you're letting Hibernate generate your schema. If you think you might support multiple databases at some point, use TABLE.
Brian Deterling
Well, in fact, I'm also using Oracle with AUTO and it works like charm
Bozho
Don't use identity, Oracle does not support identity, it supports sequence.
JuanZe
This worked for me... @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="gen_USERS") @SequenceGenerator(name="gen_USERS", sequenceName = "USER_SEQ")@Column(name="ID")
cedric
A: 

I use HSQL.

Pojo:

public class Writer  implements java.io.Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
     private int id;
     private String name;
     private Set books = new HashSet(0);

    public Writer() {
    }

    public Writer(int id) {
        this.id = id;
    }
    public Writer(int id, String name, Set books) {
       this.id = id;
       this.name = name;
       this.books = books;
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public Set getBooks() {
        return this.books;
    }

    public void setBooks(Set books) {
        this.books = books;
    }
}

everithing works well, except when I try to ommit at generated key:

Session session = DbUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Writer w = new Writer();
            w.setId(0);
            w.setName("Auto");
            session.save(w);
            session.getTransaction().commit();

trace:

Hibernate: insert into PUBLIC.PUBLIC.WRITER (NAME, ID) values (?, ?)
Jul 26, 2010 9:36:43 PM org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: -104, SQLState: 23505
Jul 26, 2010 9:36:43 PM org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: integrity constraint violation: unique constraint or index violation; SYS_PK_10027 table: WRITER
Jul 26, 2010 9:36:43 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
        at desktopapplication1.DesktopApplication1View.db(DesktopApplication1View.java:134)
        at desktopapplication1.DesktopApplication1View.<init>(DesktopApplication1View.java:115)
        at desktopapplication1.DesktopApplication1.startup(DesktopApplication1.java:19)
        at org.jdesktop.application.Application$1.run(Application.java:171)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by: java.sql.BatchUpdateException: integrity constraint violation: unique constraint or index violation; SYS_PK_10027 table: WRITER
        at org.hsqldb.jdbc.JDBCPreparedStatement.executeBatch(Unknown Source)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
        ... 19 more
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
        at desktopapplication1.DesktopApplication1View.db(DesktopApplication1View.java:134)
        at desktopapplication1.DesktopApplication1View.<init>(DesktopApplication1View.java:115)
        at desktopapplication1.DesktopApplication1.startup(DesktopApplication1.java:19)
        at org.jdesktop.application.Application$1.run(Application.java:171)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Caused by: java.sql.BatchUpdateException: integrity constraint violation: unique constraint or index violation; SYS_PK_10027 table: WRITER
        at org.hsqldb.jdbc.JDBCPreparedStatement.executeBatch(Unknown Source)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
        ... 19 more

Where am I going wrong?

umpirsky