Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Saturday, July 1, 2017

Pessimistic and optimistic locking in Hibernate

1. Intro


When data can be updated by different sessions, sometimes we have to make some additional checking if data are consistent.

From jboss documentation:

Locking is perhaps the most ignored persistence consideration. Most applications tend to ignore thinking about concurrency issues during development, and then smush in a locking mechanism before going into production. Considering the large percentage of software projects that fail or are canceled, or never achieve a large user base, perhaps this is logical. However, locking and concurrency is a critical or at least a very important issue for most applications, so probably should be something considered earlier in the development cycle.

Optimistic locking assumes that the data will not be modified between when you read the data until you write the data. This is the most common style of locking used and recommended in today's persistence solutions. The strategy involves checking that one or more values from the original object read are still the same when updating it. This verifies that the object has not changed by another user in between the read and the write.

Pessimistic locking means acquiring a lock on the object before you begin to edit the object, to ensure that no other users are editing the object. Pessimistic locking is typically implemented through using database row locks, such as through the SELECT ... FOR UPDATE SQL syntax. The data is read and locked, the changes are made and the transaction is committed, releasing the locks.


2. Application structure

All code related with locking is placed in TEST source set. In MAIN - just HibernateUtil and DTO files.



3. build.gradle


Here I have compile dependencies for hibernate and mysql. And test dependencies for slf4j, spock, junit.

group 'com.demien.hibernate'version '1.0-SNAPSHOT'
apply plugin: 'groovy'apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
    mavenCentral()
}

dependencies {
    compile 'org.hibernate:hibernate-core:5.2.10.Final'    
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'

    testCompile group: 'junit', name: 'junit', version: '4.12'    
    testCompile group: 'org.spockframework', name: 'spock-core', version: '1.1-groovy-2.4'    
    testCompile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.25'
}


4. Hibernate Util

Just regular settings for MySQL connection and 3 dto files with annotations which will be  used for testing: Role, User and UserGroup.

package com.demien.hiblock.db;

import com.demien.hiblock.dto.Role;
import com.demien.hiblock.dto.User;
import com.demien.hiblock.dto.UserGroup;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        final Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(User.class);
        configuration.addAnnotatedClass(UserGroup.class);
        configuration.addAnnotatedClass(Role.class);

        configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/test");
        configuration.setProperty("hibernate.connection.username", "test");
        configuration.setProperty("hibernate.connection.password", "test");
        configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        configuration.setProperty("hibernate.hbm2ddl.auto", "update");
        configuration.setProperty("hibernate.show_sql", "true");

        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(builder.build());
    }

    public static Session getSession()
            throws HibernateException {
        return sessionFactory.openSession();
    }
}

5. Base test class

I used separate test files for locking types, so I moved common logic to BaseTest class.

package com.demien.hiblock

import com.demien.hiblock.db.HibernateUtil
import com.demien.hiblock.dto.Role
import com.demien.hiblock.dto.User
import com.demien.hiblock.dto.UserGroup
import org.hibernate.LockMode
import org.hibernate.LockOptions
import org.hibernate.resource.transaction.spi.TransactionStatus
import spock.lang.Specification

abstract class BaseTest extends Specification {
    def session = HibernateUtil.getSession()

    def setupSpec() {
        println "Starting"    }

    def cleanupSpec() {
        println "Done!"    }

    def setup() {
        doInTransaction({
            session.createQuery("delete from User").executeUpdate()
            session.createQuery("delete from UserGroup").executeUpdate()
            session.createQuery("delete from Role").executeUpdate()
        })
    }

    def cleanup() {
        session.clear()
    }

    def doInTransaction(f) {
        def tx = session.getTransaction()
        if (tx.getStatus().equals(TransactionStatus.ACTIVE)) {
            tx.commit()
        }
        tx.begin()
        f()
        tx.commit()
    }

    def doInAnotherSession(f) {
        def oldSession = session        session = HibernateUtil.getSession()
        f()
        session = oldSession
    }

    def doAsync(f) {
        def runnale = new Runnable() {
            @Override            void run() {
                f()
            }
        }
        def thread = new Thread(runnale)
        thread.start()

    }

