如何在一个项目中同时运行2个不相关的实体(两个存储库)?可能吗?

问题描述 投票:0回答:1

我试图在一个项目中制作2个实体(不相关)。我正在使用Java springboot连接到mysql数据库。那么我能做的最好的方法是什么?因为我试图建立2个存储库,但我只接替其中的一个。另一个是给我一个错误。它给我的错误,即使它在mysql workbench中运行查询时实际上很好

在我的存储库(AccountRepository.java)中,这不起作用,我把这样的东西:

public interface AccountRepository extends CrudRepository<Accounts, Integer> {

    @Query("SELECT applicationPassword FROM Accounts where applicationName = 'myApp'")
    String findPasswordApp();
}

在实体文件(Accounts.java)中,我放了这样的东西

@Entity
public class Accounts {
    @Id
    private Integer accountID;
    private String applicationName;
    private String applicationPassword; 
    public void setAccountID(Integer accountID) {
        this.accountID = accountID;
    }

public void setApplicationName(String applicationName) {
    this.applicationName = applicationName;
}

public void setApplicationPassword(String applicationPassword) {
    this.applicationPassword = applicationPassword;
}

public Integer getAccountID() {
    return accountID;
}

public String getApplicationName() {
    return applicationName;
}

public String getApplicationPassword() {
    return applicationPassword;
}
}

但它给了我错误。我想从这个实体得到的是,我可以检查数据库中的值(读取),我已经将它手动放在mysql工作台中。

这是我在mysql workbench中首先执行的表查询

CREATE TABLE Accounts (
    accountID int,
    applicationName varchar(255),
    applicationPassword varchar(255)
);  

而且这里是我成功插入数据的时候:

INSERT INTO Accounts (accountID, applicationName, applicationPassword)
VALUES ('1', 'myApp', 'password'));

我的代码有什么问题吗?请帮忙

编辑:我试着用这行上的try catch掩盖'String password = accountRepository.findPasswordApp(); '那就像'java.lang.NullPointerException'那样给我异常

这是我的完整例外:org.eclipse.paho.client.mqttv3.internal.CommsCallback.deliverMessage(CommsCallback.java:499)org.eclipse.paho.client.mqttv3.internal.CommsCallback.handleMessage(CommsCallback.java: 402)atg.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:206)at java.util.concurrent.Executors $ RunnableAdapter.call(Executors.java:511)at java.util.concurrent java.util.concurrent.ScheduledThreadPoolExecutor上的.FutureTask.run(FutureTask.java:266)$ java.util.concurrent.ScheduledThreadPoolExecutor $ ScheduledFutureTask.run $ $(ScheduledThreadPoolExecutor.java:297) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624)at java.lang.Thread.run(Thread.java:748) )'

java mysql spring spring-boot
1个回答
0
投票

我非常确定您的存储库缺少注释或者不在扫描包中。我有10个存储库的项目,所以这绝对不是问题,你在@Query注释中的HQL似乎有点好。

没有理由那两个不能一起工作,所以我猜你的@Autowired字段为repo抛出错误在运行时为null。你可能只是忘了注释。您是否在AccountRepository之上没有@Repository注释?主类或配置中的@ComponentScan是否没有包含它的包?

如果缺少这些中的任何一个,那就是你的问题。你能用例外的全文编辑它吗?

© www.soinside.com 2019 - 2024. All rights reserved.