我在使用 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);
}
这是我的愿望 list
实体
@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
。
关于java - Spring Hibernate 发现了不止一行具有给定外键的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708878/