Hibernate Error索引:检查行是否存在时为null

时间:2016-11-01 22:24:24

标签: java hibernate

我正在尝试检查数据库中是否存在行。

Word word = (Word) session.createQuery("select 1 from Word w where w.content = :key").setParameter("key",words[i]).uniqueResult();

我也在尝试:

Word word = session.get(Word.class,contentId);

除此之外,我尝试了session.load和其他一些。每次Hibernate都会返回错误: Error indexing: null 要么 Error indexing: no row with the given identifier exists

确实,row不存在,但为什么它不会像session.get那样返回null: http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#get(java.lang.Class,%20java.io.Serializable)。 如果没有找到行,我想创建一个并添加到数据库,但我无法检查它是否存在。

编辑: Word.java

public class Word {

    private String content;
    private Set<Sentence> sentences;

    empty constructor, setters and getters
}

Word.hbm.xml

<class name="Word">
    <id name="content" column="wordId" type="string">
    </id>
    <set name="sentences" inverse="true">
        <key><column name="wordId"/></key>
        <many-to-many class="Sentence" column="sentenceId"/>
    </set>
</class>

Sentence.java

public class Sentence {

    private long id;
    private ProcessedUrl processedUrl;
    private List<Word> words;

    empty constructor, setters and getters
}

Sentence.hbm.xml

<class name="Sentence">
    <id name="id" column="sentenceId">
            <generator class="native"/>
    </id>
    <many-to-one name="processedUrl" column="processedUrlId" not-null="true"/>
    <list name="words">
        <key>
            <column name="sentenceId" not-null="true"/>
        </key>
        <list-index column="idx" />
        <many-to-many class="Word">
            <column name="wordId" not-null="true"/>
        </many-to-many>
    </list>
</class>

0 个答案:

没有答案