简体   繁体   中英

Hibernate mapping with ID generated by DB trigger + sequence

everyone. I've a LOG table with a combination of trigger and sequence to create the id, so when I insert the line I do not have to specify the id, otherwise the database returns error. However Hibernate claims (rightly) that was specified primary key.

What kind of "generator" property should I use in this case?

I already tried " assigned " it says:

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save (): it.m2sc.simulator.beans.Log

With " select " hib ask me the natural key, but there is no natural key in this table, but the primary.

org.hibernate.id.IdentifierGenerationException: no natural-id property defined; need to specify [key] in generator parameters

That's my hbm

<hibernate-mapping>
    <class name="it.m2sc.simulator.beans.Log" table="LOG">
        <id name="id" type="integer" column="LOG_ID" access="field">
            <generator class="select" /> 
        </id>
        <property name="date" type="date" column="LOG_DATE" access="field" />
        <property name="user" type="string" column="LOG_USER" access="field" />
        <property name="evtId" type="integer" column="EVT_ID" access="field" />
        <property name="detail" type="string" column="LOG_DETAIL" access="field" />
        <property name="deleted" type="character" column="LOG_DELETED" access="field" />
        <property name="codiceRaggruppamento" column="LOG_CODICE_RAGGRUPPAMENTO" type="string" access="field" />
    </class>
</hibernate-mapping>

The Class

public class Log {
    private Integer id;
    private Date date;
    private String user;
    private Integer evtId;
    private String detail;
    private Character deleted = '0';
    private String codiceRaggruppamento;

    ... ( getter & setter )
}

DDL of table/trigger/sequence

CREATE TABLE
    LOG
    (
        LOG_ID NUMBER(12) NOT NULL,
        LOG_DATE TIMESTAMP(6),
        LOG_USER VARCHAR2(50),
        EVT_ID NUMBER(12),
        LOG_DETAIL VARCHAR2(100),
        LOG_DELETED CHAR(1) DEFAULT '0 ' NOT NULL,
        LOG_CODICE_RAGGRUPPAMENTO NCHAR(2) NOT NULL,
        CONSTRAINT LOG_PK PRIMARY KEY (LOG_ID),
        CONSTRAINT LOG_CFG_EVENT_TYPE_FK1 FOREIGN KEY (EVT_ID)
        REFERENCES CFG_EVENT_TYPE (EVT_ID)
    );

   CREATE SEQUENCE  LOG_SEQ  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 358 CACHE 20 NOORDER  NOCYCLE;

CREATE OR REPLACE TRIGGER "DTCUSR"."LOG_TRG" BEFORE INSERT ON LOG
FOR EACH ROW
BEGIN
  <<COLUMN_SEQUENCES>>
  BEGIN
    IF :NEW.LOG_ID IS NULL THEN
      SELECT LOG_SEQ.NEXTVAL INTO :NEW.LOG_ID FROM DUAL;
    END IF;
  END COLUMN_SEQUENCES;
END;

Ah, just fyi: db is Oracle11

Ty in advice

sequence-identity id generation strategy embeds sequence call directly in the insert statement:

insert into log (log_id, log_date, log_user, ...)
values (LOG_SEQ.nextval, ?, ?, ...)

This way you can get rid of the trigger because it's not needed.

Also, you have to set hibernate.jdbc.use_get_generated_keys property to true , so that Hibernate reads the generated keys after executing insert statements.

In hbm.xml:

<id name="id" type="integer" column="LOG_ID" access="field">
  <generator class="sequence-identity" >
    <param name="sequence">LOG_SEQ</param>
  </generator>
</id>

With annotations:

@Entity
@Table(name = "LOG")
public class Log {
  @Id
  @org.hibernate.annotations.GenericGenerator(name="logSequenceGenerator", strategy = "sequence-identity",
    parameters = {@org.hibernate.annotations.Parameter(name="sequence", value="LOG_SEQ")})
  @GeneratedValue(generator = "logSequenceGenerator")
  @Column(name = "LOG_ID")
  private Integer id;
  ...
}

Take a look at this link explaining how to use a trigger based generator.

Additionaly, remember to use the hibernate.jdbc.use_get_generated_keys property in your Hibernate persistence configuration

<property name="hibernate.jdbc.use_get_generated_keys" value="true" />

Probably you will get an NullPointerException while inserting using the class described on the link. Change the method executeAndExtract(PreparedStatement insert, SessionImplementor session) to anything like this

    @Override
    protected Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session)  throws SQLException {

        insert.executeUpdate();

        try {

            ResultSet rs = insert.getGeneratedKeys();
            rs.next();

            return rs.getLong(1);

        } catch (RuntimeException rt) {
            throw new SQLException("Error while attempt to use the CustomTriggerGenerator. Check the <property name=\"hibernate.jdbc.use_get_generated_keys\" value=\"true\" /> in your persistence.xml");      
        }

    }

Hibernate doc is really clear on different generation mechanism available. Depending on how data will be written one should make a call:

For simple use cases you might use sequence , but there are several more options available.

Refer: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-id

If you want your ID to be generated only in database and just read by hibernate you can use parameters 'insertable' and 'updatable' in @Column annotation:

@Column(name = "LOG_ID", insertable=false, updatable=false)
private Integer id;

With this parameters hibernate will not add the id column to inserts and updates.

To achieve the goal you need to use GenerationType.IDENTITY

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "LOG_ID", updatable = false, nullable = false)
private Integer id;

See more on https://www.thoughts-on-java.org/jpa-generate-primary-keys/

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