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

vnjpjtjt  于 2023-11-21  发布在  其他
关注(0)|答案(1)|浏览(107)

我的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类型无DialectMap:2003

有没有办法做到这一点?

zysjyyx4

zysjyyx41#

在接口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以将其Map到StringArrayType.class
一个扩展Postgres Dialect的例子

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());
    }

}

相关问题