Reputation: 1080
I have a relationship between two Hibernate entities: User
and Item
.
User
:
@Entity
@Table(name="user")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private Integer mId;
@Column(name="username")
private String mUsername;
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="user_id")
private List<Item> mItems;
}
Item
:
@Entity
@Table(name="users_item")
public class Item implements Serializable{
@Id
@Column(name="item_id")
private Integer mId;
@Id
@Column(name="item_class_id")
private Integer mClassId;
}
However, when I query for a User
all I want is a List<Integer>
that represents their Items'
ids not a List<Item>
. Are there annotations I can use, or some other way using Hibernate
to achieve that?
Upvotes: 0
Views: 36
Reputation: 3733
I don't believe there are annotations that will support that kind of requested behavior.
However, if you want to get a list of the id of items, that is easy to do in two steps which I like also to use on my own projects. The two steps are:
Use Java8-Streams to get a list of id. like this:
User user = session.get(1,User.class);
List<Item> list = user.getMItems();
List<Integer> listIds = list.stream().map(item -> item.getId()).collect(Collectors.toList());
Upvotes: 1