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

问题描述 投票:0回答:1

我的实体类如下所示:

@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

有什么办法可以实现这个目标吗?

spring spring-boot hibernate spring-data-jpa spring-data
1个回答
0
投票

接口中

FieldDetails
,所有方法都必须是getter方法。

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
未注册为正在使用的默认方言的一部分。

根据您的数据库提供商,扩展适当的方言并注册类型

2003
以将其映射到
StringArrayType.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());
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.