Domanda

I want to get the maximum value of column relationId from table ElementRelationType I have written code but its giving error

CriteriaBuilder cb1 = entityManager.getCriteriaBuilder();
CriteriaQuery<ElementRelationTypes> cq1 = cb1.createQuery(ElementRelationTypes.class);
Root<ElementRelationTypes> root = cq1.from(ElementRelationTypes.class);
cq1.select(cb1.max(root.get("relationId")));

select and max both giving error how to get the integer max value

public class ElementRelationTypes {

private RelationId relationLangPK=new RelationId(); 

private Country country;
private Status status;


@EmbeddedId
public RelationId getRelationLangPK() {
    return relationLangPK;
}
public void setRelationLangPK(RelationId relationLangPK) {
    this.relationLangPK = relationLangPK;
}

@Transient
public Integer getRelationId() {
    return getRelationLangPK().getRelationId();
}
public void setRelationId(Integer relationId) {
    getRelationLangPK().setRelationId(relationId);
}
@Transient
public Language getLanguage() {
    return getRelationLangPK().getLanguage();
}
public void setLanguageCode(Language language) {
    getRelationLangPK().setLanguage(language);
}

and

public class RelationId implements Serializable {
private static final long serialVersionUID = 1L;
private Integer relationId;
private Language language;

@JoinColumn(name=PersistenseConstants.ELEMENT_RELATION_TYPE_COL_RELATION_ID)
public Integer getRelationId() {
    return relationId;
}

public void setRelationId(Integer relationId) {
    this.relationId = relationId;
}

@OneToOne
@JoinColumn(name=PersistenseConstants.LANGUAGE_ENTITY_COL_LANG_CODE)
public Language getLanguage() {
    return language;
}

public void setLanguage(Language language) {
    this.language = language;
}
È stato utile?

Soluzione

You didn't post which errors do you receive, so I have to guess.

CriteriaBuilder.max accepts Expression<N> where N extends Number

At the same time Root.get by default returns Path<Object> which is inconvertible to Expression<Number>.

So to make your call to max work you need to specify generic parameter to root.get:

cq1.select(cb1.max(root.<Number>get("relationId")));

here you can replace Number with an actual type of relationId (Long, BigInteger etc.)

UPDATE: @perissf addressed another issue with your code. If you are going to select maximal value (which is numeric) you should declare your CriteriaQuery as a query to Number not ElementRelationTypes

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top