尝试调用 JpaRepository 接口时出现 NullPointerException

发布于 2025-01-17 14:17:29 字数 17770 浏览 0 评论 0原文

我有一个应用程序,它从电子邮件下载文件并将其数据存储到 Oracle 数据库中。 我本来是使用 JPA 来做这件事并且工作得很好,但我决定将其更改为 JPA 以使代码更清晰。 问题是我只是不知道如何初始化或使存储库正常工作,它不断出现 NPE。

堆栈跟踪:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.2)

2022-03-28 18:26:12.890  INFO 15288 --- [           main] c.s.m.ManagementReportApplication        : Starting ManagementReportApplication using Java 1.8.0_202 on WS-9641 with PID 15288 (C:\Users\raca0116\Desktop\company_Project\Management Report\code\managementReport\target\classes started by raca0116 in C:\Users\raca0116\Desktop\company_Project\Management Report\code\managementReport)
2022-03-28 18:26:12.894  INFO 15288 --- [           main] c.s.m.ManagementReportApplication        : No active profile set, falling back to default profiles: default
2022-03-28 18:26:13.765  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-03-28 18:26:13.769  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2022-03-28 18:26:13.842  INFO 15288 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface ca.company.managementReport.database.QuotesRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2022-03-28 18:26:13.843  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 58 ms. Found 0 JDBC repository interfaces.
2022-03-28 18:26:13.873  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-03-28 18:26:13.875  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-03-28 18:26:13.957  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 69 ms. Found 1 JPA repository interfaces.
2022-03-28 18:26:14.847  INFO 15288 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-03-28 18:26:14.943  INFO 15288 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.3.Final
2022-03-28 18:26:15.210  INFO 15288 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-03-28 18:26:16.025  INFO 15288 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-03-28 18:26:17.189  INFO 15288 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-03-28 18:26:17.209  INFO 15288 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.OracleDialect
2022-03-28 18:26:17.214  WARN 15288 --- [           main] org.hibernate.dialect.Oracle9Dialect     : HHH000063: The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead
2022-03-28 18:26:17.215  WARN 15288 --- [           main] org.hibernate.dialect.OracleDialect      : HHH000064: The OracleDialect dialect has been deprecated; use Oracle8iDialect instead
2022-03-28 18:26:17.957  INFO 15288 --- [           main] org.hibernate.tuple.PojoInstantiator     : HHH000182: No default (no-argument) constructor for class: ca.company.managementReport.database.Quotes (class must be instantiated by Interceptor)
2022-03-28 18:26:18.552  INFO 15288 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-03-28 18:26:18.567  INFO 15288 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-03-28 18:26:18.573  INFO 15288 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: private static ca.company.managementReport.database.QuotesRepository ca.company.managementReport.ManagementReportApplication.quotesRepository
2022-03-28 18:26:18.586  INFO 15288 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: private static ca.company.managementReport.database.QuotesRepository ca.company.managementReport.Controller.quotesRepository
2022-03-28 18:26:19.438  INFO 15288 --- [           main] c.s.m.ManagementReportApplication        : Started ManagementReportApplication in 7.294 seconds (JVM running for 8.3)
[DatabaseConnection] Connection established
jdbc:oracle:thin:@localhost:1522/XEPDB1
QuoteId:78420126
2022-03-28 18:26:19.551  INFO 15288 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-03-28 18:26:19.555  INFO 15288 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
Exception in thread "main" java.lang.NullPointerException
    at ca.company.managementReport.Controller.loadFileToDatabase(Controller.java:83)
    at ca.company.managementReport.Controller.start(Controller.java:46)
    at ca.company.managementReport.ManagementReportApplication.main(ManagementReportApplication.java:21)
2022-03-28 18:26:19.579  INFO 15288 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 1

package ca.company.managementReport;

import ca.company.managementReport.database.DatabaseConnection;
import ca.company.managementReport.database.QuotesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ManagementReportApplication {

    public static DatabaseConnection db;

    @Autowired
    private static QuotesRepository quotesRepository;

    public static void main(String[] args) {
        // Start Spring Boot and create tables under database package
        SpringApplication.run(ManagementReportApplication.class, args);

        Controller.start();
    }

}

控制器.java 包 ca.company.managementReport;

