如何在 Eclipse 的独立(Swing)应用程序中配置休眠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10582586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 18:10:37  来源:igfitidea点击:

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

javaeclipsehibernatedesktop-application

提问by Mahmoud Saleh

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:

我通常在 web 应用程序中使用 hibernate 和 spring,所以我使用 DI 和 maven 进行配置,现在我想在不使用 maven 或 spring 的桌面/swing 应用程序中使用 hibernate,我想知道以下几点:

  1. What jars do i need ?
  2. How to configure the hibernate, and how to make a sample query ?
  1. 我需要什么罐子?
  2. 如何配置休眠,以及如何进行示例查询?

please advise, thanks.

请指教,谢谢。

回答by Yanflea

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).

我不了解 Spring,因此如果您真的想使用它,则必须稍微更新我的答案(例如 Spring 有自己的初始化实体管理器的机制)。

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) :

这是我最近用于我的桌面项目的配置(某些版本可能已经发展),它使用 Hibernate over JPA(即它使用 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.

您可以在maven central上找到所有这些。

Configuration

配置

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

您需要在 META-INF 文件夹中有一个有效的 persistence.xml :

<?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, EntityClass3registered in the persitence.xmlfile above.

为上面persitence.xml文件中注册的EntityClass1EntityClass2EntityClass3创建实体类的常用方法。

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

然后,对于EntityManager...由于您不在 EE 环境中,您必须从EntityManagerFactoty获取它的实例

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

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

(同样,Spring 可能会提供另一种方式来获取它,请查看文档)。

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.

您需要阅读一些文档才能使整个过程与 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
...

回答by Brad

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.

WebApp 和使用 Spring/Hibernate 进行配置的 StandAlone 应用程序之间没有区别。您需要为 hibernate 使用相同的 JAR 文件。对于 spring,您可以取消面向 Web 的 JAR,否则需要所有核心内容。

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.

将 JAR 放在“/lib”文件夹中,并通过在 Manifest.mf 中将其指定为 Maven 构建的一部分将其添加到类路径中。

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

要在命令行上引导 Java 应用程序,只需调用/加载 ApplciationContext 以从您的 Main 类开始,就像这样......

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

这是一个示例 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.jarand add the following to your Spring configuration...

Yanflea 提出的好观点,你会想要使用数据库连接池库,因为它不像在 Web 应用程序中那样为你提供。下载commons-dbcp.jar并将以下内容添加到您的 Spring 配置中...

<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> 

回答by Sumit Desai

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.

SessionFactory 是在任何(基于 Web 或桌面)应用程序中使用 Hibernate 的最佳方式。只需从http://sourceforge.net/projects/hibernate/files/hibernate4/下载最新的休眠版本包。其中有一个必需的文件夹,在 lib 文件夹下。包括所有这些 jar,因为它们对于休眠项目都是必需的。然后定义一个类,它将为您提供 SessionFactory 的单例实例。您可以在 Configuration 的实例上使用 buildSessionFactory() 方法获取此实例(它是一个可以读取和处理休眠配置文件的类)。您必须在文件 hibernate.cfg.xml 中定义所有连接和其他参数(您也可以使用任何其他名称)。有关更多详细信息,请访问http://javabrains.koushik.org/. 在那里,在 Hibernate 部分下,只需阅读前几个教程。那里解释得很好。