如何内部加入Hibernate中的两个独立实体

时间:2016-08-08 14:04:44

标签: java oracle hibernate join entity

我有2个实体:DocumentEntity (docNumber (primary key), dateOfFill, ...)FileEntity (id, title, size, ...)。我有一个内部连接为2的HQL查询,它应该在Oracle DB上运行:

String queryStr = "SELECT docNumber " +
             + "FROM DocumentEntity d " +
             + "INNER JOIN FileEntity f " +
             + "ON d.docNumber = f.title " +
             + "WHERE d.date > to_date('01.01.2011','dd.mm.yyyy')"

Query query = em.createQuery(query_string);
return query.getResultList();

当我运行代码段时,我收到异常org.hibernate.hql.ast.QuerySyntaxException: Path expected for join!

我查看了

但没有人解决我的问题。建议的路径不能在此示例中使用(至少它会给出错误的路径错误)。最后一个链接的答案说:

  

只有在实体之间存在关联时才能使用联接。

问题在于我无法关联这两个实体。

问题是: 我如何加入这两个实体?

更新 我的实体是:

@Entity
@Table(name = "DOCUMENT")
public class DocumentEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "DOC_NUMBER", nullable = false)
    private String docNumber;

    @Basic(optional = false)
    @Column(name = "DATE_OF_FILL")
    @Temporal(TemporalType.DATE)
    private Date dateOfFill;

    ...
}

@Entity
@Table(name = "FS_FILE")
public class FileEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "FS_FILE_SEQ", allocationSize = 1, sequenceName = "FS_FILE_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FS_FILE_SEQ")
    @Column(name = "ID", nullable = false)
    protected Long id;

    @Column(name = "TITLE", nullable = false)
    protected String title;

    @Column(name = "MIMETYPE", nullable = false)
    protected String mimetype;

    @Column(name = "FILESIZE", nullable = false)
    protected Long filesize;

    @Column(name = "FILEPATH", nullable = false)
    protected String filepath;

    ...
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,您不需要进行连接,因为您使用条件d.docNumber = f.title限制结果。 只需在where子句中添加条件并使用SQL查询而不是JPQL查询,因为它似乎更符合您的需求。

String sqlString= "SELECT d.docNumber " +
             + "FROM DOCUMENT d, FS_FILE f " +
             + "WHERE d.docNumber = f.title " +
             + "AND d.date > to_date('01.01.2011','dd.mm.yyyy')"


Query query = em.createNativeQuery(sqlString);
return query.getResultList();