Hibernate to initialize a table and use a String as ID and Primary Key (a hash value that I supply)?

I’ve read this question :

And I was wondering if I want Hibernate to crate the database table and name it and the columns, at the same time I want the primary key to be a hash value (as a String) that I generate at run time.

would something like the answer for the above question work?

@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "RequestID")
private Reqeust request;

Hope you can provide some guidance or point me to a reliable resource?

thanks

PS: also looked at : Using a oracle sequence on non primary key

1 Like

Try to elaborate that part since it’s not clear what you are asking.

thanks for looking,
So the values I’m starting with are:

  • A unique string
  • The hash value of the string, but String.valueOf(str.hashCode())
    the hash is generated at runtime and converted to a string

So when I run the application for the first time, I want Hibernate to start off creating the table and the columns,
define the primary key to be the string hash value.

What annotations do I need to add to the entity to achieve that?

thanks again

What annotations do I need to add to the entity to achieve that?

You don’t need an annotation to do that. You might achieve what you want by customizing the PhysicalNamingStrategy.

Ok, just to be sure, the link describes how to achieve the following?
When I first run the app, new (blank) database Hibernate will have a table built (according to the annotations in the entity) the table would get a column id and a column item

Table Items


| ID (varchar) | ITEM (varchar) |


and then I can populate the table with the string and the string hash as the ID, as follows:


| ID (varchar) | ITEM (varchar) |


| 8765456 | item number 1 |

| 5678987 | item number 2 |

| 3976563 | item number 3 |

| | |

etc

Is that what it is?

I told you how to build a column name dynamically.

So when I run the application for the first time, I want Hibernate to start off creating the table and the columns, define the primary key to be the string hash value.

Now, you are telling that the column name is static and the values are assigned with some hashes.

If that’s the case, then just use an assigned identifier and set the id with the calculated hashValue.

Yeah, I looked back and I wasn’t very clear with my request, I had to confirm after reading the link.
So I should do something similar to this?

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;

where the id will be the hash that I provide

thanks again

You need to write a custom identifier generator that extends the Hibernate IdentityGenerator and sets the custom identifier logic.

Check out this article for more details.

1 Like