我试图用一个createAccount()方法设置一个简单的端点来访问MySQL数据库,但似乎Spring Boot不能在我的所有类中连接/创建Bean.

以下是代码详细信息:

MykitchenresourcesApplication

package com.it326.mykitchenresources;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan(basePackages = "com.it326.mykitchenresources.*")
@EntityScan("com.it326.mykitchenresources.*")  
@EnableJpaRepositories("com.it326.mykitchenresources.*")
public class MykitchenresourcesApplication {

    public static void main(String[] args) {
        SpringApplication.run(MykitchenresourcesApplication.class, args);
    }

}

AccountController

package com.it326.mykitchenresources.controllers;

// Imports

@RestController
@RequestMapping("/account")
public class AccountController {

    private final AccountService accountService;

    @Autowired
    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @RequestMapping("/hello")
    public String hello() {
        return "Hello, world!";
    }

    @PostMapping("/create")
    public ResponseEntity<String> createAccount(@RequestBody AccountDTO accountDTO) {
        // Retrieve values from the DTO (Data Transfer Object)
        String name = accountDTO.getName();
        String username = accountDTO.getUsername();
        String password = accountDTO.getPassword();

        // Create the account
        Account createdAccount = accountService.createAccount(name, username, password);

        if (createdAccount != null) {
            return ResponseEntity.status(HttpStatus.CREATED).body("Account created successfully");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create account");
        }
    }
}

AccountService

package com.it326.mykitchenresources.services;

// Imports

@Service
public class AccountService {
    
    @Autowired
    private final AccountDb accountDb;

    public AccountService(AccountDb accountDb) {
        this.accountDb = accountDb;
    }

    public Account createAccount(String name, String username, String password) {
        Account account = new Account();
        account.setName(name);
        account.setUserName(username);
        account.setHashedPassword(hashPassword(password));
        return accountDb.save(account);
    }

    private String hashPassword(String password) {
        // Generate a salt and hash the password using BCrypt
        String salt = BCrypt.gensalt();
        return BCrypt.hashpw(password, salt);
    }
}

AccountDb (my repository class)

package com.it326.mykitchenresources.dbs;

// Imports

@Repository
public interface AccountDb extends JpaRepository<Account, Integer> {
    Account findByUsername(String username);
}

Account (my entity class)

package com.it326.mykitchenresources.entities;

// Imports

@Entity
@Table(name = "accounts")
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "account_id")   
    private int accountId;

    @Column(name = "name", length = 45)
    private String name;

    @Column(name = "username", length = 45)
    private String username;

    @Column(name = "hashed_password", length = 45)
    private String hashedPassword;
    
    // Constructors, getters, setters, etc.
    public Account(){}

    public Account(int accountId, String name, String username, String hashedPassword){
        this.accountId = accountId;
        this.name = name;
        this.username = username;
        this.hashedPassword = hashedPassword;
    }
    
    public int getAccountId() {
        return accountId;
    }
    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUserName() {
        return username;
    }
    public void setUserName(String username) {
        this.username = username;
    }
    public String getHashedPassword() {
        return hashedPassword;
    }
    public void setHashedPassword(String hashedPassword) {
        this.hashedPassword = hashedPassword;
    }
}

application.properties

spring.datasource.url= // My URL is here.
spring.datasource.username= // Same with my username
spring.datasource.password= // And my password
server.port=8081
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

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>3.1.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.it326</groupId>
    <artifactId>mykitchenresources</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mykitchenresources</name>
    <description>Backend for myKitchen</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Password Hashing Dependency -->
        <dependency>
            <groupId>org.mindrot</groupId>
            <artifactId>jbcrypt</artifactId>
            <version>0.4</version> <!-- or the latest version available -->
        </dependency>

        <!-- Database Connection Dependencies -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.5.7.Final</version> <!-- Use the appropriate version -->
        </dependency>
        
        <!-- Testing Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

我try 将我的所有类放入与主应用程序相同的包中,但似乎这并没有解决我的问题.

我还try 了mvn clean install次,没有使用任何类,以确保我的主应用程序运行正常,而且运行得很好.

The logs and error I'm getting:

o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - 
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController' defined in file [C:\Users\...\target\classes\com\it326\mykitchenresources\controllers\AccountController.class]: 
Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'accountService' defined in file [C:\Users\...\target\classes\com\it326\mykitchenresources\services\AccountService.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'accountDb' defined in com.it326.mykitchenresources.dbs.AccountDb defined in @EnableJpaRepositories declared on MykitchenresourcesApplication: Not a managed type: class com.it326.mykitchenresources.entities.Account

这是我第一次自己建立一个Spring Boot项目,所以我可能遗漏了一些非常明显的东西,并且正盯着我的脸;任何帮助和指示都将非常感激!谢谢!

推荐答案

正如在注释中所述,您应该将显式依赖项从remove改为hibernate-core.这一条:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.5.7.Final</version> <!-- Use the appropriate version -->
</dependency>

做完之后,你应该在你的课堂上使用check all imports.尤其是实体类.不应该有从javax.persistence个包进口.只从jakarta.persistence开始.否则,将会出现对象不匹配和如下所示的错误:not a managed type.

Java相关问答推荐

编译期间错误(Java 0000)Android .Net MAUI

Maven Google Sheets版本问题

具有额外列的Hibert多对多关系在添加关系时返回NonUniqueHealthExcellent

AlarmManager没有在正确的时间发送alert

S的字符串表示是双重精确的吗?

AssertJ Java:多条件断言

使用Spring Boot3.2和虚拟线程的并行服务调用

无法了解Java线程所消耗的时间

为什么S的文档中说常量方法句柄不能在类的常量池中表示?

第二次按下按钮后,我需要将按钮恢复到其原始状态,以便它可以再次工作

如何使用Jackson将XML元素与值和属性一起封装

有没有更快的方法在N个容器中删除重复项?

在执行流和相关操作时,使用Java泛型为2个方法执行相同的操作,但对象不同

Kotlin Val是否提供了与Java最终版相同的可见性保证?

我怎样才能让IntelliJ标记toString()的任何实现?

为什么相同的数据条码在视觉上看起来不同?

Java KeyListener不工作或被添加

放置在变量中的Java成员引用不相等

";重复键的值提示唯一约束«;livre_genre_pkey»";例外

OpenAPI Maven插件生成错误的Java接口名称