简体   繁体   English

如何在主类 Java 中使用 DAO 模块?

[英]How to use a DAO module in a main class Java?

I need to use a class object into a main class, but I'm get some problems:我需要在主类中使用一个类对象,但我遇到了一些问题:

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

}

And this is my这是我的

persistence.xml:持久性.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>

But I'm getting this error:但我收到此错误:

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

Where am I wrong?我哪里错了? How Can I use the DAO without any problem in a Java Class?如何在 Java 类中毫无问题地使用 DAO?

You cannot use injection this way.您不能以这种方式使用注入。 I think that this is a short and nice article about how to use DI in Java: https://www.vogella.com/tutorials/DependencyInjection/article.html .我认为这是一篇关于如何在 Java 中使用 DI 的简短而精彩的文章: https : //www.vogella.com/tutorials/DependencyInjection/article.html

However, I would recommend you to use some framework, eg Spring (nice tutorial here: https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring ).但是,我建议您使用一些框架,例如 Spring(这里有很好的教程: https : //www.baeldung.com/inversion-control-and-dependency-injection-in-spring )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM