Persisting UUID in PostgreSQL using JPA

前端 未结 7 631
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 06:43

I\'m trying to persist an entity in PostgreSQL that uses UUID as primary key. I\'ve tried persisting it as a plain UUID:

@Id
@Column(name = \"customer_id\")
         


        
7条回答
  •  青春惊慌失措
    2020-12-01 07:07

    The solution suggested by Oleg did not work perfectly for me (it failed if you tried to persist a null value). Here is a tweaked solution that also works for null values.

    In my case i am using EclipseLink though so if you are using Hibernate you might not need this.

    public class UuidConverter implements AttributeConverter {
        @Override
        public Object convertToDatabaseColumn(UUID uuid) {
            PGobject object = new PGobject();
            object.setType("uuid");
            try {
                if (uuid == null) {
                    object.setValue(null);
                } else {
                    object.setValue(uuid.toString());
                }
            } catch (SQLException e) {
                throw new IllegalArgumentException("Error when creating Postgres uuid", e);
            }
            return object;
        }
    
        @Override
        public UUID convertToEntityAttribute(Object dbData) {
            return (UUID) dbData;
        }
    }
    

提交回复
热议问题