问题描述
(1)在此SpringBoot应用程序上使用@OneToMany和@ManyToOne只会使关系一对一.这个想法是让一个用户可以拥有多个卡.每次将新卡设置为@Post时,它都会更新该卡,而不是为用户创建新卡.
(1) Using @OneToMany and @ManyToOne on this SpringBoot application is only making the relation one to one. The idea is having a User that can have multiple Cards. Every time a new card is @Post, it updates the card instead of creating a new one for User.
(2)任何实现信用卡更新,删除方法的想法.
(2) Any Ideas implementing an update, delete method for credit cards.
信用卡类
@Entity
@Table(name = "CreditCards")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class CreditCard {
@Id
@Column(name = "username", nullable = false)
private String username;
@Column(name = "cardName")
private String cardName;
@Column(name = "cardNumber")
private BigInteger cardNumber;
@Column(name = "expirationDate")
private Integer expirationDate;
@Column(name = "securityCode")
private Integer securityCode;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
@JsonIgnore
private User user;
//For Deserialization
public CreditCard() {}
public CreditCard(String username) {
this.username = username;
}
public BigInteger getCardNumber() {
return cardNumber;
}
public void setCardNumber(BigInteger cardNumber) {
this.cardNumber = cardNumber;
}
public Integer getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Integer expirationDate) {
this.expirationDate = expirationDate;
}
public Integer getSecurityCode() {
return securityCode;
}
public void setSecurityCode(Integer securityCode) {
this.securityCode = securityCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
}
用户类别
@Entity
@Table(name = "Users")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {
@Id
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
@Column(name = "email")
private String email;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
//@JoinColumn(name = "username")
private List<CreditCard> creditCard;
//For Deserialization
public User() {
}
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<CreditCard> getCreditCard() {
return creditCard;
}
public void setCreditCard(List<CreditCard> creditCard) {
this.creditCard = creditCard;
}
}
UserResources类
UserResources Class
@RestController
@RequestMapping("/geektext")
public class UserResource {
@Autowired
private UserRepository userRepository;
//Displays User By Username Search
@GetMapping("/users/{username}")
public User getUserByUsername(@PathVariable String username) {
Optional<User> users = userRepository.findByUsername(username);
if (users.isPresent()) {
return users.get();
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
//Displays List of All Users
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepository.findAll();
}
//Creates a New User
@PostMapping("/users")
public User loadUser(@RequestBody final User user) {
user.setEmail(user.getUsername());
return userRepository.save(user);
}
//Creates a List of New Users
@PostMapping("/users/all")
public List <User> loadAllUsers(@RequestBody final List <User> users) {
return userRepository.saveAll(users);
}
//Updates an Existing User
@PutMapping("/users/{username}")
public User updateUser(@PathVariable String username, @RequestBody User user) {
return userRepository.save(user);
}
//Deletes an Existing User
@DeleteMapping("/users/{username}")
public String deleteUser(@PathVariable String username) {
Optional<User> users = userRepository.findById(username);
if (users.isPresent()) {
userRepository.delete(users.get());
return "User '" + username + "' has been deleted";
} else {
throw new RuntimeException("User '" + username + "' not found");
}
}
}
CreditCardResources类
CreditCardResources Class
@RestController
@RequestMapping("/geektext/users")
class CreditCardResource {
@Autowired
CreditCardRepository cardsRepository;
@Autowired
UserRepository userRepository;
//Displays CreditCard By Username Search
@GetMapping("/{userID}/cards")
public Optional<CreditCard> getCardsByUsername(@PathVariable String userID) throws NotFoundException {
if (!userRepository.existsById(userID)){
throw new NotFoundException("User '" + userID + "' not found");
}
return cardsRepository.findByUsername(userID);
}
//Creates New Card for User
@PostMapping("/{userID}/cards")
public CreditCard loadCard(@PathVariable String userID, @RequestBody CreditCard creditCard) throws NotFoundException {
if (userRepository.existsById(userID)) {
creditCard.setUsername(userID);
}
return userRepository.findByUsername(userID).map(user -> {creditCard.setUser(user);
return cardsRepository.save(creditCard);
}).orElseThrow(() -> new NotFoundException("User '" + userID + "' not found"));
}
}
UserRepository界面
UserRepository Interface
@Repository
public interface UserRepository extends JpaRepository<User, String> {
//Optional<User> findByName(String name);
Optional<User> findByUsername(String username);
}
CreditCardRepository接口
CreditCardRepository Interface
@Repository
public interface CreditCardRepository extends JpaRepository<CreditCard, String> {
Optional<CreditCard> findByUsername(String username);
}
推荐答案
您应该在注解@ManyToOne()中添加值层叠= CascadeType.Persist.
You should add in annotation @ManyToOne() value cascade = CascadeType.Persist.
@ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.Persist)
@JoinColumn(name = "user_id", nullable = false)
@JsonIgnore
private User user;
这篇关于为单个用户创建信用卡时,它只会更新前一张卡,而不会添加新卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!