R
R
Romka212018-12-02 18:11:27
Java
Romka21, 2018-12-02 18:11:27

OneToMany in Hibernate?

Comrades, I ask you to help, I can’t catch up with something.
In general, there are two classes "Directory" and "Directory fields".
Both classes are written in HibernateSessionFactoryUtil:

configuration.addAnnotatedClass(Dictionary.class);
configuration.addAnnotatedClass(DictionaryContent.class);

and are successfully created in the database, here they are:
@Entity
@Table(name = "sys_dictionaries")
public class Dictionary {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    UUID guid = UUID.randomUUID();

  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<DictionaryContent> dictionaryContents = new HashSet<>();
 
   .............................
}

@Entity
@Table(name = "sys_dictionaries_content")
public class DictionaryContent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;


    @Column
    UUID guid = UUID.randomUUID();

    @Column
    UUID dictionaryId;
  
    ........................
}

I would very much like to associate child records ( DictionaryContent ) with Dictionary by means of its UUID identifier.
Now when I save a Dictionary object by passing a collection from DictionaryContent to it, everything is successfully written to its tables, however, no identifier pointer to the parent Dictionary appears in the DictionaryContent table.
Screenshot of DictionaryContent table:
5c03f5b8b3b7e953674217.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2018-12-02
@Romka21

Hello!
I myself am just learning Java development (hibernate, spring etc.)
You need to use OneToMany & ManyToOne. From the Dictionary side, get a list of DictionaryContent entries (List or Set), and from the DictionaryContent side, get a Dictionary object.

@Entity
public class Dictionary {

   @OneToMany(mappedBy = "dictionary")
    private List<DictionaryContent> contentList;
}

@Entity 
public class DictionaryContent {

    @ManyToOne
    @JoinColumn(name = "id")
    private Dictionary dictionary;

}

this is because from the DictionaryContent side, most likely you did not bind, as in the example above.
A good example is https://devcolibri.com/%D0%BA%D0%B0%D0%BA-%D1%81%D...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question