gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:56:05 25 4
gpt4 key购买 nike

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

这是我的用户类:

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

我的 类 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;
}

我的 Controller :

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

我的仓库:

public interface UserRepository extends CrudRepository<User, Long> {
}

和日志:

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
...
..
.

enter image description here

最佳答案

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

因此解决方法很简单:如果您希望用户返回,即使他们与详细信息无关 - 将关系标记为可选 - @OneToOne(optional = true)。 Hibernate 然后将生成 left outer join 而不是 inner join

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

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

关于java - 为什么 findById 响应未找到 id 但 findAll 返回具有此 id 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62745294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com