SpringBoot-Spring Data Jpa Cascade Operation Many-to-One Traverse, Data Insertion

Keywords: Java Database Attribute Session

 

  • Entity class

  • This operation is a multi-user-to-Role operation, with User as the main object
  1. The parametric constructor must be retained
  2. Don't override the toString method in entity classes, which can cause a lot of unnecessary trouble (after all, values are passed in the project and things are not done in the console)
  • User (Principal Entity Class)
  1. Note @Entity @Id @GeneratedValue @ManyToOne and @JoinColumn
  2. @ ManyToOne is labeled with @JoinColumn for many-to-one relationships, and User associates roles with foreign key role_id
package com.chen.jap.model;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "user")//If object attributes are inconsistent with database table names, they are used to indicate
public class User implements Serializable {

    private static final long serialVersionUID = 4122384962907036649L;

    @Id   // Indicate id
    @GeneratedValue(strategy = GenerationType.IDENTITY)   //  Automatic generation, detection of maximum self-increasing
    @Column(name = "id", length = 100)//If object attributes are inconsistent with database fields, they are used to indicate
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private String sex;

    @ManyToOne
    @JoinColumn(name = "role_id")//Specify the current entity foreign key
    private Role role;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

}
  • Role (sub-entity class)

  1. Note @Entity @Id @GeneratedValue @OneToMany and the attribute cascade in it

  2.  

  • package com.chen.jap.model;
    
    import javax.persistence.*;
    import java.io.Serializable;
    import java.util.List;
    
    @Entity
    @Table(name = "role")
    public class Role implements Serializable {
    
        private static final long serialVersionUID = 4122384962907036647L;
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id",length = 100)
        private Integer id;
        private String name;
    
        @OneToMany(cascade = CascadeType.ALL,mappedBy = "role")
        private List<User> users;
    
        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 List<User> getUsers() {
            return users;
        }
    
        public void setUsers(List<User> users) {
            this.users = users;
        }
    
    }
    

 

  • Test Code Cascade Query

  • The test used here is the junit4 test
  • @Repository
    public interface UserDAO extends JpaRepository<User,Long> {
        //In the interface, just write custom code. The general CRUD has been inherited in JpaRepository.
    }

     

  • @Test
        public void findAll() {
            List<User> all = this.dao.findAll();
            Iterator<User> it = all.iterator();
            while (it.hasNext()) {
                User user = it.next();
                System.out.println(user.toString());
                System.out.println(user.getRole().toString());
            }
        }

     

  • Operation result

  • Wrong demonstration

  • Notice here that role is given in the Jpa Repository generic, that is, Role is the main body.
  • @Repository
    public interface RoleDAO extends JpaRepository<Role,Integer> {
    }
    

     

  • @Test
        public void findAll2() {
            List<Role> all = this.roleDAO.findAll();
            Iterator<Role> it = all.iterator();
            while (it.hasNext()) {
                Role role = it.next();
                Iterator<User> iterator = role.getUsers().iterator();
                while (iterator.hasNext())
                    System.out.println(iterator.next());
            }
        }

     

  • Operation result

 

  • The object relationship we configure is a single relationship with User as the main body. Here, only Role information can be obtained by this operation. User has no data.

 

  • Cascading Insertion of Test Code

  1. If only User is loaded into Role, only Role data is inserted after running
  2. If you only load Role into User, insert two, but the associated foreign key field is empty, that is to say, the association fails.
  • @Test
        public void save() {
            User user = new User();
            user.setUsername("testMax");
            user.setPassword("9696");
            user.setSex("female");
            user.setAge(99);
            Role role = new Role();
            role.setName("testMax");
            ArrayList<User> users = new ArrayList<>();
            users.add(user);
    //Object Mutual Installation Link
            role.setUsers(users);
            user.setRole(role);
            Role save = this.roleDAO.save(role);
            System.out.println(save.toString());
        }

     

  • Operation result

  1. As noted above, here is the Role given by generics in the DAO interface, that is to say, Role is the main body.
  2. If User is the main body, insertion fails, foreign key constraints, Session status

 

Chenyb takes notes with him just for his own convenience

2019-04-05

 

 

 

 

 

 

 

 

 

 

Posted by jabapyth on Thu, 02 May 2019 23:00:40 -0700