java - 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);
}
}
当我尝试保存用户详细信息时,它不会在外键列中插入任何值。有人可以告诉我我做错了什么。
解决方案
您需要手动设置users
字段。Authorities
Hibernate 不会为您填充它。
推荐阅读
- javascript - 图像未在打印预览中呈现
- java - 如何解决数组列表中未知来源的问题?
- tableau-api - 如何使 View 更小 Tableau?
- sapui5 - 如何将项目添加到 JSONModel
- php - 如何删除浏览器中显示的 Xdebug 样式和附加信息?
- javascript - 动态改变元素的索引
- javascript - 如何防止在javascript中提交表单
- javascript - Google Maps JS API v3 - 如何检查和显示多边形点之间的距离
- elasticsearch - ElasticSearch 跨集群 GET by _id
- javascript - 无序列表通过递归函数问题“合并”