views:

36

answers:

1

I create 3 tables by Hibernate, how to return a List<task> when set task_status = ? and set create_user_id = ?, task_status in "dotask" table, create_user_id in task table.

How to write the "HQL"? Here is mine, but I can't make it true with it:

String hql="from task t left join dotask d on d.task_status = ? and t.create_user_id = ? limit ?, ?";
Query query=sess.createQuery(hql);
query.set(0,1);
...
query.set(4,2);
List<Task> lt=query.list();

The task.hbm.xml follows:

<class name="com.model.Task" table="task" >
   <id name="id">
       <generator class="native"/>
   </id>
  <property name="name" />
    ...
    ...
  <set name="lu" table="dotask" cascade="save-update" lazy="true">
        <key column="task_id"></key>
        <many-to-many class="com.model.User" column="user_id"></many-to-many>
   </set>
</class>    

And the tables:

CREATE TABLE `dotask` (
  `id` int(11) NOT NULL auto_increment,
  `user_id` int(11) NOT NULL,
  `task_id` int(11) NOT NULL,
  `task_status` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `FKB0F704903D43702C` (`user_id`),
  KEY `FKB0F70490EA675DEC` (`task_id`),
  CONSTRAINT `FKB0F704903D43702C` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
  CONSTRAINT `FKB0F70490EA675DEC` FOREIGN KEY (`task_id`) REFERENCES `task` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


CREATE TABLE `task` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(128) NOT NULL,
  `create_user_id` int(11) NOT NULL,
  `create_time` date NOT NULL,
  `end_time` date default NULL,
  `limit_time` date NOT NULL,
  `day` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `departmentId` int(11) default NULL,
  `name` varchar(50) default NULL,
  `password` varchar(50) default NULL,
  `sex` char(2) default NULL,
  `birthday` date default NULL,
  `address` varchar(200) default NULL,
  `phone` varchar(100) default NULL,
  `mobile` varchar(100) default NULL,
  `remark` varchar(255) default NULL,
  `login` varchar(50) default NULL,
  `email` varchar(200) default NULL,
  `active` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
+1  A: 

Try this instead (not sure because you didn't show the object model and didn't describe all relations):

SELECT t 
FROM Task t LEFT JOIN t.dotask d WITH d.task_status = ? 
WHERE t.create_user_id = ?

And use setMaxResults() and setFirstResult() to limit the results in a portable way.

References

Pascal Thivent
Isn't it better to include an ORDER BY statement when doing pageing?
extraneon
@extraneon You're right of course. But my main point was to avoid using the limit keyword. Anyway, I'm not sure writing the query is even possible in the current state, I don't really understand the mapping.
Pascal Thivent