Wednesday, September 24, 2008

XDoclet Serial Type Mapping

I was in mistake, I did the wrong way to get the id in a table which is Long and always increment in oracle
such as from table APP_USER.

Wrong Way I:
- I create sequence in the schema, for example for APP_USER:
CREATE SEQUENCE "SCHEMANAME"."SEQ_APP_USER_ID" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 30 NOORDER NOCYCLE ;

- I create trigger before insert, in which it will increment if the ID is null
create or replace TRIGGER BI_APP_USER
before insert on APP_USER
for each row
begin
if :new.id is null
then select SEQ_APP_USER_ID.nextval into :NEW.ID from dual;
end if;
end;

- And in the pojo, the getter of the ID, is like this:
/**
* @return Returns the id.
* @hibernate.id column="ID" unsaved-value="null"
* @hibernate.generator class="increment"
*/
public Long getId() {
return id;
}

and belive it or not I got this way from browse the net, sadly I didn't save the address, it's from such a forum I think.

I did this method for some of my pojos, and few of them didn't work, I don't know why, in case it need tobe fixed fast, so I use another way,

Wrong Way II:
- Simply it check the maximum value of the id, and then I increment it before insert.
- I add method to get the maximum id of the table, in the DaoHibernate seems like this
@Override
public Long getMaxId() {
Long maxId = (Long) getSession().createQuery("select max(id) from LogTable ").uniqueResult();
return maxId;
}
- And offcourse the insert code just like below:
public void saveLogTable(final LogTable logTable) {
if (logTable.getId() == null) logTable.setId(getMaxId() + 1);
getHibernateTemplate().saveOrUpdate(logTable);
getHibernateTemplate().flush();
}
- And the getter of the pojo is like this:
/**
* @return Returns the id.
* @hibernate.id column="ID"
* @hibernate.generator class="assigned"
*/
public Long getId() {
return id;
}

- It doesn't need to create sequencial, but offcourse it consume resource because it count the record first.

Thanks for fellow in front of mine, that give me information how to do it right for getting the id before inserting:

The Right Way is over here:
- It only need to create the sequence same as the first way
- The pojo looks like this:
/**
* @hibernate.id column="ID" not-null="true" unique="true" type="long"
* @hibernate.generator class="sequence"
* @hibernate.param name="sequence" value="SEQ_APP_USER_ID"
*/
public Long getId() {
return id;
}

just that, and it's very simple way!!

No comments: