我试图在JPA中从本机查询中提取别名,类似于(SUM,COUNT),如果我完全拉动SUM或COUNT ,该方法可以返回整数(仅当我拉动它时)单独)。 但我怎么能用剩下的物体把它拉出来?这是我想要做的样本
@Entity
@Table("hotels")
public class Hotel {
@Column(name="id")
@Id
private int hotelId;
@Column(name="hotel_name")
private String hotelName;
@OneToMany
private List<Availability>list;
private int avaialbeCount; //this one should be Aliased and need to be pulled by none column
}
存储库
public interface HotelRepository extends JpaRepository<Hotel,Integer>{
@Query(value="select h.*,a.count(1) as avaialbeCount from hotels h INNER JOIN availability a on (a.hotel_id=h.hotel_id) group by a.date",nativeQuery=true)
public List<Hotel> getHotels();
}
在上面的存储库中。我试图获得avaialbeCount与酒店列但我无法拉它,但我可以通过删除选择h。*拉它,并保持选择仅COUNT并使方法返回整数而不是酒店
答案 0 :(得分:1)
您可以使用JPQL,类似这样的
@method_decorator(login_required, name='dispatch')
class ContactView(FormView):
要使用此@Query("SELECT new test.Hotel(h.hotelName, count(h)) FROM Hotel h GROUP BY h.hotelName")
构造,您需要像
new test.Hotel(h.hotelName, count(h))
示例:强>
存储库:
public Hotel(String hotelName, Long avaialbeCount) {
this.hotelName = hotelName;
this.avaialbeCount = avaialbeCount;
}
实体:
package test;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface HotelRepo extends JpaRepository<Hotel, Long> {
@Query("SELECT new test.Hotel(h.hotelName, count(h)) FROM Hotel h GROUP BY h.hotelName")
List<Hotel> getHotelsGroupByName();
}
package test;
import javax.persistence.*;
@Entity
@Table(name = "hotels")
public class Hotel {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long hotelId;
@Column(name = "hotel_name")
private String hotelName;
@Transient
private Long avaialbeCount;
public Hotel() {
}
public Hotel(String hotelName) {
this.hotelName = hotelName;
}
public Hotel(String hotelName, Long avaialbeCount) {
this.hotelName = hotelName;
this.avaialbeCount = avaialbeCount;
}
@Override
public String toString() {
return "Hotel{" +
"hotelId=" + hotelId +
", hotelName='" + hotelName + '\'' +
", avaialbeCount=" + avaialbeCount +
'}';
}
}
注释用于指示不在数据库中保留字段。