Spring 引导,JPA/Hibernate DTO,ManyToOne

Spring Boot, JPA/Hibernate DTO, ManyToOne

这是我使用 Spring/Spring Boot 的第一个项目。这是一个带有用户和书签实体的简单书签服务。对于每个控制器,都会在 creation/post 上创建并验证 DTO。如果 DTO 有效,我将实例化一个新用户或书签。

我遇到的问题是,当我创建新书签时,书签 table 中的 user_id 列为空。我将 post 代码从两个域 objects、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,但如果需要可以添加它。

书签控制器

@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);
}
}

我是个白痴。解决方案很简单,在 dunni 要求我 post BookmarkService 后我才意识到。

BookmarkCreateForm(DTO)没有用户 属性。所以在 BookmarkService 中,当设置 Bookmark 对象的属性时,用户永远不会被设置。显然 JPA/Hibernate 无法映射不存在的用户。

代码:

public class BookmarkCreateForm {

@NotEmpty
@URL
private String url="";

private String description="";

private User user;

public BookmarkCreateForm() { }

//getters / setters
}

书签服务

@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());
    bookmark.setUser(form.getUser());

    return bookmarkRepository.save(bookmark);
}

}

书签控制器

@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)));

    form.setUser(user);
    Bookmark bookmark = bookmarkSerivce.create(form);

    return bookmark;
}

}