Summary of some common methods of HibernateTemplate integrated by Spring and Hibernate

Source: Internet
Author: User

1: get/load access to a single piece of data

  1. Public Teacher getTeacherById (Long id ){
  2. Return (Teacher) this. hibernateTemplate. get (Teacher. class, id );
  3. }
  4. Public Teacher getTeacherById (Long id ){
  5. Return (Teacher) this. hibernateTemplate. load (Teacher. class, id );
  6. }

2: find/iterate query operation

  1. Public Iterator getTeachersByAge (int age ){
  2. IteratorIterator=Null;
  3. // Use the find Method
  4. ListList= (List) this. hibernateTemplate (). find ("from Teacher t where t. age>? ", New Integer (age ));
  5. Iterator=List. Iterator ();
  6. // Use the iterator Method
  7. Iterator=This. HibernateTemplate (). iterate ("from Teacher t where t. age>? ", New Integer (age ));
  8. Return iterator;
  9. }

The difference between find and iterato is that iterate uses N + 1 queries. for a large number of queries, for example, to query 10000 records, iterate needs to execute 10000 + 1 query, find and iterate should be based on the actual

For frequently written objects, use the find query. For some read-only data objects, use the iterate operation because the iterate operation uses the Hibernate cache mechanism.

3: save/update/saveOrUpdate/delete: save/update/delete

 
  1. Public void save (Teacher teacher ){
  2. This. hibernateTemplate. save (teacher );
  3. }
  1. Public void update (Teacher teacher ){
  2. This. hibernateTemplate. update (teacher );
  3. }
  1. Public void update (Teacher teacher ){
  2. This. hibernateTemplate. saveOrUpdate (teacher );
  3. }

  1. Public void update (Teacher teacher ){
  2. This. hibernateTemplate. delete (teacher );
  3. }

4: bulkUpdate: Batch delete or update

BulkUpdate provides batch deletion and update, which are directly converted to the corresponding update/delete SQL for batch deletion and update.

  1. Public void batchDelete (String name, int age ){
  2. This. hibernateTemplate. bulkUpdate ("delete Teacher whereName=? AndAge=? ", New Object [] {name, age });
  3. }
  1. Public void batchDelete (String name, String newName ){
  2. This. hibernateTemplate. bulkUpdate ("update Teacher setName=? WhereName=? ", New Object [] {newName, name });
  3. }
In this case, you must manually clear the cache of related objects in Hibernate (including Level 1 cache and level 2 cache) by using the bulkUpdate operation)

5: execute Core Method

  1. Public Object execute (HibernateCallBack action, boolean exposeNativeSession) throws DataAccessException {
  2. // Obtain a Session
  3. SessionSession=GetSession();
  4. // Whether the current session is in the transaction
  5. BooleanExistingTransaction=SessionFactoryUtils. IsSessionTransactional (session, getSessionFactory ());
  6. FlushModePreviusflushmode=Null;
  7. Try {
  8. Previusflushmode=ApplyFlushMode(Session, existingTransaction); // apply the flush Mode
  9. EnableFilters (session );
  10. // Session exposed to action
  11. SessionSessionToExpose= (ExposeNativeSession? Session: createSessionProxy (session ));
  12. // Execute action
  13. ObjectResult=Action. DoInHibernate (sessionToExpose );
  14. FlushIfNecessary (session, existingTransaction );
  15. Return result;
  16. } Catch (HibernateException ex ){
  17. Throw convertHibernateAccessException (ex );
  18. } Catch (SQLException ex ){
  19. Throw convertJdbcAccessException (ex );
  20. } Catch (RuntimeException ex ){
  21. Throw ex;
  22. } Finally {
  23. // If the session is in the transaction, the session is not closed.
  24. If (existingTransaction ){
  25. DisableFilters (session );
  26. If (previusflushmode! = Null ){
  27. Session. setFlushMode (previusflushmode );
  28. }
  29. } Else {
  30. // Release the session
  31. SessionFactoryUtils. releaseSession (session, getSessionFactory ());
  32. }
  33. }
  34. }
* HibernateCallBack, which is generally used to implement specific business logic

* ExposeNativeSession: A boolean value that must be exposed to the actual session Object of HibernateCallBack, rather than a proxy object.


6: Generally, the execute method is used only when the methods provided by HIberateTemplate cannot meet the requirements. Its usage is as follows,

  1. Public void createDatabaseSchema () throws DataAccessException {
  2. HibernateTemplateHibernateTemplate=NewHibernateTemplate (this. sessionFactory );
  3. // Call the execute method of HibernateTempalte
  4. HibernateTemplate.exe cute (new HibernateCallback (){
  5. Public Object doInHibernate (Session session) throws HibernateException, SQLException {// doInHibernate method that implements HibernateCallback
  6. // Specific implementation
  7. ConnectionConn=Session. Connection ();
  8. Final DialectDialect=Dialect. GetDialect (configuration. getProperties );
  9. String []SQL=Configuration. GenerateSchemaCreationScript (dialect );
  10. ExecuteSchemaScript (conn, SQL );
  11. }
  12. });
  13. }
The focus of the execute method is to implement the doInHibernate method of HibernateCallback. It will pass a Session instance, which can be used to operate the database, from this we can see that the advantage of the execute method is that the application does not have to worry about session creation and release, but only needs to process the business logic of interest.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.