Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate Custom Id in JPA

i want generate Custom Id in JPA it must be primary key of table. there are many examples to create Custom Id using hibernate like this i want same implementation but in JPA.The id must be alphanumeric like STAND0001

Thanks.

like image 281
Amol Raje Avatar asked Nov 13 '17 07:11

Amol Raje


People also ask

How would you implement a custom sequence based id generator?

If you want to use a custom generator, you need to define the generator in a @GenericGenerator annotation and provide the fully-qualified classname as the strategy. You can also configure a set of parameters that will be provided to the configure method when Hibernate instantiates the generator.

What is @EmbeddedId in JPA?

Annotation Type EmbeddedIdApplied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated as Embeddable .

Is @ID mandatory in JPA?

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the "Jpa Id" is the combination of all columns.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.


1 Answers

You can do it using GenericGenerator like this :

 @Entity
public class Client {

    @Id
    @GenericGenerator(name = "client_id", strategy = "com.eframe.model.generator.ClientIdGenerator")
    @GeneratedValue(generator = "client_id")  
    @Column(name="client_id")
    private String clientId;
}

and the custom generator class (will add prefix to the ID, you can make it do what you like):

public class ClientIdGenerator implements IdentifierGenerator {

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

    String prefix = "cli";
    Connection connection = session.connection();

    try {
        Statement statement=connection.createStatement();

        ResultSet rs=statement.executeQuery("select count(client_id) as Id from Client");

        if(rs.next())
        {
            int id=rs.getInt(1)+101;
            String generatedId = prefix + new Integer(id).toString();
            return generatedId;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}
}
like image 53
Bara' ayyash Avatar answered Oct 04 '22 19:10

Bara' ayyash