Skip to content

Library3: API Rest Library Book @ManyToMany @OneToOne CRUD with Swagger

Albert edited this page May 31, 2022 · 19 revisions

Welcome to the cifojava2022-3 wiki!

Spring Boot Projects: Library3

Base project

  • Base project:

New tools

  • Library and Address @Entity

  • 1:1 relationship

  • n:m relationship: inverse-side or owning-side

    • Every @ManyToMany association has two sides and a join table:
      • the owning side
      • the join table for the relationship created
        • the join table must be specified on the owning side.
      • and the non-owning, or inverse, side.
    • If the association is bidirectional, either side may be designated as the owning side.
    • If the relationship is (not) bidirectional, the non-owning side must use the mappedBy element of the @ManyToMany annotation to specify the relationship field or property of the owning side.
  • Annotations:

    • @OneToOne
    • @ManyToMany
    • @JoinTable
  • Example @ManyToMany bidirectional:

       @Entity
       public class User{
    
       @ManyToMany
       @JoinTable(name = "USER_PRODUCT"
              joinColumns = @JoinColumn(name = "USER_FK"),
              inverseJoinColumns = @JoinColumn(name = "PRODUCT_FK"))
       public Set<Product> products
    
    
    
    
       @Entity
       public class Product {
    
       @ManyToMany
       @JoinTable(name = "USER_PRODUCT"
             joinColumns = @JoinColumn(name = "PRODUCT_FK"),
             inverseJoinColumns = @JoinColumn(name = "USER_FK"))
       public Set<User> users
    
  • Example @ManyToMany unidirectional:

        @Entity
        public class User{
        
        }
     
        @Entity
        public class Product {
    
        @ManyToMany
        @JoinTable(name = "USER_PRODUCT"
              joinColumns = @JoinColumn(name = "PRODUCT_FK"),
              inverseJoinColumns = @JoinColumn(name = "USER_FK"))
        public Set<User> users
    
  • Example @OneToOne bidirectional:

       @Entity
       public class Library{
        
       @OneToOne(mappedBy = "address", cascade = CascadeType.ALL)
       private Address address;
    
    
    
       @Entity
       public class Address{
    
       @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
       @JoinColumn(name = "LIBRARY_FK", nullable = false)
       private Library library;
    

Versions

  • version 1.0 : basic project:

    • Library, Address and Book @Entity without basic CRUD operations (Read and Create)
    • without assigning Library <n:m> Book and Library <1:1> Address
    • H2 : library3 created
    • included swagger
  • version 2.0 : test (JUnit, unitary test) basic project creating:

    1. tables (DDL create and update)
    2. objects and
    3. assign Library <n:m> Book bidirectional by LIBRARY_BOOK_JOIN_TABLE
    4. @ManyToMany Library <n:m> Book bidirectional by LIBRARY_BOOK_JOIN_TABLE

    @ManyToMany

Clone this wiki locally