我试图通过jpa在电话簿和用户之间建立关系,当当前登录用户创建联系人时,表电话簿中用户的外键保持为空。我在这里检查了几个问题,但确实没有为我工作。
电话簿
@Entity
@Table(name = "Phonebook")
public class Phonebook {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "phonebook_id")
private Long id;
@Column(name = "phone", length = 15, nullable = false)
private String phoneNumber;
@Column(name = "firstname", length = 50, nullable = false)
private String firstName;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
//getters and setters
用户
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
@Column(name = "email")
private String email;
@Column(name = "password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@org.springframework.data.annotation.Transient
private String password;
@OneToMany(mappedBy = "user")
private List<Phonebook> phonebooks;
//getters and setters
PhonebookController
@RequestMapping(value = {"/home/phonebook"}, method = RequestMethod.GET)
public String showPage(Model model, @RequestParam(defaultValue = "0") int page){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
model.addAttribute("data",phonebookRepository.findAllByUserId(user.getId(),PageRequest.of(page,10)));
model.addAttribute("currentPage",page);
return "/home/phonebook";
}
@PostMapping("/home/phonebook/save")
public String save (Phonebook p){
phonebookRepository.save(p);
return "redirect:/home/phonebook";
}
PhonebookRepository
@Repository("phonebookRepository")
public interface PhonebookRepository extends JpaRepository<Phonebook,Integer> {
List<Phonebook> findAllByUserId(Long id, Pageable pageable);
}
答案 0 :(得分:0)
你要做的就是先创建一个用户对象并设置id,然后保留电话簿。
答案 1 :(得分:0)
您必须将PhoneBook
与User
一起保留。
User u = new User();
// Set properties for your User...
PhoneBook p = new PhoneBook();
// Set properties for your phonebook...
// Store phone book to user:
u.setPhoneBook(Collections.singletonList(p));
userRepository.save(p);