如何在Spring Boot中从SQL表获取纯Integer类型字段值?
解决Spring Boot中直接获取SQL Integer列纯数值的问题
下面针对不同持久化场景给出直接获取纯数值的方案:
方案1:修改实体类字段类型(JPA场景)
如果你的实体类中rating字段被错误映射为Rating类型,直接将其改为Integer类型即可:
@Entity public class YourEntity { @Column(name = "rating") // 对应SQL表的Integer列 private Integer rating; // 标准getter/setter public Integer getRating() { return rating; } }
查询后调用yourEntity.getRating()就能直接拿到可用于计算的Integer数值。
方案2:使用JPA投影获取单一字段
若不想修改实体类,或仅需获取rating字段,可定义投影接口:
public interface RatingProjection { Integer getRating(); }
在Repository中添加查询方法:
@Repository public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { // 根据实际条件调整查询方法 RatingProjection findRatingById(Long id); }
调用后通过projection.getRating()直接获取纯数值。
方案3:MyBatis直接映射数值
使用MyBatis时,在Mapper接口中直接定义返回Integer的查询方法:
@Mapper public interface YourEntityMapper { @Select("SELECT rating FROM your_table WHERE id = #{id}") Integer getRatingById(Long id); }
调用yourEntityMapper.getRatingById(id)即可直接得到可用于计算的纯数值。
方案4:JPQL/原生SQL直接查询字段
在JPA Repository中编写直接查询rating字段的方法:
JPQL方式
@Repository public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { @Query("SELECT e.rating FROM YourEntity e WHERE e.id = :id") Integer getRatingById(@Param("id") Long id); }
原生SQL方式
@Repository public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { @Query(value = "SELECT rating FROM your_table WHERE id = :id", nativeQuery = true) Integer getRatingById(@Param("id") Long id); }
该方法直接返回Integer类型的纯数值,无需后续处理。
内容的提问来源于stack exchange,提问作者Rupesh SA
相关产品推荐
相关产品推荐

