是否可以使用HQL使用PostgreSQL数组?

时间:2016-10-22 19:43:11

标签: java postgresql hibernate

我已经阅读了许多专门用于在Hibernate中使用PostgreSQL数组的主题。 我实现了UserType接口,我的查询与本机sql完全一致。

private void addCountry(String country, String[] cities) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    Query insert = session.createNativeQuery("INSERT INTO public.\"countries\"(\n" +
            "\t\"country\", \"cities\")\n" +
            "\tVALUES (:Country, :Cities);");
    Type arrayType = new CustomType(new StringUserType());
    insert.setParameter("Country", country);
    insert.setParameter("Cities", cities, arrayType);

    insert.executeUpdate();
    /**
    CountriesEntity countriesEntity = new CountriesEntity();
    countriesEntity.setCountry(country);
    countriesEntity.setCities(cities);
    session.save(countriesEntity);
     */
    session.getTransaction().commit();
}

private List<String[]> listCities() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Query getCities = session.createNativeQuery("SELECT \"cities\"\n" +
            "\tFROM public.\"countries\";")
            .addScalar("cities", new CustomType(new StringUserType()));

    List<String[]> cities = getCities.list();
    session.getTransaction().commit();
    return cities;
}

实体类:

@Entity
@Table(name = "countries", schema = "public", catalog = "Travel_Agency")
public class CountriesEntity {
private String country;
private String[] cities;

@Id
@Column(name = "country")
public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}


@Column(name = "cities")
@Type(type = "com.testHibernate.core.StringUserType")
public String[] getCities() {
    return cities;
}

public void setCity(String[] cities) {
    this.cities = cities;
}

}

那么,是否可以仅使用HQL进行此操作?

1 个答案:

答案 0 :(得分:0)

您正在使用createSQLQuery(String queryString)为给定的 SQL 查询字符串创建SQLQuery实例。

可以使用createQuery(String query)方法为给定的 HQL 查询字符串创建Query实例。例如,检索城市名称为cityName的城市:

Query getCities = session.createQuery("FROM countries WHERE cityName = :city ");
getCities.setParameter("city", "cityName");
return query.list();

以下是The Hibernate Query Language的文档。