我有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个表?我可以使用本机查询,但也许没有必要?
更新
在查询中,当匹配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
您可以添加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;
}