0

I am developing spring boot application and I need to create one field in object which can have different data types, for example Long, String, Boolean, but I don't have any idea how to do it. I thought about Object but Hibernate can't mapping this type and save in postgres database.

I would like retrive JSON like this:

{
"field1" : "string"
"value" : true / 124L / "text" <- problem with this field(bool or long or string)
} 

Does anybody have an idea?

2

1 Answer 1

0

It should be possible but I am not sure if it is the best design decision in your case. Since you ask for ideas, I would recommend some options which may better suit to your use case:

Instead of having a field with multiple possible data types, you can consider using JSONB, where it is still a single column in the database table, it has the flexibility of JSON. In your JSON structure you can have separate fields for each possible data type for your business case but only set the relevant one and store it in db. Postgres has a good support for JSONB types and it works fine with Hibernate.

If you are trying to implement something like a key/value store, then you should check the hstore module of postgres and define your custom user type as described here: Is there a way to query a PostgreSQL hstore with Hibernate/JPQL?

An obvious but not so good option to have your value field as a text data type and have another field showing the actual data type and parse accordingly, as suggested here: Sane way to store different data types within same column in postgres?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for answer. Yes, I realize that isn't the best solution but I have issue to do it, but the method is not specified, so I can consider other solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.