我有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
但我需要重新userId
到UserName
:
id user message
1 Bill message1
2 Bill message2
3 John message3
4 John message4
如果我之间没有任何关系,我该如何加入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;
}