    def createEntity(entity) {
        doInTransaction({
            session.persist(entity)
        })
    }

    def updateEntity(entity) {
        doInTransaction({
            session.merge(entity)
        })
    }

    def mergeEntity(entity) {
        doInTransaction({
            session.merge(entity)
        })
    }

    def updateEntityInAnotherSession(entity) {
        doInAnotherSession({ updateEntity(entity) })
    }

    def lockEntity(entity) {
        session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(entity)
    }

    def lockEntityInAnotherSession(entity) {
        doInAnotherSession({ lockEntity(entity) })
    }

    def createTestUser() {
        createEntity(new User(1l, "Huan Sebastyan"))
    }

    def loadTestUser() {
        return session.get(User.class, 1L)
    }

    def createTestGroup() {
        createEntity(new UserGroup(1L, "SYSDBA", "Database Administrators"))
    }

    def loadTestGroup() {
        return session.get(UserGroup.class, 1L)
    }

    def createTestRole() {
        createEntity(new Role(1L, "SYSDBA", "Admin role"))
    }

    def loadTestRole() {
        return session.get(Role.class, 1L)
    }

}

6. Optimistic locking

As it was mentioned before, in  optimistic locking strategy we are not locking data physically, we are just checking was data modified before our update or not. We can do that in 2 ways:

  • by version checking - if version is the same - record was not chenged
  • by all fields checking - if all fields remained the same - record was not changed


6.1 by Version

In entity class we have to annotate one field with @Version. This field will be incremented by hibernate every time we update the record.

@Entity
public class User {

    @Id    
    @Column    
    private Long userId;

    @Column    
    private String userName;

    @Version    
    private Long version;



Now let's write the test:

def "it should fail if record was changed by another session"() {
    given:
    createTestUser()
    User loadedUser1 = loadTestUser()
    User loadedUser2 = loadTestUser()
    loadedUser1.setUserName("Updated1")
    loadedUser2.setUserName("Updated2")

    when:
    updateEntityInAnotherSession(loadedUser1)
    updateEntity(loadedUser2)

    then:
    thrown OptimisticLockException

}

In output window we will find:
Hibernate: insert into User (userName, version, userId) values (Huan Sebastyan, 0, 1)
Hibernate: select user0_.userId as userId1_1_0_, user0_.userName as userName2_1_0_, user0_.version as version3_1_0_ from User user0_ where user0_.userId=1
Hibernate: update User set userName=Updated2, version=1 where userId=1 and version=0
Hibernate: update User set userName=Updated2, version=1 where userId=1 and version=0

Hibernate automatically added version fields to UPDATE and WHERE clauses. As a result, last update will fail because record was updated in another session and now it has version 1 , not 0.

6.2 by all fields checking

To entity class we have to add additional annotations:
@Entity
@DynamicUpdate
@OptimisticLocking(type = OptimisticLockType.DIRTY)
public class UserGroup {

    @Id    
    @Column    
    private Long groupId;

    @Column    
    private String groupName;

