spring 创建在应用程序上声明的@EnableJpaRepositories中定义的名为“userRepository”的Bean时出错:不是托管类型:class

2wnc66cl  于 2023-11-16  发布在  Spring
关注(0)|答案(2)|浏览(126)

主类

package com.TVMovie.ReviewSystem;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories(basePackages = "com.TVMovie.ReviewSystem.repository")
@SpringBootApplication
@EntityScan("com.TVMovie.ReviewSystem.entity")
public class Application {

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

}

字符串

实体类

package com.TVMovie.ReviewSystem.entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import lombok.Data;

@Data
@Table
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String email;
    private String firstName;
    private String lastName;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Rating> ratings = new HashSet<>();

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Review> reviews = new HashSet<>();

    public User() {

    }

    public User(Long id, String username, String password, String email, String firstName, String lastName,
            Set<Rating> ratings, Set<Review> reviews) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.ratings = ratings;
        this.reviews = reviews;
    }

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Set<Rating> getRatings() {
        return ratings;
    }

    public void setRatings(Set<Rating> ratings) {
        this.ratings = ratings;
    }

    public Set<Review> getReviews() {
        return reviews;
    }

    public void setReviews(Set<Review> reviews) {
        this.reviews = reviews;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email
                + ", firstName=" + firstName + ", lastName=" + lastName + ", ratings=" + ratings + ", reviews="
                + reviews + "]";
    }

}

仓库接口

package com.TVMovie.ReviewSystem.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.TVMovie.ReviewSystem.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User save(User user);

    List<User> findAll();

    long count();

    void delete(User user);

    User findByUsername(String username);

    User findByEmail(String email);

    List<User> findByFirstName(String firstName);

    List<User> findByLastName(String lastName);

    @Query("SELECT u FROM User u LEFT JOIN FETCH u.ratings")
    List<User> findAllWithRatings();

    @Query(value = "SELECT * FROM user WHERE username LIKE %:search%", nativeQuery = true)
    List<User> searchUsersByUsername(@Param("search") String search);

    User findByUsernameAndPassword(String username, String password);

}

服务类

package com.TVMovie.ReviewSystem.service;

import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;

import com.TVMovie.ReviewSystem.entity.Rating;
import com.TVMovie.ReviewSystem.entity.Review;
import com.TVMovie.ReviewSystem.entity.User;

public interface UserService {

    // Create (Save) a User
    User save(User user);

    // Retrieve (Read) All Users
    List<User> findAll();

    Optional<User> findById(Long id);

    // Count the Number of Users
    long count();

    // Delete (Remove) a User
    void delete(User user);

    // Retrieve a User by Username
    User findByUsername(String username);

    // Retrieve a User by Email
    User findByEmail(String email);

    // Retrieve Users by First Name
    List<User> findByFirstName(String firstName);

    // Retrieve Users by Last Name
    List<User> findByLastName(String lastName);

    // Retrieve All Users with Ratings
    List<User> findAllWithRatings();

    // Search Users by Username
    List<User> searchUsersByUsername(String search);

    // Authenticate a User by Username and Password
    Optional<User> authenticateUser(String username, String password);

    // Add a Rating to a User
    Rating addRatingToUser(User user, Rating rating);

    // Remove a Rating from a User
    void removeRatingFromUser(User user, Rating rating);

    // Add a Review to a User
    Review addReviewToUser(User user, Review review);

    // Remove a Review from a User
    void removeReviewFromUser(User user, Review review);

}
package com.TVMovie.ReviewSystem.service;

import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;

import com.TVMovie.ReviewSystem.entity.Rating;
import com.TVMovie.ReviewSystem.entity.Review;
import com.TVMovie.ReviewSystem.entity.User;

@Service
public class UserServiceImpl implements UserService {

    @Override
    public User save(User user) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> findAll() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Optional<User> findById(Long id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long count() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void delete(User user) {
        // TODO Auto-generated method stub

    }

    @Override
    public User findByUsername(String username) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public User findByEmail(String email) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> findByFirstName(String firstName) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> findByLastName(String lastName) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> findAllWithRatings() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> searchUsersByUsername(String search) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Optional<User> authenticateUser(String username, String password) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Rating addRatingToUser(User user, Rating rating) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void removeRatingFromUser(User user, Rating rating) {
        // TODO Auto-generated method stub

    }

    @Override
    public Review addReviewToUser(User user, Review review) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void removeReviewFromUser(User user, Review review) {
        // TODO Auto-generated method stub

    }

}

控制器类

package com.TVMovie.ReviewSystem.controller;

import com.TVMovie.ReviewSystem.entity.Rating;
import com.TVMovie.ReviewSystem.entity.Review;
import com.TVMovie.ReviewSystem.entity.User;
import com.TVMovie.ReviewSystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;

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

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        Optional<User> user = userService.findById(id);
        user.ifPresent(u -> userService.delete(u));
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.save(user);
    }

    @GetMapping("/{id}/ratings")
    public List<Rating> getUserRatings(@PathVariable Long id) {
        Optional<User> user = userService.findById(id);
        return user.map(u -> new ArrayList<>(u.getRatings())).orElse(null);
    }

    @GetMapping("/{id}/reviews")
    public List<Review> getUserReviews(@PathVariable Long id) {
        Optional<User> user = userService.findById(id);
        return user.map(u -> new ArrayList<>(u.getReviews())).orElse(null);
    }

}

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.TVMovie</groupId>
    <artifactId>ReviewSystem</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</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-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version> <!-- Use the appropriate version -->
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.5.7.Final</version> <!-- Use the appropriate version -->
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version> <!-- Use the latest version -->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>


即使我已经多次更正代码并创建代码,我还是得到了相同的错误。
org.springframework.beans.factory.BeanCreationException:创建在com.TVMovie.ReviewSystem.repository中定义的名为“userRepository”的bean时出错。在应用程序上声明的@EnableJpaRepositories中定义的UserRepository:不是托管类型:class com. TVMovie. ReviewSystem. entity. User。

fcy6dtqo

fcy6dtqo1#

这里的问题是混合了hibernate API的版本。spring-boot-starter-parent<version>3.1.5</version>意味着在spring-boot-starter-data-jpa中使用的hibernate的底层版本是6.2.x。它使用jakarta.x而不是javax.x
要修复它:
pom.xml中删除下一个依赖项:

<dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.0.Final</version>
        </dependency>

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

字符串
Entity User类中替换下一个导入:

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;


收件人:

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;

uqdfh47h

uqdfh47h2#

此错误是“Javax”命名空间的结果。将User实体类中的导入语句替换为“Jakarta”命名空间。阅读更多

import javax.persistence.*; //Change this

字符串

import jakarta.persistence.*;  //to this

相关问题