Spring Boot JPA和Criteria API-选择单列

时间:2019-06-28 11:27:00

标签: java hibernate spring-boot jpa-2.0 criteria-api

我正在尝试从表中检索单个列,但出现有关返回类型的编译错误。

SQL

select oComment from comment where oNote = note and version > 0;

我有Comment表和Note表。注释表具有comment, note and version列。评论本身就是一个注释。现在,我想检索版本大于0的注释的所有注释。但是在这里,我只想注释类型为注释的注释列。

Comment.java

    @Entity
    @Table(name="comment")
    @Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="comments")
    public class Comment implements Serializable {

        private static final long serialVersionUID = -4420192568334549165L;

        public Comment() {
        }

        @Id
        @OneToOne
        @JoinColumn(name="commentuuid",referencedColumnName="noteuuid")
        private Note oComment;

        @Id
        @OneToOne
        @JoinColumn(name="noteuuid",referencedColumnName="noteuuid")
        private Note oNote;
}

Note.java

@Entity
@Table(name = "note")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="notes")
public class Note implements Serializable{

    private static final long serialVersionUID = 4089174391962234433L;

    @Column(name="title")
    private String m_szTitle;

    @Column(name="htmlcontent")
    private String m_sbHtmlContent;

    @Column(name="textcontent")
    private String m_sbTextContent;

    @Id
    @Column(name="noteuuid", columnDefinition="varchar(36)")
    private String noteUuid;
}

CustomRepositoryMethod

public List<Note> findAllByNote(Note oNote, int iOffset, int iResultSize) {

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Comment> cq = cb.createQuery(Comment.class);

        Root<Comment> oComment = cq.from(Comment.class);
        List<Predicate> predicates = new ArrayList<>();

        predicates.add(cb.equal(oComment.get("oNote"), oNote));
        predicates.add(cb.greaterThan(oComment.get("version"), 0));

        Subquery<Note> subquery = cq.subquery(Note.class);
        Root<Note> note = subquery.from(Note.class);

        cb.desc(note.get("m_dtCreationDate"));

        cq.where(predicates.toArray(new Predicate[0]));

        cq.multiselect(oComment.<Note>get("oComment"));

        return (List<Note>)em.createQuery(cq).setFirstResult(iOffset).setMaxResults(iResultSize).getResultList();
    }

错误 返回语句出错,

Cannot cast from List<Comment> to List<Note>

4 个答案:

答案 0 :(得分:2)

CustomRepositoryMethod 中首先替换 第CriteriaQuery<Comment> cq = cb.createQuery(Comment.class);行到CriteriaQuery<Note> cq = cb.createQuery(Note.class)

cb.createQuery参数在docs中接受结果类。

更新

// assuming query like
// select oComment from comment inner join Note on comment.noteuuid=Note.noteuuid where Note.noteUuid = 1 and version > 0;

CriteriaBuilder cb = em.getCriteriaBuilder();
// data type of oComment
CriteriaQuery<Note> query = cb.createQuery(Note.class);
// from comment
Root<Comment> comment = query.from(Comment.class);

//join
Join<Comment, Note> note = comment.join(comment.get("oNote"));

//version Condition
Predicate version=cb.greaterThan(comment.get("version"),0 );

//Note condition
predicate note=cb.equal(note.get("noteuuid"),note.getNoteUuid());

// get oComment and where condtion 
query.select(comment.get("oComment")).where(cb.and(version,note));

    return  em.createQuery(query).setFirstResult(iOffset).setMaxResults(iResultSize).getResultList();

答案 1 :(得分:1)

您的条件查询的根是Comment而不是Note

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Comment> cq = cb.createQuery(Comment.class);
Root<Comment> oComment = cq.from(Comment.class);

您正在尝试

return (List<Note>)em.createQuery(cq).setFirstResult(iOffset)
.setMaxResults(iResultSize).getResultList();

在这种情况下编译错误是不可避免的,因为em.createQuery(cq).getResultList()将返回List<Comment>而不是List<Note>

答案 2 :(得分:0)

不必编写自定义存储库方法,因为要创建的存储库方法已经在spring-data中生成。

如果您的存储库扩展了CrudRepository,您将免费获得该方法。

该模式为findAllBy [propertyOfClass]。

但是请注意,您的实体中实际上没有NOTE的集合。

也许您应该首先将OneToOne关联更改为OneToMany。

答案 3 :(得分:0)

可以作为标准查询构建,如下所示:

case AuthStatus.signedIn: {
            print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@');
            int length;
            userData.services.length.then((dataLength){
                length = dataLength;
            });
            if (length==0) {
              print('Here I am!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
              print(length);
              return Phone();

            } else {
              return
               HomeScreen();
            }

          } break;

CriteriaQuery<Country> q = cb.createQuery(Country.class); Root<Country> c = q.from(Country.class); q.select(c.get("currency")).distinct(true); 方法采用一个类型为Selection的参数并将其设置为SELECT子句的内容。