1

以下是我的 POJO

class User extends AbstractDomainObject{
    private String username;
    private String password;

    //setter and getter
}

class Notification extends AbstractDomainObject{
    private String message;
    private Set<User> notificationFor;

    //setter and getter
}

class AbstractDomainObject{
    private long id;
    // setter and getter
}

以下是上述 POJO 的映射

用户.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="User" table="user">
        <id name="id" type="long" column="id">
            <generator class="native" />
        </id>

            <property name="username" type="string">
            <column name="username" />
        </property>

        <property name="password" type="string">
            <column name="password" />
        </property>
    </class>
 </hibernate-mapping>

通知.hbm.xml

 <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>

         <class name="Notification" table="notification">
            <id name="id" type="long" column="id">
                <generator class="native" />
            </id>

                <set name="notificationFor" table="user_notification" lazy="false" cascade="all">
            <key column="notification_id"/>
            <many-to-many unique="true" class="User" column="user_id"/>
            </set>

                <property name="message" type="string">
            <column name="message" />
            </property>
         </class>
    </hibernate-mapping>

我想要给定用户的通知列表。下面是我的daoimpl。

public List<Notification> getNotification(User user) {

        Session session = null;
        List<Notification> notifications = null;
        try {

            session = getSessionFactory().openSession();
            String queryString = "from Notification notification where notification.notificationFor IN (:user)";
            Query query = session.createQuery(queryString);
            query.setParameter("user", user);
            notifications = query.list();        

        } catch (Exception e) {

            e.printStackTrace();

        }

        return notifications;
    }

上面的代码片段在query.list()行给出错误。错误是 ERROR util.JDBCExceptionReporter - 没有为参数 1 指定值 任何帮助都会很明显。我不知道我错在哪里。

4

1 回答 1

0

User 是一个用户定义的类,hibernate 不知道它。您应该提供 Hibernate 已知的类型。可能是String, Long, int.

我假设 User 有一个 name 字段,并且将相应地执行查询。

query.setParameter("user", user.getName());

此外,您应该将实体类赋予Query类。Query#setResultTransformer可以使用。

Query query = session.createQuery(queryString).setResultTransformer(Transformers.aliasToBean(Notification.class));
于 2013-10-02T12:23:06.047 回答