您好我正在使用Hibernate和HSQL实现一个简单的应用程序。然而Hibernate表现得很奇怪!我想在两个值之间查询一些实体,但是只返回一个实体而不是整个列表。
这是我的方法。
@Override
public List<ClientConnectionEntity> getConnectionBetween(long start, long end) {
Session session = sessionFactory.openSession();
Query query = session.createQuery("FROM com.cayetano.persistense.entities.ClientConnectionEntity c" +
" WHERE c.connectionTime between :start and :end ")
.setParameter("start", start)
.setParameter("end", end);
List<ClientConnectionEntity> list = query.list();
session.close();
return list;
}
@Override
public void saveConnection(ClientConnectionEntity entity) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.persist(entity);
transaction.commit();
session.close();
}
@Test
public void returnsClientConnectionsBetweenTwoDates() {
ClientConnectionEntity entity1 = new ClientConnectionEntity();
entity1.setConnectionTime(1l);
entity1.setClientBrowser("1");
ClientConnectionEntity entity2 = new ClientConnectionEntity();
entity1.setConnectionTime(2l);
entity1.setClientBrowser("2");
ClientConnectionEntity entity3 = new ClientConnectionEntity();
entity1.setConnectionTime(2l);
entity1.setClientBrowser("2");
ClientConnectionEntity entity4 = new ClientConnectionEntity();
entity1.setConnectionTime(4l);
entity1.setClientBrowser("4");
repository.saveConnection(entity1);
repository.saveConnection(entity2);
repository.saveConnection(entity3);
repository.saveConnection(entity4);
assertThat(repository.getConnections().size(),is(4)); // this one is Ok
List<ClientConnectionEntity> expected = repository.getConnectionBetween(2l, 4l);
assertThat(expected.size(), is(2));
}
并且测试失败......
java.lang.AssertionError:
Expected: is <2>
but: was <1>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:865)
at org.junit.Assert.assertThat(Assert.java:832)
答案 0 :(得分:2)
ClientConnectionEntity entity1 = new ClientConnectionEntity();
entity1.setConnectionTime(1l);
entity1.setClientBrowser("1");
ClientConnectionEntity entity2 = new ClientConnectionEntity();
entity1.setConnectionTime(2l);
entity1.setClientBrowser("2");
ClientConnectionEntity entity3 = new ClientConnectionEntity();
entity1.setConnectionTime(2l);
entity1.setClientBrowser("2");
ClientConnectionEntity entity4 = new ClientConnectionEntity();
entity1.setConnectionTime(4l);
entity1.setClientBrowser("4");
您进行了复制/粘贴,忘记更改变量名称