首页 > 解决方案 > jpa为什么不给外键值加数据

问题描述

我有一个包含用户详细信息的用户表。我还有一个具有用户角色的权限表。用户和权限表具有一对多映射。当我尝试使用 Jpa 保存详细信息时,外键列是空白的,该字段中没有插入数据。我有一个表格,我在其中指定用户的角色以及其他详细信息。

package com.example.StarsProject.Model;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;

@Entity
@Table
@Getter
@Setter
public class Authorities {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String role;
    @ManyToOne(cascade = CascadeType.PERSIST,fetch=FetchType.EAGER)
    @JoinColumn(name = "users_id", referencedColumnName = "id")
    private Users users;

    public Authorities(String role){
        this.role = role;
    }

}

package com.example.StarsProject.Model;

import com.example.StarsProject.DTO.UserDTO;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table
@Getter
@Setter
public class Users {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "first_name")
    private String firstname;
    @Column(name = "last_name")
    private String lastname;
    @Column(unique = true)
    private String email;
    private String password;
    @OneToMany(fetch = FetchType.EAGER,targetEntity = Authorities.class,mappedBy = "users", cascade = CascadeType.PERSIST)
    private  Set<Authorities> authorities;

    public Users(UserDTO userDTO) {
        this.email = userDTO.getEmail();
        this.firstname = userDTO.getFirstname();
        this.lastname = userDTO.getLastname();
        this.password = userDTO.getPassword();
//        Authorities authorities = new Authorities();
//        authorities.setRole(userDTO.getRole());
//        Set<Authorities> set = new HashSet<>();
//        set.add(authorities);
        this.authorities = new HashSet<Authorities>(Arrays.asList(new Authorities(userDTO.getRole())));
    }

}

package com.example.StarsProject.Service;

import com.example.StarsProject.DTO.UserDTO;
import com.example.StarsProject.Model.Users;
import com.example.StarsProject.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsServiceInterface{

    @Autowired
    UserRepository userRepository;

    @Override
    public void storeUserDetails(UserDTO userDTO) {
        Users users = new Users(userDTO);
        userRepository.save(users);
    }
}


当我尝试保存用户详细信息时,它不会在外键列中插入任何值。有人可以告诉我我做错了什么。

标签: javaspring-bootjpa

解决方案


您需要手动设置users字段。AuthoritiesHibernate 不会为您填充它。


推荐阅读