Monday, November 30, 2015

An example of using an SQLite database in a Spring Hibernate application project

I wanted to use SQLite as an object relational model (ORM) database for a Spring Hibernate Java application. It turned out to be relatively simple to achieve. This post shows a simple example illustrating the project configuration, SQLite table creation, Java object definition, saving and retrieving a Java object into/from the database. The example project structure is shown in the screenshot below.

In order to prepare a Java application to work with SQLite as an ORM database, the following steps can be done:
  1. Add in the software dependencies to the project's Maven pom.xml
  2. Define Hibernate beans in the application context configuration file
Add in software dependencies to pom.xml
The following listing is an example pom.xml file.
Note that Hibernate, SQLite and Spring ORM dependencies have been appended to the dependencies element.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""
 <name>Spring Hibernate Utility</name>
  <![CDATA[This project is a minimal jar utility with Spring configuration for Hibernate.]]>


  <!-- Dependencies for Hibernate and ORM  -->  

  <!-- Dependencies for SQLite -->


   <name>JBoss Maven Release Repository</name>



Define Hibernate beans in the application context configuration file
The Spring Java application's context configuration file is located in the /path/to/project/src/main/resources/META-INF/spring/app-context.xml file. The beans SessionFactory, TransactionManager and the DataSource should at least be defined in the file as shown in the listing below.

Note: In this example listing, we configure Spring to scan for additional components under the package namespace com.dom925.demo.spring.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:context=""
 xmlns:tx="" xmlns:jdbc=""

 <tx:annotation-driven transaction-manager="transactionManager" />

 <!-- Tell Spring where to scan for components -->
 <context:component-scan base-package="com.dom925.demo.spring" />
 <!-- Specify the Hibernate properties setting file -->

 <bean id="dataSource" 
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 <bean id="sessionFactory" 
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses" value="com.dom925.demo.spring.hibernate.model.Person" />
  <property name="hibernateProperties">
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
 <bean id="transactionManager" 
  <property name="sessionFactory" ref="sessionFactory" />
 <tx:annotation-driven transaction-manager="transactionManager"/>

In this example, some of the Hibernate data source's JDBC properties are defined in a separate file /path/to/project/src/main/resources/META-INF/ file, as shown below.

Note: this example configures Spring to use a SQLite database named person_db.sqlite. Since the path is not defined, it will be created in /path/to/project/ directory.



At this point, the project configuration should be done. The next steps would be to write the Java classes and interfaces. In this example, the following classes are created.
  3. which implements the interface
  4. which implements the interface
When Spring initializes the Java application, the @PostConstruct annotation in this file will cause the initialize method to be executed. This method will recreate the SQLite database and table each time you run the application. 

package com.dom925.demo.spring.hibernate.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class DBUtils {

 private DataSource dataSource;
 public void initialize(){
  try {
   Connection connection = dataSource.getConnection();
   Statement statement = connection.createStatement();
   statement.execute("DROP TABLE IF EXISTS PERSON_INFO");
     "ID INTEGER Primary key, " +
     "FIRST_NAME varchar(30) not null, " +
     "LAST_NAME varchar(30) not null)"
     "VALUES " + "('DONALD', 'TRUMP')"
  catch (SQLException e) {
Now we define the plain old Java object POJO class that we want to associate to a SQLite database table.

Note I: the Spring annotations @Entity and @Table specify the database table
Note II: the annotations @Column specify the database column name, and @Id define the primary key.

package com.dom925.demo.spring.hibernate.model;

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

@Table(name = "PERSON_INFO")
public class Person {

 @Column(name = "ID")
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer id;
 @Column(name = "FIRST_NAME")
 private String firstName;
 @Column(name = "LAST_NAME")
 private String lastName;
 public Integer getId() {
  return id;
 public void setId(Integer id) { = id;
 public String getFirstName() {
  return firstName;
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 public String getLastName() {
  return lastName;
 public void setLastName(String lastName) {
  this.lastName = lastName;
 public boolean equals(Object obj){
  if (this == obj){
   return true;
  Person person = (Person) obj;
  if (firstName != null ?
    :person.firstName != null){
   return false;
  else {
   return true;
 public String toString() {
  return "Person [id=" 
    + id 
    + ", name=" 
    + firstName 
    + " " 
    + lastName 
    + "]";
This interface defines the interface for accessing the Person data.

package com.dom925.demo.spring.hibernate.dao;

import java.util.List;

import com.dom925.demo.spring.hibernate.model.Person;

public interface PersonDAO {

 public List<Person> getAllPersons();
 public void insertPerson (Person person);
This implements the interface defined by the file. Note the use of the Spring @Repository and @Transactional annotations for database related activities.

package com.dom925.demo.spring.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dom925.demo.spring.hibernate.model.Person;

@Transactional(readOnly = true)
public class PersonDaoImpl implements PersonDAO {

 private SessionFactory sessionFactory;

 public List<Person> getAllPersons() {
  Session session = sessionFactory.openSession();
  String hql = "FROM Person";
  Query query = session.createQuery(hql);
  List<Person> persons = query.list();
  return persons;

 @Transactional(readOnly = false)
 public void insertPerson(Person employee) {
  Session session = sessionFactory.openSession();;

This file defines the interface for a service to access the Person data.

package com.dom925.demo.spring.hibernate.service;

import java.util.List;

import com.dom925.demo.spring.hibernate.model.Person;

public interface PersonService {

 public List<Person> getAllPersons();
 public void insertPerson(Person person);
This is an implementation of the interface defined in the file. Note the Spring @Service annotation.

package com.dom925.demo.spring.hibernate.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.dom925.demo.spring.hibernate.dao.PersonDAO;
import com.dom925.demo.spring.hibernate.model.Person;

public class PersonServiceImpl implements PersonService {

 private PersonDAO personDao;
 public List<Person> getAllPersons() {
  List<Person> persons = personDao.getAllPersons();
  return persons;

 public void insertPerson(Person person) {

Finally, the Java application's main method, which loads the application context, get a PersonService bean to add a new Person object to the database. Then print out the database contents to the screen.

package com.dom925.demo;

import org.springframework.context.ApplicationContext;

import com.dom925.demo.spring.hibernate.model.Person;
import com.dom925.demo.spring.hibernate.service.PersonService;

public class SpringHibernateMain {

 public static void main(String[] args) {
  ApplicationContext context = 
    new ClassPathXmlApplicationContext(
  PersonService personService = 
    context.getBean("personServiceImpl", PersonService.class);
  Person person = new Person();
  for (Person p : personService.getAllPersons()){
Example print out from the Spring application

A zip file containing the example project can be downloaded here.


Dusan Klinec said...
This comment has been removed by the author.
Dusan Klinec said...

Thanks for tutorial! It helped a lot.
I was trying to do it also with Hibernate4 but SQLite dialect was not working for me. So I made a port:

groupId: com.enigmabridge
artifactId: hibernate4-sqlite-dialect
version: 0.1.0

Related Posts with Thumbnails