Spring Boot JPA错误:“不是受管理的类型:类com.example1.project.User.User”。

huangapple go评论140阅读模式
英文:

Spring Boot JPA Error: "Not a managed type: class com.example1.project.User.User

问题

I'm a beginner in Spring Boot and JPA. I'm developing an application using these technologies, but I've run into a problem. When I run the application, I encounter a 'Not a managed type' exception related to my User entity class.

User entity class:

  1. package com.example1.project.User;
  2. import jakarta.persistence.*;
  3. import jakarta.validation.constraints.Email;
  4. import jakarta.validation.constraints.NotBlank;
  5. @Entity
  6. @Table(name = "users")
  7. public class User
  8. {
  9. @Id
  10. @GeneratedValue(strategy = GenerationType.IDENTITY)
  11. private Long id;
  12. @NotBlank
  13. private String name;
  14. @Email
  15. @NotBlank
  16. private String email;
  17. @NotBlank
  18. private String username;
  19. @NotBlank
  20. private String password;
  21. // Constructors, Getters, and Setters
  22. }

UserRepository:

  1. package com.example1.project.User;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. public interface UserRepository extends JpaRepository<User, Long> {
  4. User findByUsername(String username);
  5. }

UserService:

  1. package com.example1.project.User;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  4. import org.springframework.stereotype.Service;
  5. import java.util.List;
  6. @Service
  7. public class UserService {
  8. // Constructor, authenticateUser method, and other service methods
  9. }

LoginController:

  1. package com.example1.project.Login;
  2. import com.example1.project.User.User;
  3. import com.example1.project.User.UserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.*;
  8. @RestController
  9. @RequestMapping("/api/login")
  10. public class LoginController {
  11. // Constructor and login method
  12. }

I initially suspected that there might be an issue with the way I had annotated my entity classes, so I double-checked them to make sure I had used the correct annotations. I was expecting that if the annotations were correct, the application would run without any 'Not a managed type' errors. However, even though my entity classes seem to be correctly annotated, the error still persists.

This is my project structure:

  1. src
  2. ├── main
  3. └── java
  4. └── com.example1.project
  5. ├── Login (subpackage)
  6. ├── Order (subpackage)
  7. ├── Product (subpackage)
  8. ├── User (subpackage)
  9. └── Application (main class)
  10. └── CorsConfig (class)
  11. └── SecurityConfiguration (class)
  12. └── test

The new error:

In my MySQL table called product, this table has 4 columns called id, description, name, price, I wanted to send this data from Postman to MySQL:

  1. {
  2. "name": "Case",
  3. "price": 19.99
  4. }

But when I press Send, I get a 401 Unauthorized error in Postman, and the URL is http://localhost:8080/api/products.

I added a class called SecurityConfiguration thinking that if I set the username "user" and the password "password," I could go to PostMan → Authorization and add the user and password as credentials, but I get the same error:

SecurityConfiguration:

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.core.userdetails.User;
  4. import org.springframework.security.core.userdetails.UserDetails;
  5. import org.springframework.security.provisioning.InMemoryUserDetailsManager;
  6. @Configuration
  7. public class SecurityConfiguration {
  8. @Bean
  9. public InMemoryUserDetailsManager userDetailsService() {
  10. UserDetails user = User.withDefaultPasswordEncoder()
  11. .username("user")
  12. .password("password")
  13. .roles("USER")
  14. .build();
  15. return new InMemoryUserDetailsManager(user);
  16. }
  17. }

ProductController class:

  1. package com.example1.project.Product;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.*;
  4. import java.util.List;
  5. @RestController
  6. @RequestMapping("/api/products")
  7. public class ProductController {
  8. // Constructor and various endpoints for handling products
  9. }

When I start my application, I get the following in the console:

  1. 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'
  2. 2023-08-01T18:05:24.941+03:00 INFO 13520 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
  3. 2023-08-01T18:05:24.943+03:00 INFO 13520 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
  4. 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).
英文:

