How to configure hibernate in standalone (Swing) application in eclipse?
Asked Answered
K

3

5

i usually use hibernate with spring in web applications so i use DI and maven for configuration, now i want to use hibernate in desktop/swing application that doesn't use maven or spring, and i was wondering about the following:

  1. What jars do i need ?
  2. How to configure the hibernate, and how to make a sample query ?

please advise, thanks.

Kneecap answered 14/5, 2012 at 11:37 Comment(3)
Just a note you can still use Maven and Spring in a desktop application. The DI container is not predicated on using the MVC/web stuff. It will make your life a lot easier otherwise you end up adding a ton of boiler plate that is otherwise taken care of for you.Astir
i tried that from sometime and i think i faced some problems with autowiring and putting all jars inside one jar.Kneecap
#575094. The maven dependency plugin facilitates this.Astir
D
6

I don't know about Spring, so you will have to update my answer a little if you really want to use it (for instance Spring has its own mechanism for initializing the entity manager).

Dependencies

This is the configuration I used for a recent desktop project of mine (some versions may have evolved since), that uses Hibernate over JPA (i.e. it uses an EntityManager) :

org.hibernate:hibernate:3.2.7.ga
org.hibernate:hibernate-annotations:3.4.0.GA
org.hibernate:hibernate-entitymanager:3.4.0.GA

You may also need :

commons-collections:commons-collections:3.2.1
asm:asm:3.2
cglib:cglib:2.2
dom4j:dom4j:1.6.1
antlr:antlr:2.7.7
c3p0:c3p0:0.9.1.2

You can find all them on maven central.

Configuration

You need a valid persistence.xml in META-INF folder :

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <persistence-unit name="NONJTAPersistenceUnit" transaction-type="RESOURCE_LOCAL">

        <class>com.yourpackage.EntityClass1</class>
        <class>com.yourpackage.EntityClass2</class>
        <class>com.yourpackage.EntityClass3</class>

        <properties>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
            <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://hostXYZ/yourdatabase"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

Update it with your own database info/driver.

Usage

Create Entity classes the usual way for EntityClass1, EntityClass2, EntityClass3 registered in the persitence.xml file above.

Then, for the EntityManager... since your are not in a EE environment, you must get an instance of it from the EntityManagerFactoty :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("NONJTAPersistenceUnit");
EntityManager em = emf.createEntityManager();

(Again, Spring may provide an other way to get it, check on the documentation).

From there you can perform, for instance a persist operation, this way :

em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();

You have a little documentation reading to do to make the whole thing sticks with Spring.

EDIT

A sample query :

Query query = em.createQuery("select e from EntityClass1 where e.name = :name");
query.setParameter(:name, "foo");
List results = query.getResultList();

EDIT

Updated versions :

