简体   繁体   中英

Entity with data from two tables

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM