首先:我正在使用Spring-Boot Data JPAJava 8。
我的数据库中有一个表,我的实体定义如下:
@Entity
@Table(name="ITEMHOURS")
public class ItemHoursEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;
@Column(name = "YEAR", nullable = false)
private String year;
@Enumerated(EnumType.STRING)
@Column(name = "STATE", nullable = false)
private TypeEnum type;
@Column(name = "HOURVALUE", nullable = false)
private int hourValue = 0;
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "ITEM_ID")
private MyItem item;
//.. some more columns, getters, setters...
}
现在我得到以下选择返回这个结构:
-----------------------
| YEAR | Value | Type |
-----------------------
@Query(value = "Select year as year, sum(hourvalue) as value, state as type from ITEMHOURS h where item_id = :item_id group by h.year, h.state", nativeQuery = true)
public Optional<Collection<TotalValuesProjection>> getYearTotalsForStateByItem(@Param("item_id") int item_id);
它在我的MySQL Workbench. 对于结果,我听说我应该ItemHoursEntity通过使用投影来实现获取与默认不同的结果,所以我尝试创建以下内容:
@Projection(types = { ItemHoursEntity.class })
public interface TotalValuesProjection {
public String getYear();
public int getValue();
public HourTypeEnum getType();
}
现在在我的service班级中,我尝试以下方法:
@Override
public List<ExtendedDataPasser<String, Integer, String>> getTotalAndYearHourValuesForItem(int itemId) {
Optional<Collection<TotalValuesProjection>> projectionOptional = this.hoursRepository.getYearTotalsForStateByItem(itemId);
List<ExtendedDataPasser<String, Integer, String>> entityList = new ArrayList<ExtendedDataPasser<String, Integer, String>>();
projectionOptional.orElseGet(() -> new ArrayList<TotalValuesProjection>()).forEach(entity -> {
entityList.add(new ExtendedDataPasser<String, Integer, String>(entity.getYear(), entity.getValue(), entity.getType().toString()));
});
return entityList;
}
开心每一天1111
catspeake
相关分类