Persisting UUID in PostgreSQL using JPA

前端 未结 7 630
爱一瞬间的悲伤
爱一瞬间的悲伤 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:00

    JPA 2.1 provides a very easy way to use the PostgreSQL uuid column type and java.util.UUID as the type of the corresponding entity field:

    @javax.persistence.Converter(autoApply = true)
    public class PostgresUuidConverter implements AttributeConverter {
    
        @Override
        public UUID convertToDatabaseColumn(UUID attribute) {
            return attribute;
        }
    
        @Override
        public UUID convertToEntityAttribute(UUID dbData) {
            return dbData;
        }
    
    }
    

    Just add this class to your persistence configuration and annotate UUID fields with @Column(columnDefinition="uuid").

提交回复
热议问题