RSS

Hibernate basic example with Apache Derby and Maven

17 Abr

We’re going to make a really easy test with Hibernate in our laptop. First, we’re going to configure an Apache Derby database. We are using Spring STS as our prefered IDE. Besides we will add Maven for our project’s dependencies .Configuring Hibernate in STS with Maven is an easy task. You only need to add your needings dependencies to our pom.xml file and start to coding.

With Maven you can always configure your repositories where you want to load your dependencies through your settings.xml file (it is saved within the conf directory of your Maven installation path.
To look for your requiered dependencies, STS or Eclipse have a special editor for the pom files from where you can find and add your requiered dependencies in your project. If we know that we are going to need a determined class o we want to know how many jar versions there are, I recommend going to the next two websites: mvnrepository and jarvana. The second one is really useful because you can look for a specified class, project or content. Our pom.xml file could have the following aspect:

<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.hop2croft.pruebas.hibernate</groupId>
	<artifactId>pruebasHibernate</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<repositories>
		<repository>
			<id>jboss</id>
			<url>http://repository.jboss.org/maven2</url>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.5.1-Final</version>
			<type>pom</type>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.5.5-Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.5.5-Final</version>
		</dependency>
		<dependency>
			<groupId>antlr</groupId>
			<artifactId>antlr</artifactId>
			<version>2.7.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.9.0.GA</version>
		</dependency>
		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.5.8</version>
			<type>pom</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>ejb3-persistence</artifactId>
			<version>3.3.2.Beta1</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.5.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.derby</groupId>
			<artifactId>derby</artifactId>
			<version>10.7.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.derby</groupId>
			<artifactId>derbyclient</artifactId>
			<version>10.7.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.derby</groupId>
			<artifactId>derbynet</artifactId>
			<version>10.7.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.derby</groupId>
			<artifactId>derbytools</artifactId>
			<version>10.7.1.1</version>
		</dependency>
		<dependency>
			<groupId>javax.security</groupId>
			<artifactId>jacc</artifactId>
			<version>1.0</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

One of the things I like most about using Maven is that you can either work with your favourite IDE or work from command line. This feature allows you to compile, package in a jar o run in an application server even if you don’t use a IDE.
We have create a new project STS and we have added the requiered dependencies to work with Hibernate. Now we are going to install Apache Derby in our computer. We download and install Derby from its website. We have to add several enviroment variables to our /etc/profiles file.

export DERBY_INSTALL=/Applications/Apache/db-derby-10.7.1.1
export DERBY_HOME=/Applications/Apache/db-derby-10.7.1.1
export CLASSPATH=$DERBY_INSTALL/lib/derby.jar:$DERBY_INSTALL/lib/derbytools.jar:$CLASSPATH

Apache gives us the posibility of installing an Eclipse plug-in to deal with Derby. In my case I’ve prefered working with Derby from command line. We can see the Derby info once we have installed it in our computer.

ew-host:bin hop2croft$ java org.apache.derby.tools.sysinfo
----------------- Informaci?n de Java ----------------
Versi?n de Java:     1.6.0_24
Proveedor de Java:   Apple Inc.
Inicio Java:         /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Classpath de Java:   /Applications/Apache/db-derby-10.7.1.1/lib/derby.jar:/Applications/Apache/db-derby-10.7.1.1/lib/derbytools.jar:.java
Nombre del SO:       Mac OS X
Arquitectura del SO: x86_64
Versi?n del SO:      10.5.8
Nombre usuario Java: hop2croft
Dir. inicial usuario:/Users/hop2croft
Dir. usuario:        /Applications/Apache/db-derby-10.7.1.1/bin
java.specification.name: Java Platform API Specification
java.specification.version: 1.6
java.runtime.version: 1.6.0_24-b07-334-9M3326
--------- Informaci?n de Derby --------
JRE - JDBC: Java SE 6 - JDBC 4.0
[/Applications/Apache/db-derby-10.7.1.1/lib/derby.jar] 10.7.1.1 - (1040133)
[/Applications/Apache/db-derby-10.7.1.1/lib/derbytools.jar] 10.7.1.1 - (1040133)
------------------------------------------------------
-------------- Informaci?n de entorno local ----------
Entorno local actual:  [espa?ol/Espa?a [es_ES]]

After that we have to run our server from command line as well:

$ java -jar derbyrun.jar server start
Sat Apr 16 23:54:17 CEST 2011 : Se ha instalado el administrador de seguridad utilizando la directiva de seguridad de servidores b?sica.
Sat Apr 16 23:54:19 CEST 2011 : Apache Derby Network Server - 10.7.1.1 - (1040133) se ha iniciado y está listo para aceptar conexiones en el puerto 1527

and the ij client:

$ ./ij
Versi?n ij 10.7
ij>

From the client we can create a new database in the database server:

$ ./ij
Versi?n ij 10.7
ij> connect 'jdbc:derby://localhost:1527/BDejemplo;create=true;user=hop2croft;password=hop2croft';

If you prefer not to use the command line client there are several options. You can either install an Eclipse plug-in or a sql graphic client as sql developer or squirrel. I recommend using the second one because it is fully compatible with Hibernate .
The first thing we are going to do is creating the hibernate.cfg.xml file. It indicates how our application is going to connect to our created database.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
	<hibernate-configuration>
		<session-factory>
			<property name="connection.driver_class">
				org.apache.derby.jdbc.EmbeddedDriver
			</property>
			<property name="connection.url">jdbc:derby://localhost:1527/BDejemplo</property>
			<property name="connection.username">hop2croft</property>
			<property name="connection.password">hop2croft</property>
			<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
			<property name="hibernate.generate_statistics">true</property>
			<property name="show_sql">true</property>
			<mapping resource="com/hibernate/entities/Coche.hbm.xml"/>
		</session-factory>
	</hibernate-configuration>

The show_sql propert allows us to see the sql queries that Hibernate use in our Derby database. The last entry in our hibernate config file indicates the resource we want to map. Now we map every single table from our database. In our case this file will be named as Coche.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	<hibernate-mapping package="com.hibernate.entities">
		<class name="Coche" table="Coche">
			<id name="modelo" type="string" column="modelo"></id>
			<property name="marca" type="string" column="marca"></property>
			<property name="precio" type="int" column="precio"></property>
		</class>
	</hibernate-mapping>

We can use annontations too:

@Entity
@Table (name="coche")
public class Coche {
	@Column (name="modelo")
	@Id
	private String modelo;
	@Column (name="marca")
	private String marca;
	@Column (name="precio")
	private int precio;
        // getters y setters
        ...

The next thing will be creating a DAO for quering the database. In our case we are going to implement a method to get all the cars we have in our database. Hibernate has an entity manager that deals with transactions.

	public List<Coche> readFromManager(){
		EntityManager manager = SessionManager.getEntityManager();
		EntityTransaction tran = manager.getTransaction();
		tran.begin();
		Query query = manager.createQuery("select b from Coche b");
		List<Coche> coches = query.getResultList();
		tran.commit();
		manager.close();
		return coches;
	}

Our DAO (data access object) is ready to be used. All we have to do is create a service to use it. Our output could be like this:

Hibernate: select coche0_.modelo as modelo0_0_, coche0_.marca as marca2_0_0_, coche0_.precio as precio0_0_ from Coche coche0_ where coche().modelo=?
Modelo: A6
Marca:   Audi
Precio:   8
-------------------------------------
Hibernate: select coche0_.modelo as modelo0_0_, coche0_.marca as marca2_0_0_, coche0_.precio as precio0_0_ from Coche coche0_ where coche().modelo=?
5887 [main] INFO org.hibernate.stat.Statistics - HQL: from Book, time: 15ms, rows: 2
Modelo: Carrera
Marca:   Porche
Precio:   6
-------------------------------------
5893 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - Logging statistics....
5893 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - start time: 1302994741433
5893 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - sessions opened: 1
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - sessions closed: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - transactions: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - successful transactions: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - optimistic lock failures: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - flushes: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - connections obtained: 2
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - statements prepared: 2
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - statements closed: 2
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - second level cache puts: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - second level cache hits: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - second level cache misses: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - entities loaded: 2
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - entities updated: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - entities inserted: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - entities deleted: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - entities fetched (minimize this): 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - collections loaded: 0
5894 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - collections updated: 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - collections removed: 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - collections recreated: 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - collections fetched (minimize this): 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - queries executed to database: 1
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - query cache puts: 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - query cache hits: 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - query cache misses: 0
5895 [main] INFO org.hibernate.stat.ConcurrentStatisticsImpl - max query time: 15ms

In our Hibernate configuration file we have the option of showing data access, queries or sessiones created using statistics. It is really useful if we want to improve our application.

Share this:     

 
10 comentarios

Publicado por en 17 abril, 2011 en Hibernate

 

Etiquetas: , , , ,

10 Respuestas a “Hibernate basic example with Apache Derby and Maven

  1. vpjaiganesh

    14 octubre, 2011 at 2:22 pm

    Hi,
    I did the steps as you have outlined.
    However when I try to use the “Reverse Engineering” tool of hibernate (from the hibernate tools),
    The Table filter section fails to retrieve the database schema. It throws a error : Reading Schema error: Getting database metadata. Have you encountered this problem before?
    Any suggestions?

     
    • hop2croft

      14 octubre, 2011 at 5:06 pm

      Hi vpjaiganesh,

      first of all thanx you for visting my blog. . I think that this question will be better in the Using Hibernate tools through Maven and Ant post, so I proceed to move it there. A comment cannot be moved in wordpress.com😦

      Answering your question, is your MySQL or Derby DB instance already started?. Can you see your DB instance from a MySQL or Derby DB client?. Notice that you have to start your DB instance in order to generate your java class from it.
      You have to double check also that your user, password and connection URL are correct. Look if your database schema is correcty written in your connection URL. Some examples in my case are:

      jdbc:derby://localhost:1527/BDejemplo or
      jdbc:mysql://127.0.0.1:3306/test

      where you have to indicate which type of database you are using, your ip, port and schema.

      One more thing that you can check is if your database driver is the specified one to your DB instance. In my case:

      With apache derby:

      org.apache.derby.jdbc.EmbeddedDriver

      or with hibernate tools and MYSQL:

      com.mysql.jdbc.Driver

      Kind regards,
      Iván.

      Visit my new website java4developers.com

       
      • vpjaiganesh

        16 octubre, 2011 at 6:19 pm

        hi ,
        Indeed the database is active and i am able to connect to it with Squirrel and create tables and insert rows using SQL. When I create the hibernate profile, it also connects. but only fails to fetch schema info in the rev eng tool of hibernate..
        Thanks and Regards,
        V.P.J.

         
  2. hop2croft

    16 octubre, 2011 at 6:29 pm

    Hi,

    I don’t know the reason why hibernate tools don’t allow you to your database. But try this, open in Eclipse the database view and try to connect from there to your db. Use the same driver you uses with hibernate tool. If you can connect I would know what to tell you😦 , if not probably the driver you are using to connect from Squirrel isn’t the same that the one in Eclipse (hibernate tool or db view).
    Look if you named your schema too. Maybe you haven’t named yet. You can see the whole URL connection in the DB properties in Squirrel.

    Kind Regards,
    hopcroft

     
  3. vpjaiganesh

    17 octubre, 2011 at 1:04 am

    Hi,
    Was able to solve the problem. The derbyrun.jar should be attached to the class path in the console configuration and the driver to use is ClientDriver from the same jar file. For some reason, it worked once i made these changes.
    Thanks and Regards,
    V.P.J.

     
  4. Pingback: JavaPins
  5. თავისუფალი ბლოგი / Free Blog

    29 octubre, 2013 at 5:24 pm

    I got error in this line : EntityManager manager = SessionManager.getEntityManager(); . How can I get Entity Manager ?

     
    • hop2croft

      31 octubre, 2013 at 3:42 pm

      You need to create your entitymanager associated to a persistenceUnit.

      Regards.

       

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

 
A %d blogueros les gusta esto: