Given an Enitiy Product
#Entity
public class Product {
private Long id;
private List<Review> reviews;
public Product() {}
#Id
#GeneratedValue
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#ElementCollection
public List<Review> getReviews() {
return reviews;
}
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
// equals() and hashCode() omitted for brevity
}
And an Embeddable Review
#Embeddable
public class Review {
private Customer author;
private String title;
private String comment;
public Review() {}
#ManyToOne(optional = false)
#Column(unique = true)
public Customer getAuthor() {
return author;
}
public void setAuthor(Customer author) {
this.author = author;
}
#Column(nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(nullable = false, length = 2000)
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
How can I set an unique constraint for the Review's author. In other words: I want to make sure, that for a given product each review has a different author.
Can I use #NaturalId? Do I use #Column(unique = true)? I already found a similar question on StackOverflow, but in my case it's a list of Embeddables and not just a member, so that that approach won't work, I guess.
Thanks a lot in advance!
If you are talking about having a unique database index added during schema generation then you can do this as below:
#ElementCollection
#CollectionTable(name = "product_reviews",
uniqueConstraints = {#UniqueConstraint(columnNames={"product_id", "author_id"})})
public List<Review> getReviews() {
return reviews;
}
Related
I have a next question: while working with Hibernate 3.3.0 run into a situation when I have two tables with one-to-many relationships and I need to get the list of parents. In each entity must be filled the several fields from the parent table and a list of all children mapped in the parent. For the easiest understanding, I give an example. I have two tables with one-to-many relationships: parent is "recipients" and child is "requisites". And I have two classes whose objects are the rows of these tables. Class for the table of recipients:
#Entity
#Table(name = "recipients")
#JsonFilter(value = "recipientsFilter")
public class POJORecipient implements POJO {
private static final long serialVersionUID = 4436819032452218525L;
#Id
#Column
private long id;
#Version
#Column
private long version;
#Column(name = "client_id")
private long clientId;
#Column
private String inn;
#Column
private String name;
#Column(name = "rcpt_country_code")
private String rcptCountryCode;
#Column(name = "rcpt_passp_ser")
private String rcptPasspSer;
#Column(name = "rcpt_passp_num")
private String rcptPasspNum;
#OneToMany(mappedBy = "recipient", fetch = FetchType.LAZY)
#JsonManagedReference
private Set<POJORequisite> requisites = new HashSet<>();
public POJORecipient(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public long getClientId() {
return clientId;
}
public void setClientId(long clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInn() {
return inn;
}
public void setInn(String inn) {
this.inn = inn;
}
public String getRcptCountryCode() {
return rcptCountryCode;
}
public void setRcptCountryCode(String rcptCountryCode) {
this.rcptCountryCode = rcptCountryCode;
}
public String getRcptPasspSer() {
return rcptPasspSer;
}
public void setRcptPasspSer(String rcptPasspSer) {
this.rcptPasspSer = rcptPasspSer;
}
public String getRcptPasspNum() {
return rcptPasspNum;
}
public void setRcptPasspNum(String rcptPasspNum) {
this.rcptPasspNum = rcptPasspNum;
}
public Set<POJORequisite> getRequisites() {
return requisites;
}
public void setRequisites(Set<POJORequisite> requisites) {
this.requisites = requisites;
}
}
and for requisites table:
#Entity
#Table(name = "requisites")
public class POJORequisite implements POJO {
private static final long serialVersionUID = -35864567359179960L;
#Id
#Column
private long id;
#Version
#Column
private long version;
#Column
private String bic;
#Column
private String bill;
#Column
private String comments;
#Column
private String note;
#ManyToOne
#JoinColumn(name = "recipient_id")
#JsonBackReference
private POJORecipient recipient;
public POJORequisite(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
public String getBill() {
return bill;
}
public void setBill(String bill) {
this.bill = bill;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public POJORecipient getRecipient() {
return recipient;
}
public void setRecipient(POJORecipient recipient) {
this.recipient = recipient;
}
}
So, I want to select from the recipients only names and all mapped requisites. Consequently, after the selection, I will have a list of POJORecipient objects and in each object filled only the field "name" and set of POJORequisite objects.
As answer of my question I want to discover one of next: how can I do that with help HQL or Criteria API (the second variant is preferable), or understand it is impossible in Hibernate at all, or that this possibility appeared in later versions (also preferably with example). I'm trying to resolve this question for several months now and will be immensely grateful for any help. All clarifications and advices also will be so helpful. Thanks in advance!!!
I have 2 entities - Book and Publisher which have a many-to-many relationship. Besides the ids of these entities in the mapping entity, I want to store additional attribute such as bookFormat. So I created a mapping entity BookPublisher and created a composite key entity BookPublisherId. Now, when I want to persist the data using JSON data from my rest controller, I am not able to persist the data correctly. In my JSON data, I am passing the following:
{
"name": "Book14",
"authors": [
{
"firstName": "book14FirstName",
"lastName": "book14LastName"
}
],
"publishers": [
{
"publisher": {
"name": "Pearson1"
},
"format": "Paperback"
}
]
}
Here's the Book entity:
#Entity
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
private String name;
#ManyToMany(cascade = CascadeType.ALL)
#JsonBackReference
private Set<Author> authors;
#OneToMany(mappedBy = "book")
private List<Review> reviews;
#OneToMany(mappedBy = "book")
private Set<BookPublisher> publishers;
public Book() {
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Review> getReviews() {
return reviews;
}
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
public Set<BookPublisher> getPublishers() {
return publishers;
}
public void setPublishers(Set<BookPublisher> publishers) {
this.publishers = publishers;
}
}
Here's the Publisher entity:
#Entity
public class Publisher {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
#OneToMany(mappedBy = "publisher")
private Set<BookPublisher> publishedBooks;
public Publisher() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<BookPublisher> getPublishedBooks() {
return publishedBooks;
}
public void setPublishedBooks(Set<BookPublisher> publishedBooks) {
this.publishedBooks = publishedBooks;
}
}
Here's the BookPublisher entity:
#Entity
public class BookPublisher {
#EmbeddedId
private BookPublisherId bookPublisherId;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("bookId")
private Book book;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("publisherId")
private Publisher publisher;
private String format;
public BookPublisher() {
}
public BookPublisher(Book book, Publisher publisher, String format) {
this.book = book;
this.publisher = publisher;
this.format = format;
}
public BookPublisherId getBookPublisherId() {
return bookPublisherId;
}
public void setBookPublisherId(BookPublisherId bookPublisherId) {
this.bookPublisherId = bookPublisherId;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
Here's the code where I am trying to save the Book entity I receive in the rest controller:
public Book addBook(Book book) {
Set<BookPublisher> toAddPublishers = new HashSet<>();
for(BookPublisher publisher : publishers) {
Publisher addedPublisher = publisherRepository.save(publisher.getPublisher());
BookPublisher toAddBookPublisher = bookPublisherRepository.save(new BookPublisher(book, addedPublisher, publisher.getFormat()));
toAddPublishers.add(toAddBookPublisher);
}
book.setPublishers(toAddPublishers);
Book addedBook = bookRepository.save(book);
return addedBook;
}
When I try to call this method, I see that the BookPublisher entity is not being persisted in the database. What is the correct way to add such data?
I can not say anything definite by the looks of your code but is your addBook inside a transactional scope? Also, why have you not set any cascades for your relationships?
I have two tables: authors and books
Author:
#Entity
#Table (name="authors")
public class Author implements java.io.Serializable {
private Integer id;
private String name;
private String lastName;
/*book list*/
private Set<Book> books= new HashSet<Book>(0);
public Author() {
}
public Author(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public Author(String name, String lastName, Set<Book> books) {
this.name = name;
this.lastName = lastName;
this.books = books;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "AUTHOR_ID", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "AUTHOR_NAME", unique = true, nullable = false, length = 10)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "AUTHOR_LASTNAME", unique = true, nullable = false, length = 10)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "author")
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
}
Book:
import javax.persistence.*;
#Entity
#Table(name = "books")
public class Book implements java.io.Serializable {
private Integer id;
private String name;
private Author author;
public Book() {
}
public Book(String name) {
this.name = name;
}
public Book(String name, Author author) {
this.name = name;
this.author = author;
}
#Id
#Column(name = "BOOK_ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "BOOK_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "AUTHOR_ID",nullable = false)
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
In my book's table I have field with id author. How can I get all books from one author? How Can I solve it?
Must I use HQL or other methods? I am beginner in this.
first you need to the mapping between two entities.
Author class
#OneToMany(mappedBy="author")
private Set<Book> books= new HashSet<Book>(0);
Book class
#ManyToOne
private Author author;
after that you can use a simple criteria query to retrieve the relevant records.
I wont help you with the code here but the logic..
The very first thing you need to do is build a relationship between Author and Books using the annotations #OneToMany or #ManyToOne depending on your structure.
Next use the Author Class Object to retrive the list of Books.
The jhipster doesn't support create many to many relationships with extra fields.
What is the best way to create many to many association with extra columns in jhispter? Should i create a two one-to-many relationship with extra fields?
Using JHipster Domain Language (JDL), a #ManytoMany holding extra properties (columns) can be easily achieved using an association entity and two ManyToOne relationships. See below:
entity Foo{
...
}
entity Bar{
...
}
entity FooBarAssociation{
extraProperty1 String
extraProperty2 String
...
}
relationship ManyToOne {
FooBarAssociation{foo} to Foo{bars}
FooBarAssociation{bar} to Bar{foos}
}
You will have to do it manually.
this post describes how: https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/
In general, as #Antares42 said, you should create an entity for the Many-To-Many table like so:
first entity:
#Entity
public class Book{
private int id;
private String name;
private Set<BookPublisher> bookPublishers;
public Book() {
}
public Book(String name) {
this.name = name;
bookPublishers = new HashSet<>();
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
secound entity:
#Entity
public class Publisher {
private int id;
private String name;
private Set<BookPublisher> bookPublishers;
public Publisher(){
}
public Publisher(String name){
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy = "publisher")
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
Join table entity:
#Entity
#Table(name = "book_publisher")
public class BookPublisher implements Serializable{
private Book book;
private Publisher publisher;
private Date publishedDate;
#Id
#ManyToOne
#JoinColumn(name = "book_id")
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
#Id
#ManyToOne
#JoinColumn(name = "publisher_id")
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
#Column(name = "published_date")
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}
This entity describes the relationship between Book and Publisher and the extra field is published_date
Let's say you have entities like Movie, Rater and needs a join table Ratings. You can write a JDL script like the following:
entity Movie { title String}
entity Rater { name String}
entity Rating { value Integer} //the extra field
relationship ManyToMany {
Rating{rater(name)} to Rater,
Rating{movie(title)} to Movie
}
save it in file.jdl in the project folder, open cmd type
jhipster import-jdl file.jdl
and you have everything
I have model. there is this part:
model was mapped by jpa annotations.Everywhere I use fetchType = EAGER. If I load vacancy from database, I have 2 duplicates status_for_vacancy objects.
I use property hbm2ddl.auto = update.
If I make new schema of database and fill data, I haven't duplicates status_for_vacancy objects.
It really?
code:
vacancy:
#Entity
#Table(name = "vacancy")
#XmlRootElement(name="vacancy")
public class Vacancy {
private List<VacancyStatus> statusList = new LinkedList<VacancyStatus>();
#OneToMany(mappedBy = "vacancy", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<VacancyStatus> getStatusList() {
return statusList;
}
public void setStatusList(List<VacancyStatus> statusList) {
this.statusList = statusList;
}
}
status_for_vacancy:
#Entity
#Table(name = "status_for_vacancy")
public class StatusForVacancy extends AbstractStatus {
public StatusForVacancy() {
super();
}
public StatusForVacancy(Integer id, String name) {
super(id, name);
}
}
#MappedSuperclass
#XmlRootElement
public abstract class AbstractStatus {
private Integer id;
private String name;
public AbstractStatus() {
super();
}
public AbstractStatus(String name) {
super();
this.name = name;
}
public AbstractStatus(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column (name ="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
#NotEmpty
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
vacancy_status:
#Entity
#Table(name = "vacancy_status")
public class VacancyStatus extends AbstractHistoryStatus {
private Vacancy vacancy;
private StatusForVacancy status;
public VacancyStatus() {
super();
}
public VacancyStatus(Integer id, User author, Date date,
Vacancy vacancy, StatusForVacancy status) {
super(id, author, date);
this.vacancy = vacancy;
this.status = status;
}
#ManyToOne
#JoinColumn(name = "vacancy_id")
public Vacancy getVacancy() {
return vacancy;
}
public void setVacancy(Vacancy vacancy) {
this.vacancy = vacancy;
}
#ManyToOne
#JoinColumn(name = "status_id")
public StatusForVacancy getStatus() {
return status;
}
public void setStatus(StatusForVacancy status) {
this.status = status;
}
}
#MappedSuperclass
public abstract class AbstractHistoryStatus {
private Integer id;
private User author;
private Date date;
public AbstractHistoryStatus() {
}
public AbstractHistoryStatus(Integer id, User author, Date date) {
super();
this.id = id;
this.author = author;
this.date = date;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
#Column(name="creation_date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
It is all mapping code for these entities.
in debugger:
both id==500 ==> hibernate understand, that it is same objects.
I try add all data from old database to new database - I get old error(
I fix cause of appearance of this problem. It appearances if I add record to note table:
I highly recommend you write equals() and hashCode() methods. The standard equals()/hashCode() implement referential equality (do 2 objects reference the same memory location). So if hibernate has 2 of the 'same' object in memory, but they don't reference the same memory location then you will see the object show up twice. But if you implement equals() based on primary key being equal, then even if there are two copies of the same object in memory, Hibernate won't give you duplicates.
See the JPA spec:
2.4 Primary Keys and Entity Identity
Every entity must have a primary key. ... The value of its primary key
uniquely identifies an entity instance within a persistence context
and to EntityManager operations
Also see this SO post.