2011-04-07 71 views
0

我已经编写了接受方法名称作为参数的类级JSR-303约束注释。您设置为参数的方法名称应该返回一个布尔值。自定义验证器中的查询

我有实体Foo字段代码,validFrom和validTill。该代码必须每次都是唯一的。 示例: 两个实体('AAA',1.1.2010,31.12.2010)和('AAA',1.5.2011,31.5.2011)都OK 两个实体('AAA',1.1.2010,31.12.2010 )和('AAA',1.2.2010,31.3.2012)是错误的

现在我需要编写验证方法,检查代码是否唯一。 我写道:

public boolean isUnique() { 
    if (logger.isDebugEnabled()) logger.debug("Before select"); 
    return entityManager.createQuery("select count(o) from Currency o where " + 
      "o.code = :code and (" + 
      "(o.validFrom between :validFrom and :validTill) or " + 
      "(o.validTill between :validFrom and :validTill) or " + 
      "(:validFrom between o.validFrom and o.validTill))", 
      Long.class) 
      .setParameter("code", getCode()) 
      .setParameter("validFrom", getValidFrom()) 
      .setParameter("validTill", getValidTill()) 
      .getSingleResult() == 0; 
} 

我钻进相当无限循环

 
DEBUG http-8080-2 ch.laic.bsatrak.domain.base.BaseEntity - Before select 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - processing flush-time cascades 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - dirty checking collections 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections 
DEBUG http-8080-2 org.hibernate.pretty.Printer - listing entities: 
DEBUG http-8080-2 org.hibernate.pretty.Printer - ch.laic.bsatrak.domain.base.Currency{id=50, createdBy=, editedBy=, createdAt=2011-04-07T14:54:52.233+02:00, validFrom=2010-01-01T00:00:00.000+01:00, code=CODE, validTill=2010-12-31T00:00:00.000+01:00, suspended=false, version=0, editedAt=null} 
DEBUG http-8080-2 org.hibernate.engine.ActionQueue - changes must be flushed to space: bs_currency 
DEBUG http-8080-2 ch.laic.bsatrak.domain.base.BaseEntity - Before select 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - processing flush-time cascades 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - dirty checking collections 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects 
DEBUG http-8080-2 org.hibernate.event.def.AbstractFlushingEventListener - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections 
DEBUG http-8080-2 org.hibernate.pretty.Printer - listing entities: 
DEBUG http-8080-2 org.hibernate.pretty.Printer - ch.laic.bsatrak.domain.base.Currency{id=50, createdBy=, editedBy=, createdAt=2011-04-07T14:54:52.233+02:00, validFrom=2010-01-01T00:00:00.000+01:00, code=CODE, validTill=2010-12-31T00:00:00.000+01:00, suspended=false, version=0, editedAt=null} 

我该怎么做正确的方式?

回答

0

有必要设置FlushMode。默认值是Auto,并且在查询框架尝试刷新可能影响查询的所有实体之前。

.setFlushMode(FlushModeType.COMMIT)