Professional Documents
Culture Documents
Hibernate and Spring - An Analysis of Maintainabil
Hibernate and Spring - An Analysis of Maintainabil
97-108, 2016
Revista Facultad de Ingeniería, Universidad de Antioquia, No. 80, pp. 97-108, 2016
ARTICLE INFO ABSTRACT: Web application frameworks and ORM tools reduce time and effort needed
Received June 09, 2015 when developing quality applications; but, since they are numerous and heterogeneous
Accepted April 11, 2016 choosing the best suited is not an easy task. The comparative studies of these tools do not
consider case studies of the necessary complexity to precisely measure their advantages
and disadvantages. In order to contribute to the solution of this problem, we measured the
HIBERNATE ORM response times for different queries in a rather complex case study with
different database sizes, and compared the results with the ones obtained by using manually
coded queries. Our comparison is relevant because even though ORMs are an important
KEYWORDS maintainability factor, not optimal queries can lead to bottle necks.
ORM, performance, spring
framework, hibernate, RESUMEN: Los frameworks para el desarrollo de aplicaciones web y las herramientas ORM
maintainability permiten reducir el tiempo y esfuerzo al producir aplicaciones de software de calidad. Se
han hecho estudios comparativos sobre estas herramientas pero dado que son numerosas
ORM, desempeño, spring y heterogéneas, escoger la más adecuada no es fácil. Hay estudios comparativos sobre
framework, hibernate, estas herramientas, sin embargo no consideraron un dominio suficientemente complejo que
mantenibilidad permitan medir más precisamente sus ventajas y desventajas. Para aportar en la solución,
comparamos el tiempo de respuesta de diferentes consultas en un dominio más complejo
y con diferentes tamaños de base de datos. La comparación basada en este aspecto es
importante ya que los ORM son un factor de mantenibilidad importante y porque consultas
no optimizadas pueden conducir a cuellos de botella.
* Corresponding author: Danny Alejandro Alvarez Eraso Consequently, using off the shelve ORMs creates tension
e-mail: daalvareze@unal.edu.co between maintainability and performance. On one hand,
ISSN 0120-6230 they ease the task of developing websites controlling the
e-ISSN 2422-2844 complexity of the software specification; on the other hand,
DOI: 10.17533/udea.redin.n80a11
97
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
98
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
99
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
4.3. Relationships of the class model side we used a list-of-objects attribute of the opposite side
type. For example, the one-to-many relationship between
In the Spring code, we represented relationships Usuario and Album was represented with one Usuario typed
between two classes with object valued attributes of the attribute in Album and one List<Album> typed attribute in
corresponding type in both classes [22]. The relationship’s Usuario.
cardinality determines if the attribute is a single object or a
collection of objects. The many-to-many relationship between Album and Imagen
classes is more complex as it has an attribute that will
For one-to-one relationships, we included an attribute of the be lost if modeled with two typed-list attributes. Given
other side type in both classes. For example, to represent that the many-to-many relationship was solved in the DB
the relationship between Usuario and Persona, we added with an intersection table containing an extra column, we
an Usuario typed attribute in Persona and a Persona typed decided to use a new class (AlbumXImagen.java) containing
attribute in Usuario. an attribute for numeroOrden. Additionally, to maintain
consistency, from the point of view of Album and Imagen
For one-to-many relationships, we did as in the one-to-one classes, we included an AlbumXImagen-typed attribute in
for the one-side of the relationship, whilst for the many- both of them, as shown in Figure 5.
// Joining relationship
private List<AlbumXImagen>
albumXimagenList; // ...
100
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
101
101
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
Table 1 Average response times Figure 15 Level 1 average time in function of the
DB size
102
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
@Entity @Table(name="album")
@Column(name="nombre")
... }
Figure 19 Linking a class and table - Album case
Finally, as the details behind our results can be of particular regarding relationships. On this ground, we constructed
interest to certain readers we present them as follows, in the best possible implementation based on the acquired
section 6 we show how we linked Hibernate to our CD and knowledge.
in section 7 we present how the DB was accessed with both
Hibernate and SQL. 6.1. Linking classes and tables
Hibernate can establish a link between a JAVA class
6. Implementation and a DB table by using annotations. Annotations in the
class definitions link them to the corresponding DB table
We made sure the most convenient implementation for while annotating attributes link such attributes with
our tests were achieved by focusing on query complexity the corresponding table column, or with another object
and DB size be the only variables impacting performance. according to relationship defined by the foreign key.
So, we searched all the available literature we could and
followed the official documentation, online forums and the Thus, we linked our CD’s class models with our DB tables
recommendations of [19] regarding aspects influencing the using @Entity, @Table, @Id, @GeneratedValue for Hibernate
performance of Hibernate. The authors in [19] define an identification strategy, and @Column for the primitive class
anti-pattern as a bad practice that has a negative impact members. In Figure 19 we present Album’s case as an
in application performance, and presents five of them example.
103
103
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
Session s =
mySessionFactory.getCurrentSession();
s.createCriteria(<OBJ_CLASS>);
// criteria definition
createCriteria(Persona.class).add(
Restrictions.like("nombre","%"+nombre+"%")).addOrder(Order.desc("nombre"))
.setMaxResults(50);
Figure 21 Level 1 criteria definition
// criteria instantiation
createCriteria(Usuario.class).createAlias(
"persona", "p").add(Restrictions.
like("p.nombre", "%"+nombre+"%"))
.addOrder(Order.desc("p.nombre"))
.setMaxResults(50)
.setFetchMode("albumes", FetchMode.JOIN)
.setFetchMode("persona", FetchMode.JOIN)
.setFetchMode("albumes.albumXimagenList",
FetchMode.SELECT);
Figure 22 Level 2 criteria definition
104
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
7.2. Object trees with hibernate and Imagen objects. As a result, this scenario reads data
from all tables in the DB and construct the corresponding
All of our Hibernate DAO methods for retrieving object trees object tree.
are alike, the only code section that changes corresponds
to the query criteria, see Figure 20. This criteria was Our first attempt to build the required criteria was to set
constructed using Session’s createCriteria() method. Where <OBJ_CLASS> equals to Usuario and, in addition to level 2
<OBJ_CLASS> is the type of the resulting data, and <CLASS> query restrictions, we modified AlbumXImagen’s fetch mode
is the type of the List used to capture the Hibernate API from SELECT to JOIN. However, this approach resulted in
result, generally both classes are the same. this execution exception: “Request processing failed; nested
exception is org.hibernate.loader.MultipleBagFetchException:
level 1 Hibernate reading cannot simultaneously fetch multiple bags”. Not being
clear from the Hibernate’s documentation the nature of
In this level, we retrieve a List of Persona. So, we defined this error, we assumed it was caused by the join depth
a Criteria with <OBJ_CLASS> equals to Persona (see Figure complexity. The reader must remember that every Usuario
21), and we added the name and page size restrictions (see has a List of Albums and every one of those also has a List
section 3.2). Here, the variable nombre contains a random of AlbumXImagen, see Figure 3.
char between [a-z] (same for level 2 and level 3).
After digging a little more in the problem we solved the
Level 2 Hibernate queries issue by adjusting our model’s classes. This is, we changed
both @OneToMany and @ManyToOne annotations so the
In this level, we retrieve a List of Usuario including related data would be eagerly loaded. Thus, we modified the
relationships with Persona and Album. So, we defined a albumXimagenList attribute in Album and imagen classes as
Criteria with <OBJ_CLASS> equals to Usuario (see Figure 22) a non-lazy collection, in Figure 23 we show this modification
and, in addition to the name and page size restrictions, we in the Java file.
added relationship constrains (see Figure 4) making sure
Imagen or AlbumXImagen data was not retrieved. This approach has the inconvenient that even when it solves
the execution problem, the way classes were mapped
Level 3 Hibernate queries causes both album and albumXimagenList attributes are
always loaded. This lead queries to poor performance when
In this level, we retrieve a List of Usuario with full direct those data are not required, take our level 2 queries for
or indirect data, this is, with Persona, Album, AlbumXImagen example. On this ground, we defined the required criteria as
shown in Figure 24:
// Album.JAVA file
@OneToMany(mappedBy = "album")
@LazyCollection(LazyCollectionOption.FALSE)
private List<AlbumXImagen>albumXimagenList;
createCriteria(Usuario.class).createAlias(
"persona","p").add(Restrictions
.addOrder(Order.desc("p.nombre"))
.setMaxResults(50)
.setFetchMode("albumes", FetchMode.JOIN);
105
105
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
7.3. Object trees with SQL ResultSet. This mechanism has the advantage of reading
every tuple just one time. This approach solves the problem
All data obtained with manually coded SQL queries will with and algorithm with order O(n).
be used as a reference to assess Hibernate´s results.
To achieve the best performance in this DAO, we always Level 1 SQL queries
accessed the DB using a single query, and building the
required object tree with that result only. In this level, we retrieve a List of Persona using the SQL
query shown in Figure 25. Also, we assembled the object
Additionally, all of the three DAO methods are structured in tree from this Resultset using a simple loop that creates a
a similar way; the two code sections that change correspond Persona instance containing every row field as attributes.
to the executed SQL statement and the construction of the
object tree. Level 2 SQL queries
Object assemble using typed maps In this level, we retrieve a List of Usuario with Persona and
Album data using the SQL query shown in Figure 26. Also,
To be able to compare SQL response times with those from we assembled the object tree from this Resultset using one
Hibernate, it is necessary to recreate the same conditions. Usuario typed map.
Given that executeQuery() method responds with a ResultSet
collection instead with a set objects, we need to transform Although this code is totally functional, the query can be
that resultSet. optimized. We did this optimization as an attempt to prove
that Hibernate cannot find the best way of solving the join
Transforming tuples into objects is a simple task when order execution. We present our optimized SQL query in
the resulting data belongs to a single class (like in level 1 Figure 27.
scenario); however, the same task becomes harder when
such data belongs to many classes (like in level 2 and 3 Level 3 SQL queries
scenarios).
In this level, we retrieve a List of Usuarios with Persona,
To reduce the time the program takes to transform level Album, Imagen and AlbumXImagen data using the SQL query
2 and 3 Resultsets into objects, we used a typed map shown in Figure 28. Also, we assembled the object tree
- HashMap<id, object>- for every row contained in the using two typed maps, one for Usuario and one for Album.
106
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
ON al.id = axi.album_id
107
107
D. A. Alvarez-Eraso et al.; Revista Facultad de Ingeniería, No. 80, pp. 97-108, 2016
(STEP), Pittsburgh, USA, 1999, pp. 3–11. 15. Hotframeworks, Web framework rankings |
5. N. Wilde and R. Huitt, “Maintenance support for object- HotFrameworks. [Online]. Available: http://
oriented programs”, IEEE Trans. Softw. Eng., vol. 18, no. hotframeworks.com/. Accessed on: May. 26, 2015.
12, pp. 1038–1044, 1992. 16. T. Shan, W. Bank and W. Hua, “Taxonomy of Java Web
6. J. Kienzle and A. Romanovsky, “Framework based on Application Frameworks”, IEEE International Conference
design patterns for providing persistence in object- on e-Business Engineering (ICEBE), Shanghai, China,
oriented programming languages”, IEE Proc. - Softw., 2006, pp. 378-385.
vol. 149, no. 3, pp. 77-85, 2002. 17. V. Nagy, “Performance Analysis of Relational
7. C. Ireland, D. Bowers, M. Newton and K. Waugh, Databases, Object-Oriented Databases and ORM
“A Classification of Object-Relational Impedance Frameworks”, Bachelor Degree Project, University of
Mismatch”, in 1st International Confernce on Advances in Skövde, Skövde, Sweden, 2014.
Databases, Knowledge, and Data Applications (DBKDA), 18. J. Arthur and S. Azadegan, “Spring Framework for
Gosier, France, 2009, pp. 36–43. Rapid Open Source J2EE Web Application Development:
8. C. Murdaca, “An Object-Relational Compiler”, in A Case Study”, in 6th Int. Conf. on Software Engineering,
2009 WRI World Congress on Computer Science and Artificial Intelligence, Networking and Parallel/Distributed
Information Engineering, Los Angeles, USA, 2009, pp. Computing and 1st ACIS International Workshop on Self-
438–442. Assembling Wireless Network (SNPD/SAWN), Towson,
9. H. Abelson, G. Sussman and J. Sussman, Structure and USA, 2005, pp. 90–95.
Interpretation of Computer Programs, 2nd ed. Cambridge, 19. P. Węgrzynowicz, “Performance antipatterns of
USA: The MIT Press, 1996. one to many association in hibernate”, in Federated
10. M. Cuervo, D. Peñalosa and A. Alarcón, “Evaluación Conference on Computer Science and Information
y análisis de rendimiento de los frameworks de Systems (FedCSIS), Kraków, Poland, 2013, pp. 1475–
persistencia Hibernate y Eclipselink”, Ventana 1481.
Informática, no. 24, pp. 9-23, 2011. 20. Object Management Group (OMG), Unified Modeling
11. Z. Zhou and Z. Chen, “Performance Evaluation of Language ™ (UML®). [Online]. Available: http://www.
Transparent Persistence Layer in Java Applications”, omg.org/spec/UML/. Accessed on: Apr. 20, 2016.
in International Conference on Cyber-Enabled Distributed 21. G. Krasner and S. Pope, “A description of the model-
Computing and Knowledge Discovery (CyberC), view-controller user interface paradigm in the
Huangshan, China, 2010, pp. 21–26. smalltalk-80 system”, J. Object Oriented Program., vol.
12. P. van Zyl, D. Kourie and A. Boake, “Comparing the 1, no. 3, pp. 26–49, 1988.
performance of object databases and ORM tools”, in 22. G. King, “Chapter 7. Collection mapping”, in HIBERNATE
Annual research conference of the South African institute - Relational Persistence for Idiomatic Java, 2004. [Online].
of computer scientists and information technologists on Available: https://docs.jboss.org/hibernate/orm/3.6/
IT research in developing couuntries (SAICSIT), New reference/en-US/html/collections.html. Accessed on:
York, USA, 2006, pp. 1–11. Dec. 18. 2015.
13. K. Roopak, K. Swati, S. Ritesh and S. Chickerur, 23. Oracle Corporation, Core J2EE Patterns - Data Access
“Performance Comparison of Relational Database with Object, 2002. [Online]. Available: http://www.oracle.
Object Database (DB4o)”, in 5th International Conference com/technetwork/java/dataaccessobject-138824.
on Computational Intelligence and Communication html. Accessed on: Apr. 25, 2015.
Networks (CICN), Mathura, India, 2013, pp. 512–515. 24. Oracle Corporation, Java SE Desktop Technologies.
14. Hibernate, Hibernate. Everything data. [Online]. [Online]. Available: http://www.oracle.com/
Available: http://hibernate.org/. Accessed on: Mar. technetwork/java/javase/tech/index-jsp-138795.html.
10, 2016. Accessed on: May 25, 2015.
108