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.
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.
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 .
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.
@Column annotation is used for Adding the column the name in the table of a particular MySQL database.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With