I need help to create mapping Hibernate Annotations (ONE-to-ONE) in java classes for these relation tables:
CREATE TABLE book
(
id_book integer NOT NULL,
isdn character varying(10) NOT NULL,
CONSTRAINT "pk_bookId" PRIMARY KEY ("id_book")
)
CREATE TABLE info
(
id_info serial NOT NULL,
title character varying(200),
author character varying(200),
id_book integer NOT NULL,
CONSTRAINT info_pkey PRIMARY KEY ("id_info"),
CONSTRAINT "info_id_book_fkey" FOREIGN KEY ("id_book")
REFERENCES book ("id_book") MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION,
CONSTRAINT "info_id_book_key" UNIQUE ("id_book")
)
Can anyone help me? Thank you.
You can create one to one relation ship between these two entities like below.
#Entity
#Table(name = "book")
class book{
private int id;
private String isdn;
private Info info;
#Id
#Column(name="id_book", unique=true, nullable=false)
#GeneratedValue
public int getId(){
return this.id;
}
#Column(name="isdn")
public String getIsdn(){
return this.idsn;
}
public void setId(int id){
this.id = id;
}
public void setIsdn(String isdn){
this.isdn = isdn;
}
#OneToOne
#PrimaryKeyJoinColumn
public Info getInfo(){
return this.info;
}
public void setInfo(Info info){
this.info = info;
}
}
#Entity
#Table(name = "info")
class Info{
private int id;
private String title;
private String author;
private Book book;
#Id
#Column(name="id_info", unique=true, nullable=false)
#GeneratedValue
public int getId(){
return this.id;
}
#Column(name="title")
public String getTitle(){
return this.title;
}
public void setId(int id){
this.id = id;
}
public void setTitle(String title){
this.title = title;
}
#OneToOne(mappedBy="info", cascade=CascadeType.ALL)
public Book getBook(){
return this.book;
}
public void setBook(Book book){
this.book = book;
}
public void setAuthor(String author){
this.author = author;
}
#Column(name="author")
public String getAuthor(){
return this.author ;
}
}
Related
I have one-to-one hibernate mapping between class Report and class Flyleaf.
The listed code is successfully executed and the mapping works good.
In my real model the primary key of a report is composed of an "id" and an "index" and so does flyleaf (because its primary key is the primary key of a report).
How can I change my code in order to make the primary key composite (I tried, but an exception was thrown when I want to get list of reports and I also tried to define the key as a PKClass).
(I'm using Hibernate and Spring if this can help)
#Entity
#Table(name="report_t")
public class Report {
private int id, nbPage;
private Flyleaf flyleaf;
public Report() {}
public Report(int id) {
this.id = id;
}
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="nb_page")
public int getNbPage() {
return nbPage;
}
public void setNbPage(int nbPage) {
this.nbPage = nbPage;
}
#OneToOne (fetch = FetchType.LAZY, mappedBy = "report", cascade = CascadeType.ALL)
public Flyleaf getFlyleaf() {
return flyleaf;
}
public void setFlyleaf(Flyleaf flyleaf) {
this.flyleaf = flyleaf;
}
#Override
public String toString() {
return "ID : "+id+"\t nb page : "+nbPage+"\n\t"+flyleaf;
}
}
#Entity
#Table(name="flyleaf_t")
public class Flyleaf {
private int id;
private String title, author, checker;
private Report report;
public Flyleaf() {}
public Flyleaf(int id) {
this.id = id;
}
#GenericGenerator(name = "generator", strategy = "foreign",
parameters = #Parameter(name = "property", value = "report_t"))
#Id
#GeneratedValue(generator = "generator")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column (name="title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column (name="author")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#Column (name="checker")
public String getChecker() {
return checker;
}
public void setChecker(String checker) {
this.checker = checker;
}
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
public Report getReport() {
return report;
}
public void setReport(Report report) {
this.report = report;
}
#Override
public String toString() {
return "Flyleaf [id=" + id + ", title=" + title + ", author="
+ author + ", checker=" + checker + "]";
}
}
hi everyone i just started to learn spring boot and was wondering how can i save objects with many to many relationship through form submission?
say we have two entities of book and publisher
#Entity
public class Book{
private long id;
private String name;
private List<Publisher> publishers;
public Book() {
}
public Book(String name) {
this.name = name;
}
public Book(String name, Set<Publisher> publishers){
this.name = name;
this.publishers = publishers;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "book_publisher", joinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "publisher_id", referencedColumnName = "id"))
public List<Publisher> getPublishers() {
return publishers;
}
public void setPublishers(List<Publisher> publishers) {
this.publishers = publishers;
}
}
#Entity
public class Publisher {
private Long id;
private String name;
private List<Book> books;
public Publisher(){
}
public Publisher(String name){
this.name = name;
}
public Publisher(String name, List<Book> books){
this.name = name;
this.books = books;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToMany(mappedBy = "publishers")
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
and then we have a book repository
public interface BookRepository extends CRUDRepository<Book, Long>{
}
how would crud methods look like in bookcontroller?
the real question is the "connection table" has additional data , for example date the publishing of the book by the publisher , ISBN of the book from that publisher and so on ...
if the answer is yes then it requires another form , and that solves your issue , if not , you receive from the form list of publishers of the book you enter and add them separately to the connection table and the book to the book table through the book repository ...
from my point of view the design of the database is lacking info.
when you will answer to that question, ill try to help you to do it the spring way ...
currenly from db point of view to make such connection between objects you need existing objects . and the first stage fromwise is form for Publisher and form for Book.
many to many is known to be a headache .
i would suggest to add JPA tag to the question, and remove the spring-data .
I have this code (just multiply the number of attributes by ALOT):
#Entity
#Table(name = "MY_TABLE")
#Immutable
public class MyEntity {
#Id
#Column(name = "ID")
private String id;
public static final String PROPERTYNAME_ID = "id";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
/* used by JPA, needs to have same getters/setters as MyEntity */
public class MyEntityCriteria {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Is there a way to share the attributes, getters and setters between those class?? ('extends' doesn't work as it also shares annotations...)
I am making a small library project in Java EE. I have created 3 tables and class with authors, genres and books. Now I am trying to connect it using hibernate, but i haven't ide how confire annotations ... Please help me :)
bookTable:
| id_book | author_id | title | genre_id | description | photo |
genreTable:
| genre_id | genre |
authorTable:
| author_id | author|
It is easy structure:
bookTable.author_id - authorTable.author_id = ManyToMany
bookTable.genre_id - genreTable.genre_id = OneToOne
Below there are my pojo class:
Book
#Entity
#Table(name = "books")
public class Book implements Serializable{
private static final long serialVersionUID = -5057364006691079475L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private Integer user_id;
private Author author;
private String description;
private BookGenre genre;
private String title;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public BookGenre getGenre() {
return genre;
}
public void setGenre(BookGenre genre) {
this.genre = genre;
}
}
Author
#Entity
#Table(name = "author")
public class Author implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "author_id")
private Integer author_id;
#Column(name = "author")
private String author;
public Integer getAuthor_id() {
return author_id;
}
public void setAuthor_id(Integer author_id) {
this.author_id = author_id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Genre
#Entity
#Table(name = "genre")
public class BookGenre implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "genre_id")
private Integer genreId;
#Column(name = "genre")
private String genre;
public Integer getGenreId() {
return genreId;
}
public void setGenreId(Integer genreId) {
this.genreId = genreId;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
}
Should it be a uni-directional or bi-directional association?
Have a look at this example:
https://howtoprogramwithjava.com/hibernate-manytomany-unidirectional-bidirectional/
It even uses your entity names :)
That are entitys and no pojos, but they look good so far. For them you normally don't need to take care. Best way, you autogenerate them after you connected your project with the database. Hibernate will take care for everything. What is more interesting is how your DAO looks, bcz. that is the layer communication with your database. The entity is only the representation of the database table on Java side. I guess you already connected your project with the database?
Please provide your Database Access Object (DAO) for further help. If you havent that so far here you can get help.
the follwing is my hibernate example for one to many relationship
cart java class
#Entity
#Table(name="cart")
public class Solocart {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="carts_id")
int id;
#Column(name="cust_name")
String name;
#OneToMany(mappedBy="cartitem")
Set<Soloitems>soloitem;
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;
}
public Set<Soloitems> getSoloitem() {
return soloitem;
}
public void setSoloitem(Set<Soloitems> soloitem) {
this.soloitem = soloitem;
}
}
next items java file
#Entity
#Table(name="cartitem")
public class Soloitems {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="cart_id")
private int id;
#Column(name="no_item")
private int number;
#ManyToOne
#JoinColumn(name="carts_id")
private Solocart cartitem;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Solocart getCartitem() {
return cartitem;
}
public void setCartitem(Solocart cartitem) {
this.cartitem = cartitem;
}
impl code
Session sn=Util.getSessionFactory().openSession();
sn.beginTransaction();
Solocart crt=new Solocart();
crt.setName("solomon");
Soloitems itm1=new Soloitems();
Soloitems itm2=new Soloitems();
itm1.setNumber(5);
itm2.setNumber(8);
Set<Soloitems>values= new HashSet<Soloitems>();
values.add(itm1);
values.add(itm2);
crt.setSoloitem(values);
sn.save(crt);
sn.save(itm2);
sn.save(itm1);
sn.getTransaction().commit();
sn.close();
System.out.println("sucessfully created");
here one cart should have many items while running both the tanles were updated but
# cart_id, no_item, carts_id
'1', ' 8', NULL
'2', ' 5', NULL
second table
# carts_id, cust_name
'1', ' solomon'
as you see both the tables has been updated but the foreignkey herein this case carts_id didnt get updated in the owner class i have used joincolumn
You have a bi-directional relationship between entities Solocart and Soloitems so in your code you need to maintain the relationship from both sides of entities.
So based on this, in your code you are just setting the Soloitems to Solocart but you missed to set the Solocart to Soloitems, so as mentioned by Predrag add below lines of code to maintain the relationship:
itm1.setCartitem(crt);
itm2.setCartitem(crt);
You are not setting Solocart anywhere to your Soloitems. Try adding this to your code
itm1.setCartitem(crt);
itm2.setCartitem(crt);