Hibernate - 加入查询

时间:2014-12-01 11:11:05

标签: mysql spring hibernate join

我有两个班级:

@Entity
public class Tick {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@ManyToOne(optional = false)
@JoinColumn(name = "elitesystem_id", referencedColumnName = "id")
private EliteSystem eliteSystem;

private Date createDate;

@ManyToOne(optional = true)
@JoinColumn(name = "commander_id", referencedColumnName = "id")
private Commander commander;

private String address;

@Entity
public class Note {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@ManyToOne(optional = true)
@JoinColumn(name = "tick_id", referencedColumnName = "id")
private Tick tick;

private String text;

private Date createDate;

我想选择所有刻度并获得备注,如果有的话:

    Query query = session.createQuery("select t, n from Note n right join n.tick t where t.commander.name = '123'");
    List<Object[]> list = query.list();

这只返回Tick对象。在单个查询中获取注释信息的正确方法是什么? 我可以在Tick类中引用一个Note,但这听起来不对,因为只有几个音符,所以Tick表中的列通常都是空的。

1 个答案:

答案 0 :(得分:1)

创建一个新类,例如:

public class TickNote {
    private Tick tick;
    private Note note;

    public TickNote(Tick tick,Note note){
        this.tick=tick;
        this.note=note;

然后你的查询是:

Query query = session.createQuery("select NEW TickNote(t, n) from Note n right join n.tick t where t.commander.name = '123'");
    List<TickNote> list = query.list();