Reputation: 595
Can I create an entity that will retrieve data from 2 (or more) tables?
I would like to have tables:
user: id, name, password user_address: idUser, street, city
And UserEntity with:
int: id
String: name, password, street, city
When using only one table, I have got:
UserEntity:
@Entity
public class UserEntity {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "user")
private String user;
@Column(name = "password")
private String password;
//+ getter + setters
}
and a method for loading users from DB with code:
String queryString = "FROM UserEntity WHERE user = :user AND password = :password";
Query query = session.createQuery(queryString);
query.setString("user", userForm.getUser());
query.setString("password", userForm.getPassword());
UserEntity userEntity = (UserEntity) query.uniqueResult();
Upvotes: 1
Views: 257
Reputation: 7518
Yes. But I would suggest one java class for each table. User
and Address
and then you want to use the join @JoinColumn
annotation to specify the column that tables are joined by.
If you do not want two separate classes you can use a ResultTransformer.
Upvotes: 1