    @Column    
    private String groupDescription;



Let's write the test:
def "it should fail if record was changed by another session"() {
    given:
    createTestGroup()
    UserGroup loadedGroup1 = loadTestGroup()
    UserGroup loadedGroup2 = loadTestGroup()
    loadedGroup1.setGroupName("Updated name")
    loadedGroup2.setGroupDescription("Updated description")


    when:
    updateEntityInAnotherSession(loadedGroup1)

    updateEntity(loadedGroup2)

    then:
    thrown OptimisticLockException
}


In output we will find:
Hibernate: insert into UserGroup (groupDescription, groupName, groupId) values (Database Administrators, SYSDBA, 1)
Hibernate: select usergroup0_.groupId as groupId1_2_0_, usergroup0_.groupDescription as groupDes2_2_0_, usergroup0_.groupName as groupNam3_2_0_ from UserGroup usergroup0_ where usergroup0_.groupId=1
Hibernate: update UserGroup set groupDescription=Updated description, groupName=Updated name where groupId=1 and groupDescription=Database Administrators and groupName=SYSDBA
Hibernate: update UserGroup set groupDescription=Updated description, groupName=Updated name where groupId=1 and groupDescription=Database Administrators and groupName=SYSDBA

Hibernate automatically adds changed fields to were clause. So if field was changed by another session - it will not match were clause, records will not be updated.

7. Pessimistic locking

Pessimistic locking is applied on Database level. It "physically" locks updated record. And if other session is trying to update it - it has to wait till locking session commits changes. In MySQL for such locking used SELECT ... FOR UPDATE syntax.
In test provided below, we lock record and after that we are trying to update it in another session.
This another session will hung and after 1 minute if will fail by timeout with LockTimeout exception.


def "it should throw the exception on trying to update locked record"() {
    given:
    createTestRole()
    Role role1 = loadTestRole()

    lockEntity(role1)

    when:
    doInAnotherSession({

        Role role2 = loadTestRole()
        role2.setRoleDescription("Updated description")
        mergeEntity(role2)

    })

    then:
    thrown LockTimeoutException

}

Output:
Hibernate: insert into Role (roleDescription, roleName, roleId) values (?, ?, ?)
Hibernate: select roleId from Role where roleId =? for update
Hibernate: select role0_.roleId as roleId1_0_0_, role0_.roleDescription as roleDesc2_0_0_,
Hibernate: update Role set roleDescription=?, roleName=? where roleId=?
12:59:15,754  WARN SqlExceptionHelper:129 - SQL Error: 1205, SQLState: 41000
12:59:15,755 ERROR SqlExceptionHelper:131 - Lock wait timeout exceeded; try restarting transaction
12:59:15,756  INFO AbstractBatchImpl:193 - HHH000010: On release of batch it still contained JDBC statements
12:59:15,756 ERROR ExceptionMapperStandardImpl:39 - HHH000346: Error during managed flush [could not execute statement]


As you can see from logs, by SELECT for UPDATE record was locked. And UPDATE in another session was not update to update the record.


8. The end.

Source code can be downloaded from here.

Wednesday, June 24, 2015

EasyJDBC: using JDBC in Hibernate style

1. Intro 

This post about just one file EasyJDBC.java which I developed just for checking: is it possible to create lightweight alternative to Hibernate or not.  

Of course, Hibernate framework is very popular, and it's hard to find complex application which is working with databases and not using Hibernate. It gives to developer a lot of tools "out of the box" like lazy-initialisation, working with one-to-many/many-to-many relations, caching and many others.  It's like a "space-ship" which can do do almost everything, even to reach the starts.

But sometimes in case of  small simple application, I was thinking like: "why am I using hibernate? In that project I'm using less than 1% of it functionality!". For some simple applications  I don't need a "space ship" - for them "bike" will be well enough! So decided to think:  how can I avoid using that tool which takes so much megabytes in war file? The first answer was, of course, JDBC. But everyone who used JDBC, was dreaming about something like Hibernate with easy mapping of class fields to table columns using annotations, easy mapping to java objects all database operations :) Because creating queries, taking results from result set in JDBC are taking a lot of time in terms of coding.

So, after all, I decided to create simple utility which can work with persistence annotations and can map results of sql queries directly to java objects. It's just a annotation parser+sql builder - nothing more. It has no support of one-to-many/many-to-many relations, and support only few data types : Long, BigDecimal, String, Date. But for some easy projects that can be enough.

This utility it's just a one file EasyJDBC.java - so it's very easy to include it to project as source code without adding megabytes of .jar files which require Hibernate. 

2.  Features

So let's describe what this utility can do:

- Support of java persistence annotations.
@Entity
@Table(name="DEPARTMENT")
public class Department {

    @Id
    @Column(name = "department_id")
    private Long departmentId;

