Java 当我的项目中没有任何实体时,如何将本机查询映射到 POJO?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30595445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:52:07  来源:igfitidea点击:

How to map a Native Query to a POJO, when I do not have any Entity on my project?

javamysqlhibernatejpa

提问by JSBach

I am translating an ETL process from a tool to a Java batch API application. In this ETL process. In the current version (using the tool) we have many SQL statements that join different tables in order to generate the desired output. Translating to Java, JPA is now available.

我正在将 ETL 过程从工具转换为 Java 批处理 API 应用程序。在这个 ETL 过程中。在当前版本(使用该工具)中,我们有许多 SQL 语句连接不同的表以生成所需的输出。转换为 Java,JPA 现在可用。

I would like to use native queries. This would be nice because it would not require creating entities for every table used in the query and I could use POJOs for the result of the queries (also, I would not need to rewrite the queries). Reading this answerI know I could use @SqlResultSetMapping. The problem is that I do not have any entity in my project, so I do not know where to put this annotation. Is there anywhere I can put this annotation so the entity manager finds it?

我想使用本机查询。这会很好,因为它不需要为查询中使用的每个表创建实体,而且我可以将 POJO 用于查询结果(另外,我不需要重写查询)。阅读这个答案我知道我可以使用@SqlResultSetMapping. 问题是我的项目中没有任何实体,所以我不知道把这个注释放在哪里。有什么地方可以放置此注释以便实体管理器找到它吗?

PS: in my proof of concepts I am currently manually converting from an array of objects to the POJO, but I really don't like this approach.

PS:在我的概念证明中,我目前正在手动将对象数组转换为 POJO,但我真的不喜欢这种方法。

Adding the @Entityannotation to the POJO will cause my application not to start:

@Entity注释添加到 POJO 将导致我的应用程序无法启动:

Caused by: org.hibernate.HibernateException: Missing table: MyTable

引起:org.hibernate.HibernateException: Missing table: MyTable

I am not sure (searching for it right now), but I think it could be caused by this property in my persistence.xml

我不确定(现在正在搜索它),但我认为这可能是由我的 persistence.xml 中的这个属性引起的

<property name="hibernate.hbm2ddl.auto" value="validate"/>

采纳答案by JSBach

Actually I found the answer I was looking for:

其实我找到了我正在寻找答案

I can define @SqlResultSetMapping's behavior using XML in orm.xml, so this definition:

我可以@SqlResultSetMapping在 orm.xml 中使用 XML定义的行为,所以这个定义:

@SqlResultSetMapping(
        name = "BookValueMapping",
        classes = @ConstructorResult(
                targetClass = BookValue.class,
                columns = {
                    @ColumnResult(name = "id", type = Long.class),
                    @ColumnResult(name = "title"),
                    @ColumnResult(name = "version", type = Long.class),
                    @ColumnResult(name = "authorName")}))

Would be defined in XML like this:

将在 XML 中定义如下:

<sql-result-set-mapping name="BookValueMappingXml">
    <constructor-result target-class="org.thoughts.on.java.jpa.value.BookValue">
        <column name="id" class="java.lang.Long"/>
        <column name="title"/>
        <column name="version" class="java.lang.Long"/>
        <column name="authorName"/>
    </constructor-result>
</sql-result-set-mapping>

Allowing me to do define it without needing an entity.

允许我在不需要实体的情况下定义它。

回答by Conffusion

In the past (before JPA) we used iBatis as ORM tool (now called Mybatis). I'm still a big fan of it because you have a lot of flexibility in the way to write your SQL. You can really optimize your queries, espacially if youwant to decide in which order joins are executed. All SQL statements and mappings (columns to POJO and vice-versa) are done in XML file. In the current version it is also possible to use annotations I think like you would to with JPA.

过去(在 JPA 之前)我们使用 iBatis 作为 ORM 工具(现在称为 Mybatis)。我仍然是它的忠实粉丝,因为您在编写 SQL 的方式上有很大的灵活性。您可以真正优化您的查询,尤其是如果想决定执行连接的顺序。所有 SQL 语句和映射(列到 POJO,反之亦然)都是在 XML 文件中完成的。在当前版本中,我认为也可以像使用 JPA 一样使用注释。

More info: http://mybatis.github.io/mybatis-3/

更多信息:http: //mybatis.github.io/mybatis-3/

回答by MarkOfHall

You can map native sql to POJO using JPA. The POJO just needs @Entity and a @Id. A simple example:

您可以使用 JPA 将本机 sql 映射到 POJO。POJO 只需要@Entity 和@Id。一个简单的例子:

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class TodoQueryModel {

    @Id
    private Long id;

    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "TodoQueryModel [id=" + id + ", description=" + description
            + "]";
    }
}

Some method in your JPA impl:

您的 JPA 实现中的一些方法:

private void queryWithNativeSQL() {
    List<TodoQueryModel> todoList = em.createNativeQuery("SELECT id, description FROM [whatever you want as long as it returns 'id' and 'description' as column names]", TodoQueryModel.class)
        .setParameter(1, "foobar");
        .getResultList();

    for (TodoQueryModel todo : todoList) {
        System.out.println(todo);
    }

    System.out.println("Size: " + todoList.size());
}

You can also use @Column(name="barfoo") to map columns to attributes who's names don't match.

您还可以使用 @Column(name="barfoo") 将列映射到名称不匹配的属性。

The @Id column needs to uniquely identify the instance in the JPA context.

@Id 列需要在 JPA 上下文中唯一标识实例。