这是我第一个使用Spring/Spring Boot的项目。这是一个使用User和Bookmark实体的简单书签服务。对于每个控制器,创建/发布DTO时会创建并验证。如果DTO有效,我实例化一个新的用户或书签。Spring Boot,JPA/Hibernate DTO,ManyToOne
我遇到的问题是,当我创建一个新书签时,书签表中的user_id列为空。我将发布以两个域对象,DTO和控制器开始的代码。
用户
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String username;
private String password;
@Column(unique = true, nullable = false)
private String email;
@Column(name = "role", nullable = false)
@Enumerated(EnumType.STRING)
private Role role;
@OneToMany(mappedBy = "user")
private List<Bookmark> bookmarks;
public User() { }
public Long getId() {
return id;
}
//getters and setters and toString.
}
书签
@Entity
public class Bookmark {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String url;
@Column(length = 2048)
private String description;
@ManyToOne()
private User user;
public Bookmark() { }
//getters and setters and toString.
}
用户DTO
public class UserCreateForm {
@NotEmpty
private String username = "";
@NotEmpty
private String password = "";
@NotEmpty
private String passwordConfirmation = "";
@NotEmpty
@Email
private String email = "";
@NotNull
private Role role = Role.USER;
//getters and setters and toString.
}
书签DTO
public class BookmarkCreateForm {
@NotEmpty
@URL
private String url="";
private String description="";
private Long userId;
public BookmarkCreateForm() { }
//getters and setters and toString.
}
真的只有书签控制器在这里很重要,所以我会跳过UserController,但可以根据需要添加它。
BookmarkController
@RestController
public class BookmarkController {
private final UserService userService;
private final BookmarkSerivce bookmarkSerivce;
@Autowired
public BookmarkController(UserService userService, BookmarkSerivce bookmarkSerivce) {
this.userService = userService;
this.bookmarkSerivce = bookmarkSerivce;
}
@RequestMapping("{userId}/add")
public Bookmark addBookmark(@PathVariable("userId") Long userId, @RequestBody BookmarkCreateForm form) {
User user = userService.getUserById(userId)
.orElseThrow(() -> new NoSuchElementException(String.format("User=%s not found", userId)));
System.out.println(form.getUserId());
Bookmark bookmark = bookmarkSerivce.create(form);
return bookmark;
}
}
而且BookmarkServiceImpl
@Service
public class BookmarkServiceImpl implements BookmarkSerivce {
private final BookmarkRepository bookmarkRepository;
@Autowired
public BookmarkServiceImpl(BookmarkRepository bookmarkRepository) {
this.bookmarkRepository = bookmarkRepository;
}
@Override
public Bookmark create(BookmarkCreateForm form) {
Bookmark bookmark = new Bookmark();
bookmark.setUrl(form.getUrl());
bookmark.setDescription(form.getDescription());
return bookmarkRepository.save(bookmark);
}
}
请显示BookmarkService的代码。 – dunni
对不起,dunni。添加。 – douglas