Hibernate JPA @OneToOne 双向在 Spring-Boot 中不工作

Hibernate JPA @OneToOne Bidirectional Not Working in Spring-Boot

我有两个具有双向映射的实体用户和购物车。

当我使用控制器保存和访问实体时,我得到的引用为空。

我在购物车上使用了 mappedBy,但它给用户提供了 null

User.Java

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

@OneToOne(cascade = CascadeType.ALL)
private Cart cart;

//getters and setters and constructor

}

Cart.java

@Entity
public class Cart {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@OneToOne(mappedBy = "cart", cascade = CascadeType.ALL)
private User user;

private String cnameString;

//getters and setters and constructor

}

controller.java

@RestController
public class MainCOntroller {

@Autowired
UserRepository userRepository;

@Autowired
CartRepository cartRepository;

@GetMapping("/")
public void str() {

    Cart cart = new Cart("AnonymousCart");
    cartRepository.saveAndFlush(cart);

    User user = new User("Anonymous", cart);
    userRepository.saveAndFlush(user);

    System.out.println(user + "\n" + cart);
  }
} 

击中 localhost:8080

输出是这样的:-

User [id=1, name=Anonymous, cart=Cart [id=1, user=null, 
cnameString=AnonymousCart]]
Cart [id=1, user=null, cnameString=AnonymousCart]

不确定我要去哪里错了。

1) saveAndFlush() returns 如果在 EntityManager 上调用合并,则必须使用该实体。

2) 您必须维护双方的关系,我没有看到您将用户分配到购物车。

正确的代码如下:

@GetMapping("/")
public void str() {

    Cart cart = new Cart("AnonymousCart");

    // Use the returned cart
    cart = cartRepository.saveAndFlush(cart);

    User user = new User("Anonymous", cart);

    // Use the returned user
    user = userRepository.saveAndFlush(user);

    // assign the user to the cart
    cart.setUser(user);

    System.out.println(user + "\n" + cart);
  }
}