Answer the question
In order to leave comments, you need to log in
How to use methods on @ManyToOne connection within JpaRepository?
There are two entities:
@Entity
@Table(name = "AUTHORS", schema = "NEWS_SCHEMA")
@Getter
@Setter
@NoArgsConstructor
public class Author {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "NAME")
private String name;
@Column(name = "SURNAME")
private String surname;
@Column(name = "DATE_OF_BIRTH")
private Date dob;
@OneToMany(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
mappedBy = "authorOfArticle")
private List<Article> articlesOfAuthor;
public void addArticleToAuthor(Article article) {
if (articlesOfAuthor == null) {
articlesOfAuthor = new ArrayList<>();
}
articlesOfAuthor.add(article);
article.setAuthorOfArticle(this);
}
public Author(String name, String surname, Date dob) {
this.name = name;
this.surname = surname;
this.dob = dob;
}
}
@Entity
@Table(name = "ARTICLES",schema = "NEWS_SCHEMA")
@Getter @Setter
@NoArgsConstructor
public class Article {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "TITLE")
private String title;
@Column(name = "CONTENT")
private byte[] content;
@Column(name = "CATEGORY_ID")
int categoryId;
@ManyToMany(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinTable(
name = "ARTICLES_CATEGORIES",
schema = "NEWS_SCHEMA",
joinColumns = @JoinColumn(name = "ARTICLE_ID"),
inverseJoinColumns = @JoinColumn(name = "CATEGORY_ID"))
private List<Category> categoriesInArticle;
@ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinColumn(name = "AUTHOR_ID" )
private Author authorOfArticle;
public Article( String title, int categoryId, Author author) {
this.title = title;
this.categoryId = categoryId;
this.authorOfArticle = author;
}
}
Answer the question
In order to leave comments, you need to log in
You just need to call method void addArticleToAuthor(Article article)
A at the end call method author.save()
Here is a useful article on ManyToOne & OneToMany
https://thorben-janssen.com/best-practices-many-on...
https://www.baeldung.com/hibernate- one-to-many
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question