2011-04-07 96 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)