有没有办法在 DTO 中定义 Hibernate 自定义类型

Is there any way to define Hibernate custom type in DTO

提问人:Summy Saurav 提问时间:11/18/2023 更新时间:11/18/2023 访问量:24

问:

我的 Entity 类如下所示:

@TypeDef(name = "string-array", typeClass = StringArrayType.class)
public class Field extends BaseEntity {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false)
  private Long id;

  @Column(name = "title", length = 50)
  private String title;

  @Column(name = "acreage", precision = 10, scale = 2)
  private BigDecimal acreage;

  @Column(name = "gps_coordinates")
  private Point gpsCoordinates;

  @Column(name="zip_code", length = 10)
  private String zipCode;

  @Type(type = "string-array")
  @Column(name = "photo_path", columnDefinition = "text[]")
  private String[] photoPath;
}

并希望拥有如下 DTO 类:

public interface FieldDetails {

    String getTitle();
    Point gpsCoordinates();
    BigDecimal getAcreage();
    
    String getMemo1();
    String[] getPhotoPath();

}

并使用下面的 JPA 方法获取 FieldDetails:

@Query(value = """
            select f.title, 
            f.gps_coordinates as gpsCoordinates,
            f.acreage,
            f.memo1,
            f.photo_path as photoPath
            from public.field f where f.id = :id
            """, nativeQuery = true)
    Object getFieldDetails(Long id);

使用此方法时,我出现以下错误:

JDBC 类型无方言映射:2003

有什么方法可以做到这一点吗?

hibernate spring-data-jpa spring-data

评论


答:

0赞 atish.s 11/18/2023 #1

在接口中,所有方法都必须是 getter 方法。FieldDetails

更新到Point gpsCoordinates();Point getGpsCoordinates();

为所选字段添加适当的别名。

@Query(value = """
        select f.title as title, 
        f.gpsCoordinates as gpsCoordinates,
        f.acreage as acreage,
        f.memo1 as memo1,
        f.photoPath as photoPath
        from public.field f where f.id = :id
        """)
FieldDetails getFieldDetails(Long id);

memo1实体上似乎也不存在。

对于方言问题,该类型似乎未注册为正在使用的默认方言的一部分。StringArrayType

根据您的数据库提供程序,扩展相应的方言并注册类型以将其映射到 。2003StringArrayType.class

扩展 Postgres 方言的示例

import com.vladmihalcea.hibernate.type.array.StringArrayType;
import org.hibernate.dialect.PostgreSQL9Dialect;

public class PostgreSQL9CustomDialect extends PostgreSQL9Dialect {

    public PostgreSQL9CustomDialect() {
        super();
        this.registerHibernateType(2003, StringArrayType.class.getName());
    }

}