【问题标题】:Hibernate - Join queryHibernate - 加入查询
【发布时间】:2015-01-29 09:10:23
【问题描述】:

我有两个班级:

@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 对象。在 1 个单一查询中获取注释信息的正确方法是什么? 我可以在 Tick 类中添加对 Note 的引用,但这听起来不对,因为只有几个音符,所以 Tick 表中的列大部分是空的。

【问题讨论】:

    标签: mysql spring hibernate join


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 2011-01-23
      • 2014-03-22
      • 2013-07-31
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      相关资源
      最近更新 更多