【问题标题】:Jpa adding relationshipsJpa 添加关系
【发布时间】:2018-09-21 10:08:22
【问题描述】:

我在 Spring Boot 中使用 JPA。我是 JPA 的新手。

我有两个实体

User.java

@Entity
@Table(name = "user")
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long id;

    @Column(unique = true, name = "username")
    @NotNull
    private String username;

    @NotNull
    @Column(name = "password")
    private String password;



    @Column(name = "display_name")
    private String displayName;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "user_roles_rel", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "role_id"))
    private Set<Role> roles;

    @Column(name = "profile_picture_path")
    private String profilePicturePath;

}

Role.java

@Entity
@Table(name = "roles")
@Data
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "role_id")
    private long id;

    @Column(name = "role", unique = true)
    private String role;

}

我的要求是我的应用程序将只有 5 个角色,但成千上万的用户拥有这五个角色中的任何一个。当我添加一个新用户时,应该为该用户添加这些角色中的任何一个。每次添加新用户时,上面的代码都会插入一个新角色。如何添加具有现有角色的用户?

这是用于添加新用户的 JSON 数据

{
    "username":"username",
    "password":"password",  
    "roles":[
        {
            "role_id":1
        }
        ],
    "displayName":"Dispaly Name",
    "profilePicturePath":"abc.png"
}

这里我已经在数据库中添加了一个角色 id : 1

当我添加此用户时,我希望插入角色 id 为 1 的用户。

RoleRepository.java

public interface RoleRepository extends JpaRepository<Role, Long> {

    public Role findByRole(String role);

}

UserRepository.java

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUsername(String username);

}

UserService.java

@Service
public class UserService{


@Autowired
UserRepository userRep;

public void addUser(User user) {
    user.setPassword(passwordEncoder().encode(user.getPassword()));
    userRep.save(user);
    }

}

UserController.java

    @PostMapping(path = "/api/user/new_user_without_image")
    public ResponseMessage addUserWithoutImage(@RequestBody User user) {
    userService.addUser(user);
    return new ResponseMessage("The User was added successfully!");
    }

【问题讨论】:

  • 请提供DAO的代码
  • 已更新。请看一下
  • 插入方法在哪里?
  • 在调用插入之前打印Role对象,并检查它们的id字段是否填写正确。角色字段上的CascadeType.ALL 也是错误的,因为您的角色表基本上是一个字典,它不需要持久化(Cascade.ALL 包括持久化)。

标签: java json spring-boot spring-data-jpa


【解决方案1】:

我认为你必须在你的用户类@OneToMany 和你的角色类@ManyToOne 注释中插入。

类角色:

@OneToMany(mappedBy = "user")
private Set<Role> roles = new HashSet<>();

班级用户:

@ManyToOne
@JoinColumn(name = "user_id")
public User user;

【讨论】:

    【解决方案2】:

    以下示例适用于我。

    学生.java

    package com.techoffice.example.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    
    
    @Entity
    @Table(name = "STUDENT")
    public class Student {
    
        @Id
        @SequenceGenerator(name="student_seq", sequenceName="student_seq")
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="student_seq")
        private int id;
    
        @Column(name="STUDENT_NAME")
        private String studentName;
    
        @ManyToOne
        @JoinColumn(name = "SCHOOL_ID")
        private School school;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public School getSchool() {
            return school;
        }
    
        public void setSchool(School school) {
            this.school = school;
        }
    
        public String getStudentName() {
            return studentName;
        }
    
        public void setStudentName(String studentName) {
            this.studentName = studentName;
        }
    
        @Override
        public String toString() {
            return id + " " + studentName;
        }
    
    
    }
    

    School.java

    package com.techoffice.example.model;
    
    import java.util.List;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "School")
    public class School {
    
        @Id
        @SequenceGenerator(name="school_seq",sequenceName="school_seq")        
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="school_seq")
        private int id;
    
        private String name;
    
        @OneToMany(mappedBy = "school", cascade = CascadeType.ALL)
        private List<Student> students;
    
        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 List<Student> getStudents() {
            return students;
        }
    
        public void setStudents(List<Student> students) {
            for (Student student: students){
                student.setSchool(this);
            }
            this.students = students;
        }
    
    
    }
    

    程序

    package com.techoffice.example;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    
    import com.techoffice.example.model.School;
    import com.techoffice.example.model.Student;
    
    public class Appl {
        public static void main(String[] args){
            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( "techoffice.example" );
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            try{
                entityManager.getTransaction().begin();
                Student student1 = new Student();
                student1.setStudentName("Test 1");
                Student student2 = new Student();
                student2.setStudentName("Test 1");
    
                List<Student> students = new ArrayList<Student>();
                students.add(student1);
                students.add(student2);
    
                School school = new School();
                school.setName("School 1");
                school.setStudents(students);
                entityManager.persist(school);
    
                // 
                List<Student> results = entityManager.createQuery("From Student", Student.class).getResultList();
                for (Student result: results){
                    System.out.println(result.toString());
                }
    
                entityManager.getTransaction().commit();
                entityManager.close();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                // close the factory and release any resource it holds.
                entityManagerFactory.close();   
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多