为什么 findById 响应未找到 id 但 findAll 返回具有此 id 的对象

Ilj*_*ovs 1 java spring-data-jpa

我在我的代码中找不到错误。寻求帮助。为什么该方法不findById()返回具有此 id 的此类对象,但findAll()显示具有此 id 的此对象?

这是我的class User

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "login")
    private String login;

    @Column(name = "password")
    private String password;

    @JsonIgnore
    @OneToOne(optional = false, mappedBy = "user")
    private UserDetails userDetails;
}
Run Code Online (Sandbox Code Playgroud)

我的class UserDetails

@Entity
@Table(name = "userdetails")
public class UserDetails {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;

    @OneToOne(optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;
}
Run Code Online (Sandbox Code Playgroud)

我的控制器:

@RestController
public class AnotherUserController {
    private final UserRepository userRepository;

    @Autowired
    public AnotherUserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/demo/{id}")
    public User findById(@PathVariable("id") Long id) {
        return userRepository.findById(id).orElseThrow(() -> new RuntimeException("user not found: " + id));
    }

    @PostMapping("/demo")
    public User save(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping("/demo")
    public Iterable<User> save() {
        return userRepository.findAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的存储库:

public interface UserRepository extends CrudRepository<User, Long> {
}
Run Code Online (Sandbox Code Playgroud)

和日志:

2020-07-05 22:11:30.642 ERROR 13200 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
[Request processing failed; nested exception is java.lang.RuntimeException: user not found: 23] with root cause

java.lang.RuntimeException: user not found: 23
...
..
.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Sha*_*dov 5

好的,所以你有@OneToOne(optional = false)关系,正如你在评论中所说的,这个领域是一个问题。通过 id 查找不会返回用户,因为 hibernate 会返回inner jointo userdetails,并且由于没有匹配的记录 - 没有结果。

所以修复很简单:如果您希望您的用户返回,即使他们与细节没有关系 - 将关系标记为可选 - @OneToOne(optional = true)。然后 Hibernate 将生成left outer join而不是inner join.

如果关系不是可选的(从业务角度来看),那么您不应该允许存在没有详细信息的用户的情况发生。在数据库级别进行检查将是最好的(非空外键等)。

btwfindAll返回结果,因为它会转换为select * from users(无连接),然后在需要时延迟获取详细信息