gpt4 book ai didi

java - Spring Boot JPA 多对一 - 根据关联的模型条件获取数据

转载 作者:行者123 更新时间:2023-12-01 19:30:07 24 4
gpt4 key购买 nike

我有两个模型 - 图库类别

Category has many Gallery - @OneToMany

Gallery belongs to Gallery - @ManyToOne

Gallery.java

@Entity(name="Gallery")
public class Gallery {

@ManyToOne
@JoinColumn(name="category_id")
private Category category;

/* other code */
}

类别.java

@Entity(name="Category")
@Table(name="categories")
public class Category {
@OneToMany(mappedBy="category")
private Gallery gallery;
/* other code */
}

GalleryRepository.java

@Repository("galleryRepository")
public interface GalleryRepository extends JpaRepository<Gallery, Long>, SiteInfoCustomRepository {

}

Question: How to fetch gallery data based on category title? I tried EntityManager and JOIN query but it's not returning in desired format.

GalleryService.java

@Override
public List<Gallery> getGallery(String cat) {
// this works fine, fetches gallery and associated category
galleryRepository.findAll();

// I want to fetch gallery data which matches a particular category title

}

最佳答案

您只需在存储库中声明该方法,spring 就会为您创建查询。

Spring仅从方法的名称中推断出查询,如果你想按类别名称获取所有画廊,请像这样声明

@Repository("galleryRepository")
public interface GalleryRepository extends JpaRepository<Gallery, Long>,
SiteInfoCustomRepository {
List<Gallery> findAllByCategoryName(String categoryName);
}

您可以从您的服务中调用此接口(interface),例如:

@Service
public class GalleryService {

@Autowired
GalleryRepository galleryRepository;

public List<Gallery> getGalleriesByCategoryName(String name) {
return galleryRepository.findAllByCategoryName(name);
}
}

关于java - Spring Boot JPA 多对一 - 根据关联的模型条件获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59986506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com