我目前正在处理一个Sping Boot 应用程序,其中有两个实体,User和Account。Account实体与User之间是多对一的关系。下面是实体的基本结构:
@Table(name = "accounts")
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String currency;
private Double balance = 0.00;
@Column(name = "created_at")
private LocalDateTime createdAt = LocalDateTime.now();
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
}
在我的服务类中,我有一个方法来创建一个与User关联的Account。下面是代码片段:
@Table(name = "users")
@Entity
@Getter
@Setter
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
}
@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
// List<Account> findByUser(User user);
}
public void createAccount(User user, String currency) {
Account account = new Account();
account.setCurrency(currency);
account.setUser(user);
accountRepository.save(account);
}
然而,当我运行我的应用程序时,我遇到了以下错误:
2023-10-10T21:44:06.549+02:00 ERROR 9340 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:777) ~[spring-boot-3.1.4.jar:3.1.4]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:758) ~[spring-boot-3.1.4.jar:3.1.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-3.1.4.jar:3.1.4]
at pl.bartoszmech.BankApp.Application.main(Application.java:31) ~[classes/:na]
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: pl.bartoszmech.BankApp.model.User
我知道此错误与尝试持久化分离的实体有关,但我不确定如何正确地将用户与帐户关联并解决此问题。
有人能指导我如何解决这个问题,并确保用户实体与帐户实体正确关联时,保存在Sping Boot 与Hibernate?任何见解或解决方案将不胜感激。谢谢你,谢谢!
2条答案
按热度按时间olmpazwi1#
如果你使用CommandLineRunner,你应该用@ transmitting注解run方法。来自VN的爱
knsnq2tg2#
我已经回答了一个类似的问题,附在下面。这里account实体与User实体有单向的多对一关系,根据我的说法,反过来会更好地工作,在服务类中,我们使用setUser()将用户设置为account,但请确保您设置的User通过www.example.com(user)保存在表中userRepository.save;
如何修复JPA和Hibernate抛出的传递给持久化的分离实体