我有这些 Postgres 表:
create table deals_new
(
id bigserial primary key,
slip_id text,
deal_type integer,
timestamp timestamp,
employee_id bigint
constraint employee_id_fk
references common.employees
);
create table twap
(
id bigserial primary key,
deal_id varchar not null,
employee_id bigint
constraint fk_twap__employee_id
references common.employees,
status integer
);
create table common.employees
(
id bigint primary key,
first_name varchar(150),
last_name varchar(150)
);
物体:
@Entity
@NoArgsConstructor
@EqualsAndHashCode
@Getter
@Setter
@ToString
@Table(name = "deals_new")
public class DealTwap {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "slip_id")
private String slipId;
...
}
@Entity
@NoArgsConstructor
@Getter
@Setter
@Table(name = "twap")
public class Twap implements Serializable {
@Id
@Column(name = "id")
private long id;
@Column(name = "deal_id")
private String dealId;
@Column(name = "employee_id")
private Long employeeId;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "slip_id", referencedColumnName = "deal_id")
private List<Deal> deals;
}
@Entity
@Table(name = "employees")
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Builder
@Getter
@Setter
@ToString
public class Employee {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "last_name")
private String lastName;
@Column(name = "first_name")
private String firstName;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "account_id")
private Account account;
}
!!笔记!!!Employee
和之间没有关系Twap
我创建了这个 JPA 存盘库:
public interface DealsRepository extends JpaRepository<DealTwap, Long> {
@Query (value =
"SELECT e.first_name, e.last_name "
"FROM common.deals_new d "
"JOIN common.employees e ON e.id = d.employee_id "
"LEFT OUTER JOIN common.twap t on "
" t.deal_id = d.slip_id AND "
" d.timestamp between '11-11-2010' AND '11-11-2011' AND "
" d.deal_type in (1, 2) "
"OFFSET :offset "
"LIMIT :limit ",
nativeQuery = true)
List<ResultDTO> getHistoryAllPairsSearchParam(@Param("offset") int offset,
@Param("limit") int limit);
}
如您所见,我使用此界面得到了结果:
public interface ResultDTO {
String getFirstName();
String getLastName();
}
List<ResultDTO> list = dealsRepository.getHistoryAllPairsSearchParam(...);
for (ResultDTO item : list) {
System.out.println("!!!!!!!!!!!!!!! a " item.getFirstName());
}
当我运行代码时,我得到:
!!!!!!!!!!!!!!! a null
!!!!!!!!!!!!!!! a null
!!!!!!!!!!!!!!! a null
..........
你知道有什么问题吗?结果,我总是得到空值。当我在 SQL 编辑器中运行这个查询时,我得到了正确的结果表。
uj5u.com热心网友回复:
您正在尝试将本机查询结果映射到非物体类。如果我没记错的话,结果列名应该匹配方法名。您是否尝试过为这样的列设定别名?
SELECT e.first_name AS firstName, e.last_name AS lastName
您还阅读过这个Spring Data JPA 将本机查询结果映射到非物体 POJO吗?它看起来与您的情况非常相似。
如果这没有帮助,看起来谷歌有很多关于如何做到这一点的结果本机查询结果在 dto。
0 评论