gpt4 book ai didi

spring - 如何使用 Spring JPA 仅获取实体的选定属性?

转载 作者:IT老高 更新时间:2023-10-28 13:45:29 24 4
gpt4 key购买 nike

我在我的项目中使用 Spring Boot (1.3.3.RELEASE) 和 Hibernate JPA。我的实体如下所示:

@Data
@NoArgsConstructor
@Entity
@Table(name = "rule")
public class RuleVO {

@Id
@GeneratedValue
private Long id;

@Column(name = "name", length = 128, nullable = false, unique = true)
private String name;

@Column(name = "tag", length = 256)
private String tag;

@OneToMany(mappedBy = "rule", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RuleOutputArticleVO> outputArticles;

@OneToMany(mappedBy = "rule", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RuleInputArticleVO> inputArticles;
}

我的存储库如下所示:

@Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
}

在某些情况下,我只需要获取实体 RuleVO 的 idname 属性。我怎样才能做到这一点?我发现一个通知应该可以使用 Criteria API 和 Projections 但如何?提前谢谢了。沃杰科技

最佳答案

更新:

正如已经向我指出的那样,我很懒,这可以很好地完成,因此我在网上查看了一个合适的答案后更新了我的答案。

这是一个如何获取 only id 和 only 名称的示例:

@Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {

@Query("SELECT r.id FROM RuleVo r where r.name = :name")
List<Long> findIdByName(@Param("name") String name);

@Query("SELECT r.name FROM RuleVo r where r.id = :id")
String findNameById(@Param("id") Long id);
}

希望此更新对您有所帮助


旧答案:

仅检索特定属性名称/id 是不可能的,因为这不是 spring 的设计方式,也不是任何 SQL 数据库,因为您总是选择作为实体的行。

你可以做的是查询实体中的变量,例如:

@Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {

public RuleVo findOneByName(String name);
public RuleVo findOneByNameOrId(String name, Long id);
public List<RuleVo> findAllByName(String name);
// etc, depending on what you want
}

您可以根据需要修改这些内容。您的需求。您可以通过 Autowiring 的存储库直接调用这些方法

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/第 5.3 节了解更多选项和示例

关于spring - 如何使用 Spring JPA 仅获取实体的选定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167422/

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