    @Column(name = "department_name")
    private String departmentName; 
 
As you can see: just like in case of using Hibernate. Class Department will be mapped with DEPARTMENT table in database.

- Mapping query results to java classes.  
On creating DAO we have to define result mapping class  :


EasyJDBC<Department> depDao=new EasyJDBC<Department>(Department.class);

Now using this DAO we will get/put objects of Department class from/into database.

- Hibernate-style operations.
Supported main hibernate operations like save, update, delete  

Department dep1=createDepartment("First");
depDao.save(dep1);

- Mapping query results to objects.
All queries are returning List<> of object defined on DAO creation:

List<Department> deps=depDao.getAll();

- Internal query-builder to simplify creation of database queries.
There are several options to simplify creation of sql query :


        List<Department> deps=depDao
                .getQueryBuilder()
                .addFieldCondition(Department.COLUMNS.DEPARTMENT_NAME.name(), "=", "First")
                .executeSelect();

3. Example of usage: pom.xml and test-project structure

Project structure is very simple: in "main" folder I left only utility itself and all stuff related with demonstration are in "test" folder:


pom.xml is also very simple: only dependencies for java persistence annotations and for H2 DB which used for tests:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demien.easy</groupId>
    <artifactId>jdbc</artifactId>
    <version>1.0-SNAPSHOT</version>

   <dependencies>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0</version>
    </dependency>

       <dependency>
           <groupId>com.h2database</groupId>
           <artifactId>h2</artifactId>
           <version>1.4.178</version>
       </dependency>

   </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>

                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>


4. Example of usage: annotated DTO objects.

Here - only "top" of files: without getters/setters, full text can be downloaded from the link at the page bottom.

User.java:

package com.demien.easy.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;

@Entity
@Table(name="USER")
public class User {

    public enum COLUMNS{USER_ID, USER_NAME, EMP_DATE, SALARY, DEPARTMENT_ID}

    @Id
    @Column(name = "user_id")
    private Long userId;

    @Column(name = "user_name")
    private String userName;

    @Column(name = "emp_date")
    private Date employmentDate;

    @Column(name = "salary")
    private BigDecimal salary;

    @Column(name = "department_id")
    private Long departmentId;

    public User() {
    }

Department.java:

package com.demien.easy.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Created by kovalskd on 5/7/2015.
 */
@Entity
@Table(name="DEPARTMENT")
public class Department {

    public enum COLUMNS{DEPARTMENT_ID, DEPARTMENT_NAME}

    @Id
    @Column(name = "department_id")
    private Long departmentId;

    @Column(name = "department_name")
    private String departmentName;

    public Department() {}


5. Example of usage: test application.

In listing below - example of usage of this utility. Every step is well commented. 


package com.demien.easy;

import com.demien.easy.dto.Department;
import com.demien.easy.dto.User;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by kovalskd on 5/21/2015.
 */
public class EasyJDBCTest {

    static Connection connection;
    static EasyJDBC<User> userDao=new EasyJDBC<User>(User.class);
    static EasyJDBC<Department> depDao=new EasyJDBC<Department>(Department.class);


    public static void init() throws ClassNotFoundException, SQLException {
        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection("jdbc:h2:mem:db", "sa", "");
        userDao.setConnection(connection);
        userDao.createTable();
        depDao.setConnection(connection);
        depDao.createTable();
    }

    public static Department createDepartment(String name) {
        Department dep=new Department();
        Long id=(Long)depDao.getMaxId() + 1;
        dep.setDepartmentId(id);
        dep.setDepartmentName(name);
        return dep;
    }

    public static User createUser(String name, BigDecimal salary, Long departmentId) {
        User user=new User();
        Long id=(Long)userDao.getMaxId() + 1;
        user.setUserId(id);
        user.setUserName(name);
        user.setEmploymentDate(new Date());
        user.setSalary(salary);
        user.setDepartmentId(departmentId);
        return user;

    }

