Spring Boot Sping Boot JPA错误:“不是托管类型:class com.example1.project.User.User

huwehgph  于 2023-08-04  发布在  Spring
关注(0)|答案(1)|浏览(133)

我是Sping Boot 和JPA的初学者。我正在使用这些技术开发一个应用程序,但我遇到了一个问题。当我运行应用程序时,我遇到了与我的User实体类相关的“Not a managed type”异常。

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.

2023-07-31 15:11:07.786 ERROR 15380 --- \[           main\] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController' defined in file \[C:\\1-project\\target\\classes\\com\\example1\\project\\Login\\LoginController.class\]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file \[C:\\1-project\\target\\classes\\com\\example1\\project\\User\\UserService.class\]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.example1.project.User.UserRepository defined in @EnableJpaRepositories declared on Application: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example1.project.User.User

字符串

用户实体类:

package com.example1.project.User;

import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;

@Entity
@Table(name = "users")
public class User
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotBlank
    private String name;
    @Email
    @NotBlank
    private String email;
    @NotBlank
    private String username;
    @NotBlank
    private String password;

    public User() {}

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

用户仓库:

package com.example1.project.User;

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

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);

}

用户服务:

package com.example1.project.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    public User authenticateUser(String username, String password) {
        User user = userRepository.findByUsername(username);

        if (user != null) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (passwordEncoder.matches(password, user.getPassword())) {
                return user; 
            }
        }

        return null; 
    }

    // Implement service methods using the repository methods
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    public User saveUser(User user) {
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    
}

LoginController:

package com.example1.project.Login;

import com.example1.project.User.User;
import com.example1.project.User.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/login")
public class LoginController {
    private final UserService userService;

    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        // Extract username and password from the login request payload
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

       
        User authenticatedUser = userService.authenticateUser(username, password);

        if (authenticatedUser != null) {
            // User is authenticated, return user data or a token (if using token-based authentication)
            return ResponseEntity.ok(authenticatedUser);
        } else {
            // Invalid credentials, return an error response
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }
}


我最初怀疑我注解实体类的方式可能有问题,所以我仔细检查了它们,以确保我使用了正确的注解。我希望如果注解是正确的,应用程序运行时不会出现任何“Not a managed type”错误。然而,即使我的实体类似乎注解正确,错误仍然存在

我的项目结构如下:

src
├── main
│   └── java
│       └── com.example1.project
│                             └──Login(subpackage)
│                             └──Order(subpackage)
│                             └──Product(subpackage)
│                             └──User(subpackage)
│                             └──Application(main class)
│                             └──CorsConfig(class)                          
│                             └──SecurityConfiguration(class)                     
└── test

新错误:

在我的mysql表称为产品,这个表有4列称为id,描述,名称,价格,我想从 Postman 发送到mysql这个数据:

{
  "name": "Case",
  "price": 19.99
}


但是当我按下发送,我得到401未经授权的 Postman ,网址是http://localhost:8080/api/products。
我添加了一个名为SecurityConfiguration的类,以为如果我将用户名设置为“user”,密码设置为“password”,我可以转到PostMan→Authorization并添加用户和密码作为凭据,但我得到了相同的错误:

import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.security.core.userdetails.User;
        import org.springframework.security.core.userdetails.UserDetails;
        import org.springframework.security.provisioning.InMemoryUserDetailsManager;

        import javax.sql.DataSource;

@Configuration
public class SecurityConfiguration {
    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }
}

我的ProductController类:

package com.example1.project.Product;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    private final ProductService productService;

    @Autowired
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    @GetMapping("/{id}")
    public Product getProductById(@PathVariable Long id) {
        return productService.getProductById(id);
    }

    @GetMapping("/search")
    public List<Product> searchProducts(@RequestParam String keyword) {
        return productService.searchProducts(keyword);
    }

    @PostMapping
    public Product addProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }

    @PutMapping("/{id}")
    public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
        product.setId(id);
        return productService.saveProduct(product);
    }

    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
    }
}


当我启动我的应用程序时,我在控制台中得到以下内容:

2023-08-01T18:05:24.940+03:00  INFO 13520 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-08-01T18:05:24.941+03:00  INFO 13520 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-08-01T18:05:24.943+03:00  INFO 13520 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
2023-08-01T18:13:33.563+03:00  WARN 13520 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=7m32s427ms71µs900ns).

ubof19bj

ubof19bj1#

在你的安全配置类中,你还需要一个允许httpBasic身份验证的SecurityFilterChain的bean,这就是为什么你得到401未授权的原因,我想我是有帮助的
只需查看HttpSecurity模块中的Configuration文档

相关问题