问题
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:
- What jars do i need ?
- How to configure the hibernate, and how to make a sample query ?
please advise, thanks.
回答1:
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
...
回答2:
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>
回答3:
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.
来源:https://stackoverflow.com/questions/10582586/how-to-configure-hibernate-in-standalone-swing-application-in-eclipse