import ca.company.managementReport.database.DatabaseConnection;
import ca.company.managementReport.database.Quotes;
import ca.company.managementReport.database.QuotesRepository;
import ca.company.managementReport.mail.ConnectToExchange;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.PropertySet;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;
import microsoft.exchange.webservices.data.property.complex.Attachment;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.property.complex.FolderId;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

@Service
public class Controller {

    @Autowired
    private static QuotesRepository quotesRepository;

    private static DatabaseConnection db;
    public static void start(){

        db = new DatabaseConnection("jdbc:oracle:thin:@localhost:1522/XEPDB1","MY_DB","12345");
        db.LoginDB();

        loadFileToDatabase("QUOTES_20220328_143000.txt");

        Tools.println("Finished");
    }

    private static void loadFileToDatabase(String fileName){
        String[] rows = Tools.readFromFile(fileName);
        String[] content;
        String query;

        for(String r:rows){
            content = r.split(";");

            Quotes quote = new Quotes(
                    content[0], // QUOTE_ID
                    content[1], // ACCOUNT_BILLING_STATUS
                    content[2], // ACCOUNT_TYPE
                    content[3], // QUOTE_CREATED_WHEN
                    content[4], // CUSTOMER_ID
                    content[5], // CUSTOMER_TYPE
                    content[6], // DATE_BILL_RESPONSE
                    content[7], // DISCONNECTION_REASON_CODE
                    content[8], // DISTRIBUTION_CHANNEL
                    content[9], // INTAKE_CHANNEL
                    BigDecimal.valueOf(Double.valueOf(content[10])), // MRC
                    BigDecimal.valueOf(Double.valueOf(content[11])), // NRC
                    content[12], // CUSTOMER_ORDER
                    content[13], // ORDER_AIM
                    content[14], // ORDER_CREATED_WHEN
                    content[15], // ORDER_STATUS
                    content[16] // QUOTE_NAME
            );

            //if(db.isQuoteFound(quote.getQuoteId(), quote.getCustomerId())){
            //    db.deleteQuote(quote.getQuoteId(), quote.getCustomerId());
            //}
            Tools.println("QuoteId:"+quote.getQuoteId());
            Tools.println("teste: "+quotesRepository.findQuoteByQuoteId(quote.getQuoteId())); // It fails here onwards as quoteRepository is Null for some reason

            /*
            query = String.format("INSERT INTO QUOTES VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,%s,'%s','%s','%s','%s','%s')",
                    quote.getQuoteId(),
                    quote.getAccountBillingStatus(),
                    quote.getAccountType(),
                    quote.getQuoteCreatedWhen(),
                    quote.getCustomerId(),
                    quote.getCustomerType(),
                    quote.getDateBillResponse(),
                    quote.getDisconnectionReason(),
                    quote.getDistributionChannel(),
                    quote.getIntakeChannel(),
                    quote.getMonthlyRecurringCharge(),
                    quote.getNonRecurrentCharge(),
                    quote.getOrder(),
                    quote.getOrderAim(),
                    quote.getOrderCreatedWhen(),
                    quote.getOrderStatus(),
                    quote.getQuoteName()
            );
            //Tools.println(query);
            db.insertRow(query);

             */
        }

    }

