Reputation: 2882
I have 2 entities
@Entity
@Table(name = "USER")
public class User implements Serializable {
private Long id;
private String username;
}
And
@Entity
@Table(name = "LOGS")
public class Logs implements Serializable {
private Long id;
private Long userId;
private String message;
}
This entity does not have relations. When LOGS
fill I do not have User
entity(but I have userId
) and I set userId
in LOGS
(not User
entity/ Only Long userId
).
When I show logs for user on web page I need to show all fields of LOGS
:
id userId message
1 1 message1
2 1 message2
3 2 message3
4 2 message4
But I need replase userId
to UserName
:
id user message
1 Bill message1
2 Bill message2
3 John message3
4 John message4
How can I join 2 tables if I there is no relation between then? I can use native query but maybe it is not necessary?
Upvotes: 2
Views: 102
Reputation: 26522
Updated
In your query you should use the 'old' style on joining when you match the columns in the where clause:
1) Create the class for projected fields:
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) Perform the query
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
Upvotes: 2
Reputation: 5948
You can add a relationship 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;
}
Upvotes: 0