hibernate 定制sql语句的方法:
- sql 中column的顺序非常重要,不然就会出错,一个字段的value到另外一个字段上去。
- 取得默认的hibernate 生成的sql语句,设置org.hibernate.persister.entity.AbstractEntityPersister log级别为debug,下面是打印代码
protected void logStaticSQL() { if ( log.isDebugEnabled() ) { log.debug( "Static SQL for entity: " + getEntityName() ); if ( sqlLazySelectString != null ) { log.debug( " Lazy select: " + sqlLazySelectString ); } if ( sqlVersionSelectString != null ) { log.debug( " Version select: " + sqlVersionSelectString ); } if ( sqlSnapshotSelectString != null ) { log.debug( " Snapshot select: " + sqlSnapshotSelectString ); } for ( int j = 0; j < getTableSpan(); j++ ) { log.debug( " Insert " + j + ": " + getSQLInsertStrings()[j] ); log.debug( " Update " + j + ": " + getSQLUpdateStrings()[j] ); log.debug( " Delete " + j + ": " + getSQLDeleteStrings()[j] ); } if ( sqlIdentityInsertString != null ) { log.debug( " Identity insert: " + sqlIdentityInsertString ); } if ( sqlUpdateByRowIdString != null ) { log.debug( " Update by row id (all fields): " + sqlUpdateByRowIdString ); } if ( sqlLazyUpdateByRowIdString != null ) { log.debug( " Update by row id (non-lazy fields): " + sqlLazyUpdateByRowIdString ); } if ( sqlInsertGeneratedValuesSelectString != null ) { log.debug( "Insert-generated property select: " + sqlInsertGeneratedValuesSelectString ); } if ( sqlUpdateGeneratedValuesSelectString != null ) { log.debug( "Update-generated property select: " + sqlUpdateGeneratedValuesSelectString ); } } }
3. 根据默认的sql语句定制你自己的sql语句,记住一点要遵守column的顺序。