1: Generally, most of the codes used to access the database using the Hibernate Session are the same, as shown in the following two methods,
- // Query the Teacher operation
- Ublic Teacher getTeacher (Long id) throws DataAccessException {
- SessionSession=GetSession();
- TeacherTeacher=Null;
- Try {
- Teacher= (Teacher) session. get (Teacher. class, id );
- ...
- } Catch (HibernateException ex ){
- Throw convertHibernateAccessException (ex );
- } Catch (SQLException ex ){
- Throw convertJdbcAccessException (ex );
- } Catch (RuntimeException ex ){
- Throw ex;
- } Finally {
- Session. close ();
- Return teacher;
- }
- // Query Class operations
- Ublic classInfo getTeacher (Long id) throws DataAccessException {
- SessionSession=GetSession();
- ClassInfoClassInfo=Null;
- Try {
- ClassInfo= (ClassInfo) session. get (ClassInfo. class, id );
- ...
- } Catch (HibernateException ex ){
- Throw convertHibernateAccessException (ex );
- } Catch (SQLException ex ){
- Throw convertJdbcAccessException (ex );
- } Catch (RuntimeException ex ){
- Throw ex;
- } Finally {
- Session. close ();
- Return classInfo;
- }
The above two methods are incorrect. A large number of repeated codes may cause maintenance difficulties in the future. Here we can consider separating the specific business logic processing part, instead, it only obtains and releases public sessions.
And exception handling to form a public method, as shown in the following code,
- // Public method after encapsulation
- Ublic Object process (HibernateCallback action) throws DataAccessException {
- SessionSession=GetSession();
- ObjectObj=Null;
- Try {
- Obj=Action. DoInHibernate (session );
- } Catch (HibernateException ex ){
- Throw convertHibernateAccessException (ex );
- } Catch (SQLException ex ){
- Throw convertJdbcAccessException (ex );
- } Catch (RuntimeException ex ){
- Throw ex;
- }
- // Query the Teacher operation
- Public Teacher getTeacher (final Long id) throws DataAccessException {
- Return (Teacher) process (new HibernateCallback (){
- Public Object doInHibernate (Session session) throws HibernateException, SQLException {
- TeacherTeacher= (Teacher) session. get (Teacher. class, id );
- Return teacher;
- }
- });
- }
A callback is a service operation performed by the caller by calling the object provided by the caller. The callback mechanism is generally used in combination with the template method as a mode. The callback mechanism allows the application staff to focus only on business logic implementation,
Instead of processing some underlying general operations, the general operations and business logic can be separated. For example, when using a Callback mechanism in Java database operations, you do not need to worry about opening or closing database connections. You only need to implement relevant data access in Callback, this ensures that the database connection is always closed in time.