如果这些表之间没有关系,我该如何加入2个实体表?

时间:2017-01-25 10:05:05

标签: java hibernate jpa orm

我有2个实体

@Entity
@Table(name = "USER")
public class User implements Serializable {
    private Long id;
    private String username;
}

并且

@Entity
@Table(name = "LOGS")
public class Logs implements Serializable {
        private Long id;
        private Long userId;
        private String message;
}

这个实体没有关系。当LOGS填充时,我没有User实体(但我有userId)并且我在userId中设置了LOGS(不是User实体/只有Long userId)。

当我在网页上显示用户日志时,我需要显示LOGS的所有字段:

id userId message
1  1       message1
2  1       message2
3  2       message3
4  2       message4

但我需要重新userIdUserName

id user message
1  Bill       message1
2  Bill       message2
3  John       message3
4  John       message4

如果我之间没有任何关系,我该如何加入2个表?我可以使用原生查询,但可能没有必要吗?

2 个答案:

答案 0 :(得分:2)

<强>更新

在您的查询中,您应该使用&#39; old&#39;匹配where子句中的列时加入的样式:

1)为投影字段创建类:

package org.myapp;

public class UserLogs{

   private Long id;
   private String username;
   private String message;

   public UserLogs(Long id, String username, String message){
       this.id = id;
       this.username = username;
       this.message = message;
   }

}

2)执行查询

String query =
   " select new org.myapp.UserLogs"+
   "(l.id, u.username, l.message) "+
   " from Logs l, User u"+
   " where l.userId = u.id";

List<UserLogs> userLogs = session.createQuery(query)
                      .list();

// process list

答案 1 :(得分:0)

您可以添加关系ManyToOne

@Entity
@Table(name = "LOGS")
public class Logs implements Serializable {
    private Long id;
    private Long userId;
    private String message;

    @Getter
    @Setter
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
    @JoinColumn(name = "USER_ID")
    private User user;

}