Different column types for different databases with JPA

Is it possible to define different types of columns using JPA depending on the database used?

I need to save id as uuid and it should be protable. This is problem. PostgreSQL has "uuid", MSSQL has a "uniqueidentifier", and Oracle has nothing, so I have to use "RAW".

Does anyone have an idea and can help me?

Edit: Currently, identifiers are created using java.util.UUID and stored in the database as varchar. But due to performance issues with this data type, I want to save identifiers as uuid type. For Oracle, you must use the RAW type because there is no uuid type. How can I say that JPA uses uuid type with PostgreSQ / MSSQL and RAW types with Oracle?

+4
source share
2 answers

You can use java.util.UUID to generate your uuids and store it in a character type (60). Now, since you want to be the primary key, it should be useful to automatically generate it. Thus, you can add an object listener to your class in PrePersist:

@EntityListeners({ AbstractEntity.AbstractEntityListener.class})
public class Entity {

    public static class AbstractEntityListener {
        @PrePersist
        public void onPrePersist(Entity entity) {
            entity.uid();
        }
    }

    private String uid() {
        if (uid == null)
          uid = UUID.randomUUID().toString();
        return uid;
    }
}

Please note that I have not tested this. Therefore, it may not work 100%.

0
source

SequenceGenerator. . . . , , concurrency. , / .

0

Source: https://habr.com/ru/post/1524523/


All Articles