    public static void main(String args[]) throws Exception {
        init();
        Department dep1=createDepartment("First");
        depDao.save(dep1);

        User user1=createUser("Huan Sebastyan", new BigDecimal(123.23), dep1.getDepartmentId());
        userDao.save(user1);

        User user2=createUser("Joe Black", new BigDecimal(333.33), dep1.getDepartmentId());
        userDao.save(user2);

        Department dep2=createDepartment("Second");
        depDao.save(dep2);

        User user3=createUser("Developer", new BigDecimal(100), dep2.getDepartmentId());
        userDao.save(user3);

        User user4=createUser("Just Another User", new BigDecimal(500), dep2.getDepartmentId());
        userDao.save(user4);

        User user5= createUser("new user", new BigDecimal(666.66), dep2.getDepartmentId());
        userDao.save(user5);

        List<Department> deps=depDao.getAll();
        System.out.println("DEPARTMENTS:"+Arrays.toString(deps.toArray()));
        List<User> users=userDao.getAll();
        System.out.println("USERS:"+Arrays.toString(users.toArray()));

        // get by id test
        System.out.println("\n get by id test: userDao.getById(1L)");
        User user=userDao.getById(1L);
        System.out.println(user);

        // query test
        System.out.println("\n query test: User.COLUMNS.USER_NAME.name() in ('Huan Sebastyan','Joe Black')");
        users= userDao.getQueryBuilder().addWhereCondition(User.COLUMNS.USER_NAME.name()+" in ('Huan Sebastyan','Joe Black')").executeSelect();
        System.out.println(Arrays.toString(users.toArray()));

        // addFieldEqualsCondition test
        System.out.println("\n addFieldCondition test: (User.COLUMNS.USER_ID.name(), <=, 2L)");
        users= userDao.getQueryBuilder().addFieldCondition(User.COLUMNS.USER_ID.name(), "<=", 2L).executeSelect();
        System.out.println(Arrays.toString(users.toArray()));

        // addFieldEqualsCondition test
        System.out.println("\n addFieldEqualsCondition test: (User.COLUMNS.USER_NAME.name(), Developer)");
        users= userDao.getQueryBuilder().addFieldEqualsCondition(User.COLUMNS.USER_NAME.name(), "Developer").executeSelect();
        System.out.println(Arrays.toString(users.toArray()));



        // update test
        System.out.println("\n update test:");
        user=userDao.getById(1L);
        user.setUserName("Updated name");
        userDao.update(user);
        user=userDao.getById(1L);
        System.out.println(user);

        // delete test
        System.out.println("\n delete test - deleted user1,user2,user3:");
        userDao.delete(user1);
        userDao.delete(user2);
        userDao.delete(user3);
        users = userDao.getAll();
        System.out.println(Arrays.toString(users.toArray()));

    }
}


6. Example of usage: results

The results itself:

DEPARTMENTS:[Department{departmentId=1, departmentName='First'}, Department{departmentId=2, departmentName='Second'}]
USERS:[User{userId=1, userName='Huan Sebastyan', employmentDate='2015-06-24', salary='123.23', departmentId='1'}, User{userId=2, userName='Joe Black', employmentDate='2015-06-24', salary='333.33', departmentId='1'}, User{userId=3, userName='Developer', employmentDate='2015-06-24', salary='100.00', departmentId='2'}, User{userId=4, userName='Just Another User', employmentDate='2015-06-24', salary='500.00', departmentId='2'}, User{userId=5, userName='new user', employmentDate='2015-06-24', salary='666.66', departmentId='2'}]

 get by id test: userDao.getById(1L)
User{userId=1, userName='Huan Sebastyan', employmentDate='2015-06-24', salary='123.23', departmentId='1'}

 query test: User.COLUMNS.USER_NAME.name() in ('Huan Sebastyan','Joe Black')
[User{userId=1, userName='Huan Sebastyan', employmentDate='2015-06-24', salary='123.23', departmentId='1'}, User{userId=2, userName='Joe Black', employmentDate='2015-06-24', salary='333.33', departmentId='1'}]

 addFieldCondition test: (User.COLUMNS.USER_ID.name(), <=, 2L)
[User{userId=1, userName='Huan Sebastyan', employmentDate='2015-06-24', salary='123.23', departmentId='1'}, User{userId=2, userName='Joe Black', employmentDate='2015-06-24', salary='333.33', departmentId='1'}]

 addFieldEqualsCondition test: (User.COLUMNS.USER_NAME.name(), Developer)
[User{userId=3, userName='Developer', employmentDate='2015-06-24', salary='100.00', departmentId='2'}]

