[英]Spring hibernate more than one row with the given foreign key was found
我在使用JPA存儲庫的findByProfileId()
方法時遇到問題
這是我數據庫中的示例條目(行)。
當我嘗試通過REST( http:// localhost:8080 / rest / test / 21234 ) 請求時 ,其中21234是上表中的profile_id。
這是我的REST服務。
@RequestMapping(path="/{id}", method = RequestMethod.GET)
public ResponseEntity<?> get(@PathVariable Long id){
try {
logger.info("get({})",id);
logger.info("get({})",Lists.transform(wishlistService.get(id), toRestWishlist));
return new ResponseEntity<>(Lists.transform(wishlistService.get(id), toRestWishlist), HttpStatus.OK);
} catch (Exception e) {
// TODO: handle exception
logger.error("{}",e.getMessage());
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
這是WishlistServiceImpl
@Override
public List<Wishlist> get(Long id) {
// TODO Auto-generated method stub
return repo.findByProfileId(id);
}
這是倉庫
@Repository
public interface WishlistRepository extends JpaRepository<Wishlist, Long> {
List<Wishlist> findByProfileId(Long id);
}
這是我的Wishlist
實體
@Entity
@Table(name = "wishlist")
public class Wishlist {
@Id
@GeneratedValue
@Column(name="wish_Id")
private Long wishId;
@OneToOne(cascade= CascadeType.DETACH)
@JoinColumn(name = "profile_id")
private Profile profile;
@OneToMany(
mappedBy = "wishlist",
cascade = CascadeType.DETACH,
orphanRemoval = true
)
private List<Comment> comments;
@NotNull
@Column(name="description")
private String description;
@NotNull
@Column(name="images")
private String images;
@Column(name="created_at")
private Long createAt;
@Column(name="updated_at")
private Long updatedAt;
/* Getters and Setters and toString() */
}
每次我發送請求時,都會在日志中收到此錯誤
2017-12-08 14:15:54.854 INFO 2620 --- [nio-8080-exec-2] c.s.s.web.controller.WishlistController : get(21234)
2017-12-08 14:15:54.858 INFO 2620 --- [nio-8080-exec-2] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist
2017-12-08 14:15:54.858 ERROR 2620 --- [nio-8080-exec-2] c.s.s.web.controller.WishlistController : More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist; nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist
在Repository
中將方法簽名聲明為:
List<Wishlist> findAllByProfile(Profile profile);
而且您必須傳遞諸如new Profile(profileId)
。
另外,您可能必須將Profile
@OneToOne
注釋更改為@ManyToOne
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.