java - 在单元测试中为 Hibernate 创建 JNDI 上下文

标签 java hibernate jdbc junit jndi

我有一个配置了 Hibernate 的项目:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="jndi.url">jdbc/sqliteDB</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
        <property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
        <property name="hibernate.connection.release_mode">auto</property>
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.connection.autoReconnect">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="com.web.models.SystemUsers"/>
    </session-factory>
</hibernate-configuration>

我想运行一些 JUnit 文件来测试数据库配置。我创建这个 Junit 文件:

@BeforeClass
    public static void setUp() throws Exception
    {
        try
        {
            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            InitialContext ic = new InitialContext();

            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            SQLiteDataSource ds = new SQLiteDataSource();
            ds.setUrl("jdbc:sqlite:/C:/sqlite/test.sqlite");

            ic.bind("jdbc/sqliteDB", ds);
        }
        catch (NamingException ex)
        {
            Logger.getLogger(SQLiteDataSource.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

但是当我运行它时,我收到此错误:

SEVERE: null
javax.naming.NameNotFoundException: Name [jdbc/sqliteDB] is not bound in this Context. Unable to find [jdbc].
    at org.apache.naming.NamingContext.bind(NamingContext.java:896)
    at org.apache.naming.NamingContext.bind(NamingContext.java:192)
    at org.apache.naming.NamingContext.bind(NamingContext.java:209)
    at javax.naming.InitialContext.bind(InitialContext.java:425)
    at com.net.server.UserProvisionTest.setUp(UserProvisionTest.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)

你知道我如何创建 JNDI 上下文以便 hibernate 可以使用它进行数据库查询吗?

更新。现在我收到此错误:

listUsersTest(com.net.server.UserProvisionTest)  Time elapsed: 0.001 sec  <<< ERROR!
java.lang.NoClassDefFoundError: Could not initialize class com.web.models.HibernateUtil

我使用这个 hibernate 工厂类:

public class HibernateUtil
{
    private static final SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static
    {
        try
        {
            StandardServiceRegistry standardRegistry
                = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
            Metadata metaData
                = new MetadataSources(standardRegistry).getMetadataBuilder().build();
            sessionFactory = metaData.getSessionFactoryBuilder().build();
        }
        catch (Throwable th)
        {
            System.err.println("Enitial SessionFactory creation failed" + th);
            throw new ExceptionInInitializerError(th);
        }
    }

    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
}

编辑:这是我的 POM 文件:

<dependencies>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.faces</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.10.Final</version>
        </dependency>
        <!-- SQLite JDBC library -->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.18.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!--JBoss/Weld Refrence Implementation for CDI on a Servlet Container -->
        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet</artifactId>
            <version>2.4.3.Final</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.6</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>com.sun.el</groupId>
            <artifactId>el-ri</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.omnifaces</groupId>
            <artifactId>omnifaces</artifactId>
            <version>2.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>catalina</artifactId>
            <version>6.0.53</version>
            <scope>test</scope>
        </dependency>
        <!--
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.10</version>
        </dependency>
        -->
    </dependencies>

最佳答案

您尝试以错误的方式绑定(bind)。 而不是

ic.bind("jdbc/sqliteDB", ds);

这样做,

c.bind("java:/comp/env/jdbc/sqliteDB", ds);

您应该将其绑定(bind)(添加)到 java:/comp/env/jdbc,因为它是子上下文。

<小时/>

修复:第二个异常(exception) - 而不是:

<属性名称=“jndi.url”>jdbc/sqliteDB

添加此:

<属性名称=“hibernate.connection.datasource”>java:comp/env/jdbc/sqliteDB

关于java - 在单元测试中为 Hibernate 创建 JNDI 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870028/

相关文章:

java - 如果长度为奇数,则需要帮助删除数组中的中间元素,如果长度为偶数,则需要帮助删除中间的两个元素

java - commit() 期间通信链接失败。交易决议未知

java - 如何将 log4j 包安装到 Eclipse 中?

java - Android:无法从静态上下文中引用非静态方法

java - 在 Hibernate 中映射一个实体中的多个集合

java - Hibernate 映射 MySQL DateTime

java - 从数据库中检索最大值并在 java eclipse 中的 JTextfield 中显示

java - Hibernate - C3P0 - 连接池 - 事务

mysql - 无法在 Pehtaho 报表设计器中通过 JDBC 连接到数据库

java - 无法使用 ucanaccess 创建可更新的结果集