JPA 查询返回 Object[] 而不是所需的实体

3 java sql-server jpa

我使用此代码对 SQL Server 数据库进行查询:

List<Continent> continents = new ArrayList<>();
        List<Object[]> tuples = (List<Object[]>) em.createNativeQuery("SELECT * FROM Continents").getResultList();
        for (Object[] tuple : tuples) {

            System.out.println(tuple[0]);

        }
        return continents;
Run Code Online (Sandbox Code Playgroud)

我使用此代码是因为我无法直接从数据库中获取所需的实体类型(大陆)。

我的查询应该是什么样的?

这是我的大陆课程的开始:

@Entity
@Table
public class Continent implements Serializable {
    @Column(name = "Name")
    private StringProperty name;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ContinentID")
    private IntegerProperty continentId;
    @OneToMany(mappedBy="continent")
    private Connection connection;
    List<Country> countries;


    public Continent(String naam) throws SQLException {
        name = new SimpleStringProperty(naam);
        continentId = new SimpleIntegerProperty();
    }

    protected Continent()
    {}
Run Code Online (Sandbox Code Playgroud)

这是我的 persistence.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="HOGENT1415_11" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>domain.Continent</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=HOGENT1415_11"/>
      <property name="javax.persistence.jdbc.user" value="sa"/>
      <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
      <property name="javax.persistence.jdbc.password" value="root"/>
    </properties>
  </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

Vla*_*mir 5

如果您使用本机查询,您应该提供结果类:

List<Continent> tuples = em.createNativeQuery("SELECT * FROM Continents", Continent.class).getResultList();
Run Code Online (Sandbox Code Playgroud)

或者只使用 jpql 查询:

List<Continent> tuples = em.createQuery("SELECT c FROM Continent c", Continent.class).getResultList();
Run Code Online (Sandbox Code Playgroud)

在第二个示例中,结果类是可选的,但这样您就可以获得TypedQuery并可以避免强制转换。请注意,在 jpql 的情况下,您提供实体名称,而不是像本机查询中那样提供表名称。