shoe
shoe

Reputation: 1080

How to create a one-to-many relationship in Hibernate just using the foreign keys

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

Answers (1)

Moshe Arad
Moshe Arad

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:

  1. Get the List as you did it until now with hibernate
  2. 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

Related Questions