hibernate-core-3.5.1-Final
hibernate-entitymanager-3.5.1-Final
hibernate-jpa-2.0-api-1.0.0.Final
hibernate-annotations-3.5.1-Final
hibernate-commons-annotations-3.2.0.Final
dom4j-1.6.1
slf4j-api-1.6.4
slf4j-log4j12-1.6.4
...
Drone answered 14/5, 2012 at 13:2 Comment(13)
thanks for the answer, and i am not using spring just basic swing application.Kneecap
Ok, sorry, I probably misread your question. Forget my remarks about Spring in my answer then, and let me know if what I propose is working for you.Drone
ok i will try that but why do you use EntityManager instead of SessionFactory ? and how to make a select query with the entityManager ?Kneecap
SessionFactory is the legacy way of hibernate for managing Sessions. Since, the JPA standard was created, and obviously Hibernate has an implementation of it. This actually works the same way, you can see the EntityManager as a replacement of your SessionFactory. You are free to keep using the SessionFactory if you want to though, but I think most people are used to JPA today. I'll edit my post with a sample select query.Drone
@Msaleh See MyDaoHibernate in my answer and it's use of the getHibernateTemplate().get(...) that will return an object. Are you looking to select something with a particular query/SQL?Nutpick
@Yanflea. Good point about the connection pooling. I've added that to my answer as well ;)Nutpick
@Yanflea, can you please review the dependencies ? i am using hibernate 3.5.1 final.Kneecap
please take a look at my problem here with the jars: #10586156Kneecap
I reviewed them with the ones you mention in you other ticket (hope you don't mind :-p :-) ).Drone
well for me everything works fine now for the jars, and the configuration, but can you please add the configuration for the sessionFactory as well, because i am familiar with working with it.Kneecap
You have very good examples here : kodejava.org/examples/245.html and here : kodejava.org/examples/247.htmlDrone
complete answer is here now in my question #10587012Kneecap
How can I use this WITHOUT any mapping in the persistence unit?Platinize
N
1

There is no difference between a WebApp and a StandAlone application that uses Spring/Hibernate for it's configuration. You requrie the same JAR files for hibernate. For spring you can do away with the Web oriented JARs but otherwise all the core stuff is required.

Place the JARs in a "/lib" folder and add it to your classpath by specifying it in your Manifest.mf as part of your Maven build.

To bootstrap a Java application on command line just invoke/load the ApplciationContext to start from your Main class like this...

public static void main(String[] args) {
...

String[] contextXml = new String[]{ "resources/spring-context.xml", "resources/spring-db.xml" };

ApplicationContext ctx = new ClassPathXmlApplicationContext(contextXml);

// invoke your business logic

MyBusinessService bean = getBean(MyBusinessService.class);

bean.doSomething();
...
}

Here's an example DAO

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class MyDaoHibernate extends HibernateDaoSupport {


    /*** Functional methods ***/

    public void save(MyValueObject vo) throws DatabaseException {       
        getHibernateTemplate().saveOrUpdate(vo);
    }

    public MyValueObject get(Long id) throws DatabaseException {
        return getHibernateTemplate().get(MyValueObject.class, id);
    }

    /*** Getter & Setters ***/

    @Autowired
    public void initSessionFactory(SessionFactory sessionFactory) {
        this.setSessionFactory(sessionFactory);
    }   
}

[EDIT]

Good point raised by Yanflea, you'll want to be using a database connection pooling library because this is not provided for you like it is, in a Web App. Download commons-dbcp.jar and add the following to your Spring configuration...

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName"    value="com.sybase.jdbc2.jdbc.SybDriver" />
    <property name="url"                value="${jdbc.url}" />
    <property name="username"           value="${jdbc.username}" />
    <property name="password"           value="${jdbc.password}" />
</bean> 
Nutpick answered 14/5, 2012 at 12:41 Comment(3)
this desktop app doesn't use spring or maven.Kneecap
I suggest you use Spring for your desktop app. If you're already familiar with Spring you won't have to adjust your style of coding/testing. If you're not using Maven you'll still have to package up your application into a JAR file, so you'll end up using Maven or ANT to do this.Nutpick
It's true. If you are used to Spring, keep using it. The fact that your are on the desktop now does not prevent it at all. Same for Maven.Drone
W
0

SessionFactory is the best way to use Hibernate in any(web based or Desktop) Application. Just download latest hibernate release bundle from http://sourceforge.net/projects/hibernate/files/hibernate4/. There's a required folder in it, under lib folder. Include all those jars as they all are mandatory for a hibernate project. Then define a class which will provide you with singleton instance of SessionFactory . You can obtain this instance using buildSessionFactory() method on an instance of Configuration(It's a class which can read and process hibernate config file). You will have to define all your connection and other parameters in a file hibernate.cfg.xml(You can also use any other name you want). For more details, just go to http://javabrains.koushik.org/. There, under Hibernate section, just go through first few tutorials. It's explained very nicely there.

Wiencke answered 14/5, 2012 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.