首页 > 解决方案 > 如何在主类 Java 中使用 DAO 模块?

问题描述

我需要在主类中使用一个类对象,但我遇到了一些问题:

public static void main(String[] args) throws NoElementFoundException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("fantacalcio_rest");
    EntityManager em = emf.createEntityManager();

}

这是我的

持久性.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="fantacalcio_rest">
        <jta-data-source>java:/fantacalcio_rest</jta-data-source>
        <class>model.Player</class>
        <class>model.Module</class>
        <class>model.User</class>
        <class>model.League</class>
        <class>model.FantaPlayer</class>

        <class>model.PlayerTransfer</class>
        <class>model.Formation</class>
        <class>model.PlayerMark</class>
        <class>model.FantaPlayerMatch</class>
        <class>model.CalendarSerieA</class>
        <class>model.FantaPlayerRank</class>
        <class>model.RankRow</class>

        <properties>
            <!-- Properties for Hibernate -->
            <property name="hibernate.dialect"
                value="org.hibernate.dialect.MySQL5Dialect" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.enable_lazy_load_no_trans"
                value="true" />
        </properties>
    </persistence-unit>

</persistence>

但我收到了这个错误:

Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

我哪里错了?如何在 Java 类中毫无问题地使用 DAO?

标签: javajpadependency-injection

解决方案


您不能以这种方式使用注入。我认为这是一篇关于如何在 Java 中使用 DI 的简短而精彩的文章:https ://www.vogella.com/tutorials/DependencyInjection/article.html 。

但是,我建议您使用一些框架,例如 Spring(这里的教程很好:https ://www.baeldung.com/inversion-control-and-dependency-injection-in-spring )。


推荐阅读