I'm a beginner in Spring Boot and JPA. I'm developing an application using these technologies, but I've run into a problem. When I run the application, I encounter a 'Not a managed type' exception related to my User entity class.

  1. Error starting ApplicationContext. To display the conditions report re-run your application with &#39;debug&#39; enabled.
  2. 2023-07-31 15:11:07.786 ERROR 15380 --- \[ main\] o.s.boot.SpringApplication : Application run failed
  3. org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;loginController&#39; defined in file \[C:\-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 &#39;userService&#39; defined in file \[C:\-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 &#39;userRepository&#39; 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

User entity class:

  1. package com.example1.project.User;
  2. import jakarta.persistence.*;
  3. import jakarta.validation.constraints.Email;
  4. import jakarta.validation.constraints.NotBlank;
  5. @Entity
  6. @Table(name = &quot;users&quot;)
  7. public class User
  8. {
  9. @Id
  10. @GeneratedValue(strategy = GenerationType.IDENTITY)
  11. private Long id;
  12. @NotBlank
  13. private String name;
  14. @Email
  15. @NotBlank
  16. private String email;
  17. @NotBlank
  18. private String username;
  19. @NotBlank
  20. private String password;
  21. public User() {}
  22. // Getters and Setters
  23. public Long getId() {
  24. return id;
  25. }
  26. public void setId(Long id) {
  27. this.id = id;
  28. }
  29. public String getName() {
  30. return name;
  31. }
  32. public void setName(String name) {
  33. this.name = name;
  34. }
  35. public String getUsername() {
  36. return username;
  37. }
  38. public void setUsername(String username) {
  39. this.username = username;
  40. }
  41. public String getEmail() {
  42. return email;
  43. }
  44. public void setEmail(String email) {
  45. this.email = email;
  46. }
  47. public String getPassword() {
  48. return password;
  49. }
  50. public void setPassword(String password) {
  51. this.password = password;
  52. }
  53. }

UserRepository:

  1. package com.example1.project.User;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. public interface UserRepository extends JpaRepository&lt;User, Long&gt; {
  4. User findByUsername(String username);
  5. }

UserService:

  1. package com.example1.project.User;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  4. import org.springframework.stereotype.Service;
  5. import java.util.List;
  6. @Service
  7. public class UserService {
  8. private final UserRepository userRepository;
  9. @Autowired
  10. public UserService(UserRepository userRepository) {
  11. this.userRepository = userRepository;
  12. }
  13. public User authenticateUser(String username, String password) {
  14. User user = userRepository.findByUsername(username);
  15. if (user != null) {
  16. BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  17. if (passwordEncoder.matches(password, user.getPassword())) {
  18. return user;
  19. }
  20. }
  21. return null;
  22. }
  23. // Implement service methods using the repository methods
  24. public List&lt;User&gt; getAllUsers() {
  25. return userRepository.findAll();
  26. }
  27. public User getUserById(Long id) {
  28. return userRepository.findById(id).orElse(null);
  29. }
  30. public User saveUser(User user) {
  31. user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
  32. return userRepository.save(user);
  33. }
  34. public void deleteUser(Long id) {
  35. userRepository.deleteById(id);
  36. }
  37. }

LoginController:

  1. package com.example1.project.Login;
  2. import com.example1.project.User.User;
  3. import com.example1.project.User.UserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. @RestController
  12. @RequestMapping(&quot;/api/login&quot;)
  13. public class LoginController {
  14. private final UserService userService;
  15. @Autowired
  16. public LoginController(UserService userService) {
  17. this.userService = userService;
  18. }
  19. @PostMapping
  20. public ResponseEntity&lt;?&gt; login(@RequestBody LoginRequest loginRequest) {
  21. // Extract username and password from the login request payload
  22. String username = loginRequest.getUsername();
  23. String password = loginRequest.getPassword();
  24. User authenticatedUser = userService.authenticateUser(username, password);
  25. if (authenticatedUser != null) {
  26. // User is authenticated, return user data or a token (if using token-based authentication)
  27. return ResponseEntity.ok(authenticatedUser);
  28. } else {
  29. // Invalid credentials, return an error response
  30. return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(&quot;Invalid username or password&quot;);
  31. }
  32. }
  33. }

