NamedQuery并没有实体映射

时间:2017-08-05 15:41:22

标签: spring-boot

我想实现以下目标。我有一个查询,我想运行它并在REST调用中返回行。 我不想将查询映射到物理表,我该如何实现? 我使用Spring Boot 1.5.2。

1 个答案:

答案 0 :(得分:0)

经过一些尝试和修复后,我得到了以下解决方案。 创建一个POJO类,没有@Entity注释。如果找不到,请添加packageScan说明。

public class ActivityReport1 {
    @Column
    private BigInteger id;

    @Column
    private String title;

    //Only getters

    public ActivityReport1(BigInteger id,
                           String title){
        this.id = id;
        this.title = title;
}

在使用@Entity注释的类中创建结果集映射

@SqlResultSetMappings({
        @SqlResultSetMapping(name = "ActivityReport1Mapping",
                classes = {
                        @ConstructorResult(targetClass = ActivityReport1.class, columns = {
                                @ColumnResult(name = "id"),
                                @ColumnResult(name = "title")
                        })
                })
})

添加存储库类

@Repository
@Transactional
public class IActivityReport1Repository {
    @PersistenceContext
    private EntityManager entityManager;

    public List<ActivityReport1> getResults(String userLogin) {
        Query query = entityManager.createNativeQuery(
                "SELECT " +
                        "t.request_id as id, t.request_title as title " +                      
                        "FROM some_table t ", "ActivityReport1Mapping");

        List<ActivityReport1> results = query.getResultList();
        return results;
    }
}

最后,服务impl类。

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ActivityReport1ServiceImpl implements IActivityReport1Service {
    private static final Logger _Logger = LoggerFactory.getLogger(ActivityReport1ServiceImpl.class);

    @Autowired
    private IActivityReport1Repository sessionFactory;

    @Override
    public List<ActivityReport1> runReport(String userLogin) {
        List<ActivityReport1> reportRows = sessionFactory.getResults(userLogin);
        return reportRows;
    }
}

如果你面对&#34;找不到合适的构造函数&#34;,这意味着在Java端它无法将db类型映射到java类型。 在我的情况下,我不得不将id从Long更改为BigInteger,将Timestamp更改为java.util.date。