JPA many to many (intermediate table) / intermediate table many to many

thank CSDN-treemer
thank CSDN-csdndz

1, Example the relationship between the user and the project

Note: a User can create multiple projects, and a Project can have multiple users at the same time

Relation table

1. entity

Users User.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */
@Data
@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    private String name;

    @JsonIgnore
    @JsonIgnoreProperties({"userProjects"})
    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    private List<UserProject> userProjects;
}
project Project.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */
@Data
@Entity
@Table(name="project")
public class Project implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column
    private String name;

    @JsonIgnoreProperties({"project"})
    @OneToMany(mappedBy = "project",fetch=FetchType.EAGER)
    private List<UserProject> userProjects;
}
Corresponding entity of user project intermediate table UserProject.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */

@Entity
@Table(name = "project_user")
@IdClass(UserProjectKeys.class)
public class UserProject implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(targetEntity = User.class, fetch = FetchType.EAGER)
    @Id
    private User user;
    @ManyToOne(targetEntity = Project.class, fetch = FetchType.EAGER)
    @Id
    private Project project;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }
}
Corresponding entity of composite primary key UserProjectKeys.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */
@Data
public class UserProjectKeys  implements Serializable {

    private static final long serialVersionUID = 1L;

    private int user;
    private int project;
}

2. repository

Users UserRepository.java
/**
 * @author LEI
 * Created by LEI on 2020/5/8.
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByName(String name);
}
project ProjectRepository.java
/**
 * @author LEI
 * Created by LEI on 2020/5/8.
 */
@Repository
public interface ProjectRepository extends JpaRepository<Project, Long> {
}
User project u serProjectRepository.java
/**
 * @author LEI
 * Created by LEI on 2020/5/8.
 */
@Repository
public interface UserProjectRepository extends JpaRepository<UserProject, Long> {
}

3. Unit test addition and query

many2many_test1.java
/**
 * @author LEI Created by LEI on 2020/6/29.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class many2many_test1 {
    @Autowired
    UserRepository userRepository;
    @Autowired
    ProjectRepository projectRepository;
    @Autowired
    UserProjectRepository userProjectRepository;

    @Test
    public void test2() {
        Project project = new Project();
        project.setName("project3");
        projectRepository.save(project);
        User user = new User();
        user.setName("user3");
        userRepository.save(user);
        UserProject userProject = new UserProject();
        userProject.setProject(project);
        userProject.setUser(user);
        userProjectRepository.save(userProject);
    }

    @Test
    public void test3() {
        userRepository.findAll();
    }
}

2, Give examples of the relationship between the author and the book

A Book can have more than one Author, and one Author can publish more than one Book at the same time

Table relation

1. entity

Author Author.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */
@Data
@Entity
@Table(name="author")
public class Author implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    @JsonIgnoreProperties("authors")
    @ManyToMany(cascade = CascadeType.REMOVE,fetch=FetchType.LAZY)
    @JoinTable(name = "t_author_book")
    private List<Book> books;

}
book Book.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */
@Data
@Entity
@Table(name="book")
public class Book implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    @JsonIgnoreProperties(value = { "books" })
    @ManyToMany(cascade = CascadeType.REMOVE, mappedBy = "books",fetch=FetchType.LAZY)
    private List<Author> authors;

}

2. repository

Author AuthorRepository.java
/**
 * @author LEI
 * Created by LEI on 2020/5/8.
 */
@Repository
public interface AuthorRepository extends JpaRepository<Author, Long> {
}

book BookRepository.java
/**
 * @author LEI
 * Created by LEI on 2020/5/8.
 */
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}

3. Unit test addition and query

many2many_test2.java
/**
 * @author LEI
 * Created by LEI on 2020/6/29.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class many2many_test2 {

    @Autowired
    BookRepository bookRepository;
    @Autowired
    AuthorRepository authorRepository;

    @Test
    public void test2(){

        Book book = new Book();
        book.setName("<Java From introduction to abandonment");
        bookRepository.save(book);

        Author author = new Author();
        author.setName("ylq");
        author.setBooks(Stream.of(book).collect(Collectors.toList()));

        authorRepository.save(author);
    }

    @Test
    public void test3(){
       authorRepository.findAll();
    }
}

3, Cyclic dependence

For the problem of circular dependence, if only test printing( System.out.println )Then there is the problem of toString. If you need to print to the front end through JSON, it is the problem of serialization. There are many solutions to this problem, so we will not repeat here.

Tags: Java JSON

Posted on Tue, 30 Jun 2020 04:12:20 -0400 by wilzy