In order to prepare a Java application to work with SQLite as an ORM database, the following steps can be done:
- Add in the software dependencies to the project's Maven pom.xml
- Define Hibernate beans in the application context configuration file
The following listing is an example pom.xml file.
Note that Hibernate, SQLite and Spring ORM dependencies have been appended to the dependencies element.
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.
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/hibernate.properties 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.
- PersonDaoImpl.java which implements the interface PersonDAO.java
- PersonServiceImpl.java which implements the interface PersonServiceImpl.java
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.
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.
This interface defines the interface for accessing the Person data.
This implements the interface defined by the PersonDAO.java file. Note the use of the Spring @Repository and @Transactional annotations for database related activities.
This file defines the interface for a service to access the Person data.
This is an implementation of the interface defined in the PersonService.java file. Note the Spring @Service annotation.
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.
|Example print out from the Spring application|
A zip file containing the example project can be downloaded here.