    private static void listFirstTenItems(ExchangeService service) {
        try{
            ItemView view = new ItemView(10);
            Folder folder = Folder.bind(service, new FolderId(WellKnownFolderName.Inbox));

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startDate = formatter.parse("2022-03-25 00:00:00");
            Date endDate = formatter.parse("2022-03-25 23:59:59");

            SearchFilter greatherThan = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, startDate);
            SearchFilter lessThan = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, endDate);
            SearchFilter keyWord = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "TBAPI Report");

            SearchFilter search = new SearchFilter.SearchFilterCollection(LogicalOperator.And, greatherThan, lessThan, keyWord);
            FindItemsResults<Item> findResults = service.findItems(folder.getId(), search, view);

            if (findResults.getTotalCount() > 0) {
                service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
            } else {
                System.out.println("No reports found");
            }

            for (Item item : findResults.getItems()) {

                System.out.println("[E-mail Information]=====================");
                System.out.println("Subject: " + item.getSubject());
                System.out.println("Sender: " + item.getLastModifiedName());
                System.out.println(item.getDateTimeReceived());
                if(item.getHasAttachments()){
                    System.out.println("Found: ["+item.getAttachments().getCount()+"] attachments");
                    for(Attachment attachment : item.getAttachments()){
                        System.out.println("Attachment: "+attachment.getName());

                        FileAttachment fileAttachment = (FileAttachment) attachment;
                        File output = new File("C:\\Users\\MyUser\\Desktop\\Reports\\"+attachment.getName());
                        fileAttachment.load("C:\\Users\\MyUser\\Desktop\\Reports\\"+attachment.getName());
                    }
                } else {
                    System.out.println("No attachments found");
                }

            }
        }
        catch (RuntimeException e){
            Logger.getLogger(ConnectToExchange.class.getName()).log(Level.SEVERE, null, e);
        } catch (Exception ex) {
            Logger.getLogger(ConnectToExchange.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

QuotesRepository.java 包 ca.company.managementReport.database;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface QuotesRepository extends JpaRepository<Quotes, Long> {
    Quotes findQuoteByQuoteId(String quoteId);
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ca.company</groupId>
    <artifactId>managementReport</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Management Report</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.ews-java-api</groupId>
            <artifactId>ews-java-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.el</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>21.3.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I have an application which downloads a file from e-mail and store it's data into an oracle database.
I was using JPA to do it and was working just fine, but I decided to change it to JPA to make the code more clear.
The problem is that I just don't know how to initialize or make the Repository work in anyway, it keeps getting NPE.

Stacktrace:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.2)

2022-03-28 18:26:12.890  INFO 15288 --- [           main] c.s.m.ManagementReportApplication        : Starting ManagementReportApplication using Java 1.8.0_202 on WS-9641 with PID 15288 (C:\Users\raca0116\Desktop\company_Project\Management Report\code\managementReport\target\classes started by raca0116 in C:\Users\raca0116\Desktop\company_Project\Management Report\code\managementReport)
2022-03-28 18:26:12.894  INFO 15288 --- [           main] c.s.m.ManagementReportApplication        : No active profile set, falling back to default profiles: default
2022-03-28 18:26:13.765  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-03-28 18:26:13.769  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2022-03-28 18:26:13.842  INFO 15288 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface ca.company.managementReport.database.QuotesRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2022-03-28 18:26:13.843  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 58 ms. Found 0 JDBC repository interfaces.
2022-03-28 18:26:13.873  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-03-28 18:26:13.875  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-03-28 18:26:13.957  INFO 15288 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 69 ms. Found 1 JPA repository interfaces.
2022-03-28 18:26:14.847  INFO 15288 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-03-28 18:26:14.943  INFO 15288 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.3.Final
2022-03-28 18:26:15.210  INFO 15288 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-03-28 18:26:16.025  INFO 15288 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-03-28 18:26:17.189  INFO 15288 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-03-28 18:26:17.209  INFO 15288 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.OracleDialect
2022-03-28 18:26:17.214  WARN 15288 --- [           main] org.hibernate.dialect.Oracle9Dialect     : HHH000063: The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead
2022-03-28 18:26:17.215  WARN 15288 --- [           main] org.hibernate.dialect.OracleDialect      : HHH000064: The OracleDialect dialect has been deprecated; use Oracle8iDialect instead
2022-03-28 18:26:17.957  INFO 15288 --- [           main] org.hibernate.tuple.PojoInstantiator     : HHH000182: No default (no-argument) constructor for class: ca.company.managementReport.database.Quotes (class must be instantiated by Interceptor)
2022-03-28 18:26:18.552  INFO 15288 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-03-28 18:26:18.567  INFO 15288 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-03-28 18:26:18.573  INFO 15288 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: private static ca.company.managementReport.database.QuotesRepository ca.company.managementReport.ManagementReportApplication.quotesRepository
2022-03-28 18:26:18.586  INFO 15288 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: private static ca.company.managementReport.database.QuotesRepository ca.company.managementReport.Controller.quotesRepository
2022-03-28 18:26:19.438  INFO 15288 --- [           main] c.s.m.ManagementReportApplication        : Started ManagementReportApplication in 7.294 seconds (JVM running for 8.3)
[DatabaseConnection] Connection established
jdbc:oracle:thin:@localhost:1522/XEPDB1
QuoteId:78420126
2022-03-28 18:26:19.551  INFO 15288 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-03-28 18:26:19.555  INFO 15288 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
Exception in thread "main" java.lang.NullPointerException
    at ca.company.managementReport.Controller.loadFileToDatabase(Controller.java:83)
    at ca.company.managementReport.Controller.start(Controller.java:46)
    at ca.company.managementReport.ManagementReportApplication.main(ManagementReportApplication.java:21)
2022-03-28 18:26:19.579  INFO 15288 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 1

Main

package ca.company.managementReport;

import ca.company.managementReport.database.DatabaseConnection;
import ca.company.managementReport.database.QuotesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ManagementReportApplication {

    public static DatabaseConnection db;

    @Autowired
    private static QuotesRepository quotesRepository;

    public static void main(String[] args) {
        // Start Spring Boot and create tables under database package
        SpringApplication.run(ManagementReportApplication.class, args);

        Controller.start();
    }

}

Controller.java
package ca.company.managementReport;

import ca.company.managementReport.database.DatabaseConnection;
import ca.company.managementReport.database.Quotes;
import ca.company.managementReport.database.QuotesRepository;
import ca.company.managementReport.mail.ConnectToExchange;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.PropertySet;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;
import microsoft.exchange.webservices.data.property.complex.Attachment;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.property.complex.FolderId;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

@Service
public class Controller {

    @Autowired
    private static QuotesRepository quotesRepository;

    private static DatabaseConnection db;
    public static void start(){

        db = new DatabaseConnection("jdbc:oracle:thin:@localhost:1522/XEPDB1","MY_DB","12345");
        db.LoginDB();

        loadFileToDatabase("QUOTES_20220328_143000.txt");

        Tools.println("Finished");
    }

    private static void loadFileToDatabase(String fileName){
        String[] rows = Tools.readFromFile(fileName);
        String[] content;
        String query;

        for(String r:rows){
            content = r.split(";");

            Quotes quote = new Quotes(
                    content[0], // QUOTE_ID
                    content[1], // ACCOUNT_BILLING_STATUS
                    content[2], // ACCOUNT_TYPE
                    content[3], // QUOTE_CREATED_WHEN
                    content[4], // CUSTOMER_ID
                    content[5], // CUSTOMER_TYPE
                    content[6], // DATE_BILL_RESPONSE
                    content[7], // DISCONNECTION_REASON_CODE
                    content[8], // DISTRIBUTION_CHANNEL
                    content[9], // INTAKE_CHANNEL
                    BigDecimal.valueOf(Double.valueOf(content[10])), // MRC
                    BigDecimal.valueOf(Double.valueOf(content[11])), // NRC
                    content[12], // CUSTOMER_ORDER
                    content[13], // ORDER_AIM
                    content[14], // ORDER_CREATED_WHEN
                    content[15], // ORDER_STATUS
                    content[16] // QUOTE_NAME
            );

            //if(db.isQuoteFound(quote.getQuoteId(), quote.getCustomerId())){
            //    db.deleteQuote(quote.getQuoteId(), quote.getCustomerId());
            //}
            Tools.println("QuoteId:"+quote.getQuoteId());
            Tools.println("teste: "+quotesRepository.findQuoteByQuoteId(quote.getQuoteId())); // It fails here onwards as quoteRepository is Null for some reason

            /*
            query = String.format("INSERT INTO QUOTES VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,%s,'%s','%s','%s','%s','%s')",
                    quote.getQuoteId(),
                    quote.getAccountBillingStatus(),
                    quote.getAccountType(),
                    quote.getQuoteCreatedWhen(),
                    quote.getCustomerId(),
                    quote.getCustomerType(),
                    quote.getDateBillResponse(),
                    quote.getDisconnectionReason(),
                    quote.getDistributionChannel(),
                    quote.getIntakeChannel(),
                    quote.getMonthlyRecurringCharge(),
                    quote.getNonRecurrentCharge(),
                    quote.getOrder(),
                    quote.getOrderAim(),
                    quote.getOrderCreatedWhen(),
                    quote.getOrderStatus(),
                    quote.getQuoteName()
            );
            //Tools.println(query);
            db.insertRow(query);

             */
        }

    }

    private static void listFirstTenItems(ExchangeService service) {
        try{
            ItemView view = new ItemView(10);
            Folder folder = Folder.bind(service, new FolderId(WellKnownFolderName.Inbox));

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startDate = formatter.parse("2022-03-25 00:00:00");
            Date endDate = formatter.parse("2022-03-25 23:59:59");

            SearchFilter greatherThan = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, startDate);
            SearchFilter lessThan = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, endDate);
            SearchFilter keyWord = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "TBAPI Report");

            SearchFilter search = new SearchFilter.SearchFilterCollection(LogicalOperator.And, greatherThan, lessThan, keyWord);
            FindItemsResults<Item> findResults = service.findItems(folder.getId(), search, view);

            if (findResults.getTotalCount() > 0) {
                service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
            } else {
                System.out.println("No reports found");
            }

            for (Item item : findResults.getItems()) {

                System.out.println("[E-mail Information]=====================");
                System.out.println("Subject: " + item.getSubject());
                System.out.println("Sender: " + item.getLastModifiedName());
                System.out.println(item.getDateTimeReceived());
                if(item.getHasAttachments()){
                    System.out.println("Found: ["+item.getAttachments().getCount()+"] attachments");
                    for(Attachment attachment : item.getAttachments()){
                        System.out.println("Attachment: "+attachment.getName());

                        FileAttachment fileAttachment = (FileAttachment) attachment;
                        File output = new File("C:\\Users\\MyUser\\Desktop\\Reports\\"+attachment.getName());
                        fileAttachment.load("C:\\Users\\MyUser\\Desktop\\Reports\\"+attachment.getName());
                    }
                } else {
                    System.out.println("No attachments found");
                }

            }
        }
        catch (RuntimeException e){
            Logger.getLogger(ConnectToExchange.class.getName()).log(Level.SEVERE, null, e);
        } catch (Exception ex) {
            Logger.getLogger(ConnectToExchange.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

QuotesRepository.java
package ca.company.managementReport.database;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface QuotesRepository extends JpaRepository<Quotes, Long> {
    Quotes findQuoteByQuoteId(String quoteId);
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ca.company</groupId>
    <artifactId>managementReport</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Management Report</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.ews-java-api</groupId>
            <artifactId>ews-java-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.el</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>21.3.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

裂开嘴轻声笑有多痛 2025-01-24 14:17:29

找到了。
首先,Quotes.java需要一个默认文件:

Quotes(){}

之后,我创建了一个@bean将引号加载到主类的变量中。

package ca.company.managementReport;

import ca.company.managementReport.database.DatabaseConnection;
import ca.company.managementReport.database.QuotesRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ManagementReportApplication {

    public static DatabaseConnection db;

    public static QuotesRepository quotesRepository;

    public static void main(String[] args) {
        // Start Spring Boot and create tables under database package
        SpringApplication.run(ManagementReportApplication.class, args);

    }

    @Bean
    CommandLineRunner run(QuotesRepository quotesRepository){
        return(args -> {
            this.quotesRepository=quotesRepository;
        });
    }


}

然后,通过传递引号repository在Controller.java上的构造函数解决了问题,并使我访问了JPA查询。
start()函数只是一些循环,带有呼叫引号的通话,

public class Controller {
    
    QuotesRepository quotesRepository;

    public Controller(QuotesRepository quotesRepository){
        this.quotesRepository=quotesRepository;
        start();
    }
    .....

我确定这不是最好的方法,但它有效:)
我希望它可以帮助我像我一样遇到麻烦的人。

Found it.
First of all, the Quotes.java needed a default contructor like:

Quotes(){}

After that I created a @Bean to load the QuotesRepository into a variable at main class.

package ca.company.managementReport;

import ca.company.managementReport.database.DatabaseConnection;
import ca.company.managementReport.database.QuotesRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ManagementReportApplication {

    public static DatabaseConnection db;

    public static QuotesRepository quotesRepository;

    public static void main(String[] args) {
        // Start Spring Boot and create tables under database package
        SpringApplication.run(ManagementReportApplication.class, args);

    }

    @Bean
    CommandLineRunner run(QuotesRepository quotesRepository){
        return(args -> {
            this.quotesRepository=quotesRepository;
        });
    }


}

Then, a constructor on Controller.java by passing QuotesRepository solved the problem and gave me access to JPA queries.
The start() function is just some loops with calls to quotesRepository

public class Controller {
    
    QuotesRepository quotesRepository;

    public Controller(QuotesRepository quotesRepository){
        this.quotesRepository=quotesRepository;
        start();
    }
    .....

I am sure that this is not the best approach, but it works :)
I hope it can help someone who's in trouble with that as I was.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文