Spring Boot实现按Owner ID筛选展示对应宠物列表的问题
解决Spring Boot按Owner ID筛选宠物列表的问题
1. 完善Pet实体类
你的Pet实体缺少与Owner关联的ownerId字段,需要补充该字段完成数据库映射:
@Entity @Table(name = "pets") public class Pet { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) // 建议添加自增策略,避免手动赋值ID的问题 private Long id; private String name; private String breed; private int age; private double weight; // 新增与Owner关联的字段,对应数据库的owner_id列 @Column(name = "owner_id") private Long ownerId; public Pet() {} public Pet(String name, String breed, int age, double weight) { this.name = name; this.breed = breed; this.age = age; this.weight = weight; } // 补充所有字段的getter和setter方法(必须包含ownerId) }
2. 修改控制器方法,接收Owner ID参数
控制器需要接收前端传递的ownerId参数,再调用Service层查询对应宠物:
@GetMapping("/owner_pets") public String getPetsByOwnerId(@RequestParam("ownerId") Long ownerId, Model model) { // 传入ownerId查询匹配的宠物列表 model.addAttribute("pets", petService.getPetsByOwnerId(ownerId)); return "owner_pets"; }
3. 实现Service层的按ID查询逻辑
首先在PetRepository中定义查询方法(需继承JpaRepository):
public interface PetRepository extends JpaRepository<Pet, Long> { // JPA会自动解析方法名生成SQL,查询owner_id匹配的宠物 List<Pet> findByOwnerId(Long ownerId); }
然后在PetService中实现对应的业务方法:
@Service public class PetService { @Autowired private PetRepository petRepository; public List<Pet> getPetsByOwnerId(Long ownerId) { return petRepository.findByOwnerId(ownerId); } }
4. 前端按钮传递Owner ID参数
如果使用Thymeleaf渲染Owner列表页面,在「pets」按钮的链接中携带当前Owner的ID:
<!-- Owner列表中的按钮示例 --> <a th:href="@{/owner_pets(ownerId=${owner.id})}" class="btn btn-primary">查看宠物</a>
如果是纯HTML页面,直接通过URL拼接参数:
<a href="/owner_pets?ownerId=1" class="btn btn-primary">查看宠物</a>
(注意将1替换为实际的Owner ID变量)
内容的提问来源于stack exchange,提问作者kerniuss
相关产品推荐
相关产品推荐

