引言
- 在spring jpa 框架中,使用自定义sql 查询返回数据时返回的时一个map 对象;
- 如果想返回我们自己的自定义对象,可以使用如下四种方式
一、HQL查询+实体全参数的构造方法
注:这种方式只能用HQL查询,不能加nativeQuery = true
实体对象:
@Getter
@Setter
public class MyDto {
BigDecimal profitPercent;
String account;
public MyDto () {}
public MyDto (String account, BigDecimal profitPercent) {
this.account= account;
this.profitPercent = profitPercent;
}
}
查询接口
public interface MyRepository extends JpaRepository<MyPo, Long> {
// 注意这里只能用HQL查询,不能加nativeQuery = true
@Query(value = "select new com.my.MyDto(a.account as account, b.profitPercent as profitPercent) from TradeAccount a, TradeOrder b where a.account = b.account and a.account = ?1")
List<MyDto> findMyDtoByAccount(String account);
}
二、实体定义成接口的形式
- 建议使用,使用方便
DTO接口
// 只需要有get方法即可,注意命名要规范
public interface MyDto {
String getAccount();
BigDecimal getProfitPercent();
}
查询接口
public interface MyRepository extends JpaRepository<MyPo, Long> {
// 注意这里只能用HQL查询,不能加nativeQuery = true
@Query(value = "select new com.my.MyDto(a.account as account, b.profitPercent as profitPercent) from TradeAccount a, TradeOrder b where a.account = b.account and a.account = ?1")
List<MyDto> findMyDtoByAccount(String account);
}
三、查寻出Map结果,利用工具类转换成需要的实体
- 不建议使用,效率低还麻烦
实体对象:
@Getter
@Setter
public class MyDto {
BigDecimal profitPercent;
String account;
public MyDto () {}
public MyDto (String account, BigDecimal profitPercent) {
this.account= account;
this.profitPercent = profitPercent;
}
}
查询接口
public interface MyRepository extends JpaRepository<MyPo, Long> {
// 注意这里只能用HQL查询,不能加nativeQuery = true
@Query(value = "select new com.my.MyDto(a.account as account, b.profitPercent as profitPercent) from TradeAccount a, TradeOrder b where a.account = b.account and a.account = ?1")
List<Map<String,Object>> findMyDtoByAccount(String account);
}
Service层处理
@Autowired private MyConvert myConvert;
public List<MyDto> queryList(){
List<Map<String,Object>> list = myRepository.findMyDtoByAccount('xxx');
return myConvert.convertDto(list);
}
四、@SqlResultSetMapping注解实现
- 不建议使用,配置麻烦
DTO实体
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.SqlResultSetMapping;
@Getter
@Setter
@SqlResultSetMapping(
name = "myDto",
entities = {
@EntityResult(
entityClass = MyDto.class, // 当前类名
fields = {
@FieldResult(name = "account", column = "account"),
@FieldResult(name = "profitPercent", column = "profit_percent")
}
)
}
)
public class MyDto{
BigDecimal profitPercent;
String account;
}
查询接口
public interface MyRepository extends JpaRepository<MyPo, Long> {
// 注意这里只能用HQL查询,不能加nativeQuery = true
@Query(value = "select new com.my.MyDto(a.account as account, b.profitPercent as profitPercent) from TradeAccount a, TradeOrder b where a.account = b.account and a.account = ?1")
List<Map<String,Object>> findMyDtoByAccount(String account);
}
其他:
如果你访问github网站比较慢,或者一些资源无法访问你可以看一下这里:网络加速器
关于我
- 关注不迷路,点赞走一波~ 转载请标注~
- 公众号