I initially suspected that there might be an issue with the way I had annotated my entity classes, so I double-checked them to make sure I had used the correct annotations. I was expecting that if the annotations were correct, the application would run without any 'Not a managed type' errors. However, even though my entity classes seem to be correctly annotated, the error still persists

This is my project structure:

  1. src
  2. ├── main
  3. └── java
  4. └── com.example1.project
  5. └──Login(subpackage)
  6. └──Order(subpackage)
  7. └──Product(subpackage)
  8. └──User(subpackage)
  9. └──Application(main class)
  10. └──CorsConfig(class)
  11. └──SecurityConfiguration(class)
  12. └── test

The new error:

In my mysql table called product ,this table has 4 columns called id,description,name,price,i wanted to send from postman to mysql this data:

  1. {
  2. &quot;name&quot;: &quot;Case&quot;,
  3. &quot;price&quot;: 19.99
  4. }

But when i press Send, i get 401 Unauthorized in postman ,the url is http://localhost:8080/api/products.

I added a class called SecurityConfiguration thinking that if i set the username "user" and the password "password" i could go to PostMan→Authorization and add the user and password as credentials but i get the same error:

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.core.userdetails.User;
  4. import org.springframework.security.core.userdetails.UserDetails;
  5. import org.springframework.security.provisioning.InMemoryUserDetailsManager;
  6. import javax.sql.DataSource;
  7. @Configuration
  8. public class SecurityConfiguration {
  9. @Bean
  10. public InMemoryUserDetailsManager userDetailsService() {
  11. UserDetails user = User.withDefaultPasswordEncoder()
  12. .username(&quot;user&quot;)
  13. .password(&quot;password&quot;)
  14. .roles(&quot;USER&quot;)
  15. .build();
  16. return new InMemoryUserDetailsManager(user);
  17. }
  18. }

This is my ProductController class:

  1. package com.example1.project.Product;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.*;
  4. import java.util.List;
  5. @RestController
  6. @RequestMapping(&quot;/api/products&quot;)
  7. public class ProductController {
  8. private final ProductService productService;
  9. @Autowired
  10. public ProductController(ProductService productService) {
  11. this.productService = productService;
  12. }
  13. @GetMapping
  14. public List&lt;Product&gt; getAllProducts() {
  15. return productService.getAllProducts();
  16. }
  17. @GetMapping(&quot;/{id}&quot;)
  18. public Product getProductById(@PathVariable Long id) {
  19. return productService.getProductById(id);
  20. }
  21. @GetMapping(&quot;/search&quot;)
  22. public List&lt;Product&gt; searchProducts(@RequestParam String keyword) {
  23. return productService.searchProducts(keyword);
  24. }
  25. @PostMapping
  26. public Product addProduct(@RequestBody Product product) {
  27. return productService.saveProduct(product);
  28. }
  29. @PutMapping(&quot;/{id}&quot;)
  30. public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
  31. product.setId(id);
  32. return productService.saveProduct(product);
  33. }
  34. @DeleteMapping(&quot;/{id}&quot;)
  35. public void deleteProduct(@PathVariable Long id) {
  36. productService.deleteProduct(id);
  37. }
  38. }

When i start my application i get this in the console:

  1. 2023-08-01T18:05:24.940+03:00 INFO 13520 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet &#39;dispatcherServlet&#39;
  2. 2023-08-01T18:05:24.941+03:00 INFO 13520 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet &#39;dispatcherServlet&#39;
  3. 2023-08-01T18:05:24.943+03:00 INFO 13520 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
  4. 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&#181;s900ns).

答案1

得分: 0

在你的安全配置类中,你还需要一个允许 httpBasic 认证的 SecurityFilterChain bean,这就是你收到 401 未授权错误的原因,我认为我有帮助。

只需查看文档Configuration中的HttpSecurity模块。

英文:

In your Security Configuration class you also need a bean of SecurityFilterChain that permits httpBasic authentication, its the reason why you get 401 unauthorized, think i was helpful

Just have a look at documentation
Configuration
at HttpSecurity module

huangapple
  • 本文由 发表于 2023年7月31日 23:06:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定