我需要一个SQL查询,该查询将找到包含所有给定音符的所有音阶

时间:2018-08-01 13:26:31

标签: java mysql database hibernate id

我在使用SQL查询时遇到问题,该查询会向我显示所有包含传递给查询的所有音符的音阶。这是Java中的一些代码:

public List<Integer> findScaleByNotes(String... notes){

        String s = Arrays.toString(notes).replace("[", "").replace("]", "");


        Query query = entityManager.createNativeQuery("query_here" );

        return query.getResultList();

    }

问题是,ManyToMany关系中的Scales表和Notes表ale如此,因此我必须仅对具有id的表进行操作。

Scale.java

@Entity
public class Scale { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 
    private String keyNote; 
    private String type; 
    private String name;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
    private List<Chord>chords; 

    @ManyToMany private List<Note>notes;
    ...
}

Note.java:

@Entity
public class Note { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 
    private String name;
    ...
}

2 个答案:

答案 0 :(得分:0)

好的,我想我明白了。

SELECT scale_id, COUNT(*) FROM scale_notes WHERE notes_id IN (1,2)  GROUP BY scale_id HAVING COUNT(*) >=2;

答案 1 :(得分:0)

The Criteria Query API允许动态地向查询添加条件,并利用您的实体,也可以生成强类型的查询:

public List<Scale> findScaleByNotes(String... notes) {
    // Instantiate the criteria builder
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    // A CriteriaQuery is generically typed; the type argument represents type of result
    CriteriaQuery<Scale> criteriaQuery = criteriaBuilder.createQuery(Scale.class);
    // Root is the entity we are pulling from
    Root<Scale> scaleRoot = criteriaQuery.from(Scale.class);

    Join<Scale, Note> scaleNoteJoin = scaleRoot.join("notes");

    // Pieces of your "WHERE" clause
    // Dynamically add conditions for each of your notes.
    List<Predicate> conditions = new ArrayList<>();
    for (String note : notes) {
        Predicate condition = criteriaBuilder.isMember(note, scaleNoteJoin);
        conditions.add(condition);
    }

    // Tell the query what we are selecting, and what our conditions are.
    criteriaQuery.select(scaleRoot)
        .where(conditions);

    // Now transform the criteria query into a TypedQuery.
    TypedQuery<Scale> query = entityManager.createQuery(criteriaQuery);
    return query.getResultList();
}