 update test:
User{userId=1, userName='Updated name', employmentDate='2015-06-24', salary='123.23', departmentId='1'}

 delete test - deleted user1,user2,user3:
[User{userId=4, userName='Just Another User', employmentDate='2015-06-24', salary='500.00', departmentId='2'}, User{userId=5, userName='new user', employmentDate='2015-06-24', salary='666.66', departmentId='2'}]

Process finished with exit code 0

 

7. The end. 

Of course, it's not a "enterprise-level" library like Hibernate. But may be it will be useful for somebody. Full code can be get from git repository :
https://github.com/demien666/easy_repository.git

Wednesday, September 17, 2014

Active record domain model in Java with Spring and Hibernate

1. Goal.

As a developer, I want to create ability to use just entity object for performing base CRUD operation in DB, like:
myObject.save()
myObject.update()
myObject.delete()

2. Problem. 

The main problem here is obvious: transaction management. What it we are executing in one transaction:
object1.save();
object2.save();
and after that we have to rollback our transaction ? In case of anemic domain model business logic located at another(service) level:

@Transactional
pubic void doSomething(Object1 object1, Object2 object2) {
       Session session=sessionFactory.getCurrentSession();
       service1.save();
       service2.save();
       session.rollback();
}

Using anemic mode, at service level we can just mark method as @Transactional,  execute whole list of operations and after that  - commit or rollback transaction.
Using rich domain model, we have to think about transaction management.

3. Application context file.

In application context file we have to define data source bean(with connection to H2 database), session factory(with one domain class) bean and  abstract model bean - main(parent) class for our rich domain model.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd>">

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:~/test" />
        <property name="username" value="sa" />
        <property name="password" value="sa" />
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- Don't forget to list all your entity classes here -->
        <property name="annotatedClasses">
            <list>
                <value>com.demien.richdomain.model.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

    <bean id="AbstractModel" class="com.demien.richdomain.model.AbstractModel">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

4. Abstract model

This class could be much simpler, but because of logic related with transactions I added few more procedures: setAutoCommit, setSession, checkAndStartTransaction, checkAndCommitTransaction.

package com.demien.richdomain.model;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class AbstractModel<T, PK extends Serializable> {

    protected static SessionFactory sessionFactory;
    protected Session session;
    protected boolean autoCommit=true;

    private Class<T> cl;

    public AbstractModel() {
    }

    public AbstractModel(Class<T> cl) {
        this.cl=cl;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void setSessionFactory(SessionFactory sessionFactory) {
        AbstractModel.sessionFactory = sessionFactory;
    }

    protected Session getCurrentSession() {

        try {
            session=getSessionFactory().getCurrentSession();
        } catch (Exception e ) {

        }
        if (session == null) {
            session = getSessionFactory().openSession();
        }
        return session;
    }

    public Session getNewSession() {
        return getSessionFactory().openSession();
    }

    protected void setSession(Session session) {
        this.session=session;
    }

    protected void setAutoCommit(boolean autoCommit) {
        this.autoCommit=autoCommit;
    }

    public void checkAndStartTransaction() {
        if (autoCommit) {
            Session session = getCurrentSession();
            session.beginTransaction();
        }
    }

    public void checkAndCommitTransaction() {
        if (autoCommit) {
            session.getTransaction().commit();
        }
    }

    public T get(PK id) {
        Session session = getCurrentSession();
        checkAndStartTransaction();
        T element = (T) session.get(cl, id);
        checkAndCommitTransaction();
        return element;
    }

    public PK save() {
        Session session = getCurrentSession();
        checkAndStartTransaction();
        PK result=(PK)session.save(this);
        checkAndCommitTransaction();
        return result;
    }

    public void update() {
        Session session = getCurrentSession();
        checkAndStartTransaction();
        session.update(this);
        checkAndCommitTransaction();
    }

    public void delete() {
        Session session = getCurrentSession();
        checkAndStartTransaction();
        session.delete(this);
        checkAndCommitTransaction();
    }

    public List<T> query(String hsql, Map<String, Object> params) {

        Session session = getCurrentSession();
        checkAndStartTransaction();

        Query query = session.createQuery(hsql);
        if (params != null) {
            for (String i : params.keySet()) {
                query.setParameter(i, params.get(i));
            }
        }

        List<T> result = null;
        if ((hsql.toUpperCase().indexOf("DELETE") == -1)
                && (hsql.toUpperCase().indexOf("UPDATE") == -1)
                && (hsql.toUpperCase().indexOf("INSERT") == -1)) {
            result = query.list();
        } else {
            query.executeUpdate();
        }
        checkAndCommitTransaction();
        return result;
    }


    public List<T> getAll() {
        return query("from "+cl.getName(), null);
    }

    public void deleteAll() {
        query("delete from "+cl.getName(),null);

    }

}

Now we can just extend from this class: all child classes will have ability to work with database. 

5.Domain class which extends AbstactModel

It's just a POJO class which extends AbstractModel.

package com.demien.richdomain.model;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name = "USER")
public class User extends AbstractModel<User, Integer> implements Serializable {

