4

I have Spring Boot project with DB. I've already get table, let's call it "People". I need to add a second table "People_Strings" with two columns: People_id and String. I need to include many strings for every row from People.

How can I map it in my People entity in project?

Edit: I need to do this without creating separete class for String or for People_Strings

2
  • 2
    What have you tried? Can you show us your code? Commented Dec 19, 2017 at 16:15
  • If you want to do this without separate classes you can store a list! And please ask your questions clearly at first Commented Dec 19, 2017 at 16:26

4 Answers 4

6

If you only need that, you can add the following property to the People entity class:

@ElementCollection
public List<String> strings;
Sign up to request clarification or add additional context in comments.

Comments

1

What you need is @OneToMany relation between people and strings. Something like the following will work for you.

@Entity
@Table(name = "People")
public class People{

  @Id
  @GeneratedValue
  private Long id;

  @OneToMany(fetch= FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "peopleId")
  private List<PeopleStrings> PeopleStrings;

@Entity
@Table(name = "People_Strings")
public class PeopleStrings{

  @Id
  @GeneratedValue
  private Long peopleId;

  @ManyToOne
  @JoinColumn(name="peopleId")
  private String string;

2 Comments

This is why I hate hibernate, that FetchType.EAGER is bound to cause a query to perform really badly in the future
Option 1: Ditch hibernate... avoid that nonsense all together!! (hibernate makes intelligent people write stupid queries) Option 2: Never eager fetch by default. If you want eager, you should explicitly say so when querying.
0

You'll want a @OneToMany relationship on the Person object (please don't use plurals, eg People). And possibly a @ManyToOne relationship on the PersonString object (again no plurals)

Comments

-1

This is kinda basic question and I suggest you to read Hibernate "Get Started" first. (one-to-many / many-to-one relations especially)

2 Comments

yup, it is basic question, when it comes to include list of Objects from other entity. I don't want to create separate class for Strings. So I'm asking if there's other way.
Then you should consider using a combination of @ElementCollection, @MapKeyColumn and @CollectionTable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.