这是我使用Spring/Spring Boot的第一个项目。它是一个简单的书签服务,包含用户和书签实体。对于每个控制器,都会创建并验证DTO。如果DTO有效,则会实例化新的用户或书签。
我的问题在于,当我创建新书签时,书签表中的user_id列为空。接下来我将发布两个域对象、DTO和控制器的代码。
User
@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.
}
用户数据传输对象
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.
}
这里只有书签控制器很重要,所以我会跳过用户控制器,但如果需要的话可以添加。
书签控制器
@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);
}
}