    private static final long serialVersionUID = -7022793569839517729L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private Integer id;
    
    @Column(name = "LOGIN")
    private String login;
    
    @Column(name = "PASSWORD")
    private String password;
    

    public User() {
        super(User.class);
    }
    
    public User(String login, String password) {
        this();
        this.setLogin(login);
        this.setPassword(password);
    }
    
    public User(Integer id, String login, String password) {
        this();
        this.setId(id);
        this.setLogin(login);
        this.setPassword(password);
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    @Override
    public boolean equals(Object object) {
        if (!(object instanceof User)) {
            return false;
        } else {
            User user = (User) object;
            if (user.getId().equals(this.getId())
                    && user.getLogin().equals(this.getLogin())
                    && user.getPassword().equals(this.getPassword())) {
                return true;
            }
            return false;
        }
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", login=" + login + ", password=" + password
                + "]";
    }

}

6. Test with "simple transaction"

Let's test our class with "simple transaction": just one object associated with transaction.
    @Test
    public void simpleTest() {
        User user=new User("login", "password");
        int cnt0=user.getAll().size();

        Integer id=user.save();

        int cnt1=user.getAll().size();
        Assert.assertEquals(cnt0+1, cnt1);

        User user1=user.get(id);
        Assert.assertEquals(user, user1);

        user.setLogin("login_updated");
        user.update();

        user1.get(id);
        Assert.assertEquals("login_updated", user1.getLogin());
    }

So far, so good: it's very simple and easy to work with database by our object. 


7. Tests with "complex transaction"

If we want to use several objects associated with transaction logic is becoming much more complicated. We have to turn off transaction start(setAutoCommit method) in every object and also we have to provide all transaction object with one session object(setSession method).

  
    @Test
    public void transactionRollbackTest() {
        User user1=new User("login1","password1");
        User user2=new User("login2","password2");
        int cnt0=user1.getAll().size();

        user1.setAutoCommit(false);
        user2.setAutoCommit(false);

        Session session=user1.getNewSession();
        user1.setSession(session);
        user2.setSession(session);

        session.beginTransaction();
        user1.save();
        user2.save();
        session.getTransaction().rollback();

        int cnt1=user1.getAll().size();
        Assert.assertEquals(cnt0, cnt1);

    }

    @Test
    public void transactionCommitTest() {
        User user1=new User("login1","password1");
        User user2=new User("login2","password2");
        int cnt0=user1.getAll().size();

        user1.setAutoCommit(false);
        user2.setAutoCommit(false);

        Session session=user1.getNewSession();
        user1.setSession(session);
        user2.setSession(session);

        session.beginTransaction();
        user1.save();
        user2.save();
        session.getTransaction().commit();

        int cnt1=user1.getAll().size();
        Assert.assertEquals(cnt0+2, cnt1);

    }

8. Conclusion

As for me, active record model can be used in projects with simple transactions. But if there are a lot of complex transaction it's better to use anemic model with logic at service(not domain) level.  

Source code can be downloaded from here.