设置ID生成器注释

时间:2015-07-31 22:59:19

标签: java spring hibernate jpa

在我的应用程序中(使用xml映射)我有一个PK / ID生成器类。此类实现IdentifierGenerator,Configurable。此类存储所有实体ID。

我正在实现JPA,我想在我的Entity上使用注释来设置特定的id生成器类。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

为了解决我的请求,我使用了GenericGenerator

使用@GenericGenerator @id和PK Generator类的参数设置实体。我在策略中通过了PK Generator类

@Entity @Table(name="UTILISATEUR")
public class UtilisateurEntity implements Serializable {
    private static final long serialVersionUID = -3416450676331189345L;

    @Id @GenericGenerator(name="entityIGenerator", strategy="com.prima.solutions.primaclaims.core.dao.impl.PkGenerator", 
                          parameters={@Parameter(name=PkGenerator.TABLE, value="SEQUENCE"),
                                      @Parameter(name=PkGenerator.PK_COLUMN_VALUE, value="UTILISATEUR"),
                                      @Parameter(name=PkGenerator.VALUE_COLUMN_NAME, value="NUMERO")
                          })
    @GeneratedValue(generator="entityIGenerator")
    private Integer pk;

    @Column(name="NOM") private String nom;
    @Column(name="PRENOM") private String prenom;
    @Column(name="IDENTIFIANT") private String identifiant;
    @Column(name="NOM_AFFICHAGE") private String nomAffichage;
    @Column(name="TELEPHONE") private String telephone;
    @Column(name="FAX") private String fax;
    @Column(name="MAIL") private String mail;
    @Column(name="DATE_CREATION") private Date dateCreation;
    @Column(name="DATE_MISE_A_JOUR") private Date dateMAJ;


    public Integer getPk() {
        return pk;
    }
    public void setPk(Integer pk) {
        this.pk = pk;
    }
.....
}

这是PK Generator类:

public class PkGenerator implements IdentifierGenerator, Configurable {

    public static final String TABLE = "table";
    public static final String PK_COLUMN_NAME = "primary_key_column";
    public static final String PK_COLUMN_VALUE = "primary_key_value";
    public static final String VALUE_COLUMN_NAME = "value_column";
    public static final String PK_LENGTH_NAME = "primary_key_length";
    public static final Integer DEFAULT_PK_LENGTH = 64;

    // Valeurs par defaut
    public static final String DEFAULT_TABLE = "SEQUENCE";
    private static final String DEFAULT_PK_COLUMN = "SEQUENCE_NAME";
    private static final String DEFAULT_VALUE_COLUMN = "SEQUENCE_NEXT_VALUE";


// Membres

    private String tableName;
    private String pkColumnName;
    private String pkValueName;
    private String valueColumnName;
    private String query;
    private String selectLock;
    private String insert;
    private String update;
    private int keySize;


    /**
     * @return Object 
     */
    public Object generatorKey() {
        return tableName;
    }


    @Override
       public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {



       Connection connection = session.connection();
       Integer pk = null, rows=null;
       PreparedStatement selectStatement =null;
       PreparedStatement insertStatement = null;
       PreparedStatement updateStatement = null;
             try {
                    // Recherhe du dernier ID connu de l objet dans la table SEQUENCE
                    selectStatement = connection.prepareStatement(this.query);
                    ResultSet resultSet = selectStatement.executeQuery();

                    // Sequence existe
                    if( resultSet!=null && resultSet.next()) {
                          pk = resultSet.getInt("NUMERO");
                          resultSet.close();
                    } else {
               // Sequence non trouvee : on fait un insert
                   pk = 0;
                    insertStatement = connection.prepareStatement(this.insert);
                    insertStatement.execute();
                    }

                    // Sequence update
                    pk = pk + 1;
                    updateStatement = connection.prepareStatement(this.update);
                    updateStatement.setInt(1, pk.intValue());
                    rows = updateStatement.executeUpdate();
             } catch (SQLException e) {
                    throw new HibernateException(e);
             } catch (Exception e) {
                    throw new HibernateException(e);
             } finally {
                    try {
                          if( selectStatement!=null ) {
                                 selectStatement.close();
                          }
                          if( insertStatement!=null ) {
                                 insertStatement.close();
                          }
                          if( updateStatement!=null ) {
                                 updateStatement.close();
                          }
                    } catch (SQLException e) {
                          throw new HibernateException(e);
                    }
             }

             return new Integer(pk);
       }

       @Override
       public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
        this.tableName = params.getProperty(TABLE, DEFAULT_TABLE);
        this.pkColumnName = params.getProperty(PK_COLUMN_NAME, DEFAULT_PK_COLUMN);
        this.pkValueName = params.getProperty(PK_COLUMN_VALUE);
        this.valueColumnName = params.getProperty(VALUE_COLUMN_NAME, DEFAULT_VALUE_COLUMN);
        this.keySize = ConfigurationHelper.getInt(PK_LENGTH_NAME, params, DEFAULT_PK_LENGTH);

        // select NUMERO from SEQUENCE with (updlock, rowlock) where ENTITE = '<TABLE>'
        this.query = "select " + this.valueColumnName + " from " +  this.tableName
                       + " where " + this.pkColumnName + " = '" + this.pkValueName + "'" + dialect.getForUpdateString();

        this.selectLock = "select " + this.valueColumnName + " from " + dialect.appendLockHint(LockOptions.UPGRADE, this.tableName) 
                + " where " + this.pkColumnName + " = '" + this.pkValueName + "'" + dialect.getForUpdateString();

        // update SEQUENCE set NUMERO = ? where ENTITE = '<TABLE>'
        this.update = "update " + this.tableName + " set " + this.valueColumnName + " = ? "
                          + "where " + this.pkColumnName + " = '" + this.pkValueName + "'";
        // insert into SEQUENCE(ENTITE, NUMERO) values('<keyValue>', 0)
        this.insert = "insert into " + tableName + "(" + pkColumnName + ", " + valueColumnName + ") " + "values('" + pkValueName + "', 0)";
    }

}