簡體   English   中英

有沒有辦法用Hibernate / JPQL查詢PostgreSQL hstore?

[英]Is there a way to query a PostgreSQL hstore with Hibernate/JPQL?

假設我有一個Hibernate / JPA實體,如下所示:

@Entity
public class FooEntity {

  ...

  @Type(type = "hstore")
  HashMap<String, String> tags;
}

...而hstore Type是來自資源的簡單UserType實現。

有沒有辦法在類似於這個Pseudocode的JPQL查詢中訪問hstore:

SELECT f FROM FooEntity f WHERE f.tags CONTAINS KEY(:key)

您也可以簡單地創建一個Hibernate org.hibernate.usertype.UserType。 你擴展了那個班級; 我們自己實現的一個例子:

public class HstoreUserType implements UserType {

/**
 * PostgreSQL {@code hstore} field separator token.
 */
private static final String HSTORE_SEPARATOR_TOKEN = "=>";

/**
 * {@link Pattern} used to find and split {@code hstore} entries.
 */
private static final Pattern HSTORE_ENTRY_PATTERN = Pattern.compile(String.format("\"(.*)\"%s\"(.*)\"", HSTORE_SEPARATOR_TOKEN));

/**
 * The PostgreSQL value for the {@code hstore} data type.
 */
public static final int HSTORE_TYPE = 1111;

@Override
public int[] sqlTypes() {
    return new int[] { HSTORE_TYPE };
}

@SuppressWarnings("rawtypes")
@Override
public Class returnedClass() {
    return Map.class;
}

@Override
public boolean equals(final Object x, final Object y) throws HibernateException {
    return x.equals(y);
}

@Override
public int hashCode(final Object x) throws HibernateException {
    return x.hashCode();
}

@Override
public Object nullSafeGet(final ResultSet rs, final String[] names,
        final SessionImplementor session, final Object owner)
        throws HibernateException, SQLException {
    return convertToEntityAttribute(rs.getString(names[0]));
}

@SuppressWarnings("unchecked")
@Override
public void nullSafeSet(final PreparedStatement st, final Object value, final int index,
        final SessionImplementor session) throws HibernateException, SQLException {
    st.setObject(index, convertToDatabaseColumn((Map<String,Object>)value), HSTORE_TYPE);

}

@SuppressWarnings("unchecked")
@Override
public Object deepCopy(final Object value) throws HibernateException {
    return new HashMap<String,Object>(((Map<String,Object>)value));
}

@Override
public boolean isMutable() {
    return true;
}

@Override
public Serializable disassemble(final Object value) throws HibernateException {
    return (Serializable) value;
}

@Override
public Object assemble(final Serializable cached, final Object owner)
        throws HibernateException {
    return cached;
}

@Override
public Object replace(final Object original, final Object target, final Object owner)
        throws HibernateException {
    return original;
}


private String convertToDatabaseColumn(final Map<String, Object> attribute) {
    final StringBuilder builder = new StringBuilder();
    for (final Map.Entry<String, Object> entry : attribute.entrySet()) {
        if(builder.length() > 1) {
            builder.append(", ");
        }
        builder.append("\"");
        builder.append(entry.getKey());
        builder.append("\"");
        builder.append(HSTORE_SEPARATOR_TOKEN);
        builder.append("\"");
        builder.append(entry.getValue().toString());
        builder.append("\"");
    }
    return builder.toString();
}

private Map<String, Object> convertToEntityAttribute(final String dbData) {
    final Map<String, Object> data = new HashMap<String, Object>();
    if (dbData != null) {
        final StringTokenizer tokenizer = new StringTokenizer(dbData, ",");
        while(tokenizer.hasMoreTokens()) {
            final Matcher matcher = HSTORE_ENTRY_PATTERN.matcher(tokenizer.nextToken().trim());
            if(matcher.find()) {
                data.put(matcher.group(1), matcher.group(2));
            }
        }
    }
    return data;
}

}

現在您可以在Entity bean中使用它,如下所示:

@Entity
@Table(name="YourEntityBeanTable")
@TypeDefs({
    @TypeDef(name = "hstore",  typeClass = HstoreUserType.class)
})

public class YourEntityBean {

.....

    @Type(type = "hstore")    
    @Column(name= "an_hstore_column", columnDefinition = "hstore")
    private Map<String, String> anHStoreColumn = new HashMap<>();



}

Hibernate在許多數據庫中提供了一個通用的查詢抽象,因此非SQL語法很難被抽象出來。

我會去尋找一個本地查詢來獲取id並使用它們來獲取Hibernate實體,如果你真的需要那些。

如果您只對投影感興趣,那么本機查詢是您的最佳選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM