启动程序时,在类路径资源中定义名称为 'entityManagerFactory' 的 bean 创建时出错

Posted

技术标签:

【中文标题】启动程序时,在类路径资源中定义名称为 \'entityManagerFactory\' 的 bean 创建时出错【英文标题】:When starting the program, getting Error creating bean with name 'entityManagerFactory' defined in class path resource启动程序时,在类路径资源中定义名称为 'entityManagerFactory' 的 bean 创建时出错 【发布时间】:2021-07-27 15:10:19 【问题描述】:

出现此错误,我在网站上阅读以修复它我需要添加各种依赖项。我已经添加了我可以添加的所有内容,它并没有消失。请告诉我有什么问题。

我的实现

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
// postgresql
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.19'

implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.16'
implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
implementation group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.4.30.Final'

//lombok
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'

testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'

// spring-security-taglibs
implementation group: 'org.springframework.security', name: 'spring-security-taglibs', version: '5.4.2'

// javax.servlet
compileOnly group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'

类用户

import lombok.Data;
import org.springframework.data.annotation.Id;

import javax.persistence.*;
import java.util.Set;

@Data
@Entity
public class User 
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String username;

@Column
private String password;

@Transient
@Column
private String passwordConfirm;

@Column
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles;

类角色

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.security.core.GrantedAuthority;

import javax.persistence.*;
import java.util.Set;

@Data
@Entity
@Table(name = "t_role")
public class Role implements GrantedAuthority 

@Id
@Column
private Long id;
@Column
private String name;
@Transient
@ManyToMany(mappedBy = "roles")
private Set<User> users;

public Role(Long id) 
    this.id = id;


public Role(Long id, String name) 
    this.id = id;
    this.name = name;


@Override
public String getAuthority() 
    return getName();


类 WebSecurityConfig

public class WebSecurityConfig extends WebSecurityConfigurerAdapter 
@Autowired
UserService userService;

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() 
    return new BCryptPasswordEncoder();


@Override
protected void configure(HttpSecurity httpSecurity) throws Exception 
    httpSecurity
            .csrf()
            .disable()
            .authorizeRequests()
            //Доступ только для не зарегистрированных пользователей
            .antMatchers("/registration").not().fullyAuthenticated()
            //Доступ только для пользователей с ролью Администратор
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/news").hasRole("USER")
            //Доступ разрешен всем пользователей
            .antMatchers("/", "/resources/**").permitAll()
            //Все остальные страницы требуют аутентификации
            .anyRequest().authenticated()
            .and()
            //Настройка для входа в систему
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .logoutSuccessUrl("/");


@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
    auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder());
 

日志

Error starting ApplicationContext. To display the conditions report re-run 
your application with 'debug' enabled.
2021-05-05 12:32:55.159 ERROR 11924 --- [           main] 
o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean 
 with name 'entityManagerFactory' defined in class path resource 

Invocation of init method failed; nested exception is 
org.hibernate.AnnotationException: No identifier specified for entity: 
com.project.project.model.Role
at 
at 

... 17 common frames omitted
Process finished with exit code 1

Application.properties

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://$MYSQL_HOST:localhost:3306/main_bd
spring.datasource.username=mysql
spring.datasource.password=mysql

spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

类用户服务

@Service
public class UserService implements UserDetailsService 

@PersistenceContext
private EntityManager em;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;


@Override
public UserDetails loadUserByUsername(String username) throws 
UsernameNotFoundException 
    User user = userRepository.findByUsername(username);
    if (user == null) 
        throw new UsernameNotFoundException("Пользователь не найден");
    
    return (UserDetails) user; // ПРОВЕРИТЬ!


public User findUserById(Long userId) 
    Optional<User> userFromDb = userRepository.findById(userId);
    return userFromDb.orElse(new User());


public List<User> allUsers() 
    return userRepository.findAll();


public boolean saveUser(User user) 
    User userFromDB = userRepository.findByUsername(user.getUsername());

    if (userFromDB != null) 
        return false;
    

    user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userRepository.save(user);
    return true;


public boolean deleteUser(Long userId) 
    if (userRepository.findById(userId).isPresent()) 
        userRepository.deleteById(userId);
        return true;
    
    return false;



我尝试了我找到的所有提示,但没有任何帮助。你能告诉我我的错误是什么吗?

【问题讨论】:

我们能看到堆栈跟踪吗? 刚刚编辑..... 您是否在应用中的任何位置使用实体管理器? 是的,在 UserService 我有 @PersistenceContext private EntityManager em;但是我还没有写出这个变量的方法的实现。 想不出它可能导致的任何问题......但是你能编辑你的问题并添加那个类吗? 【参考方案1】:

错误是org.hibernate.AnnotationException: No identifier specified for entity: com.project.project.model.Role

Hibernate 告诉您,您的实体 Role 没有关联的 id。这是因为您的实体中的@Id 注释来自org.springframework.data.annotation 包,而不是来自javax.persistence

尝试将@Id 的导入更改为javax.persistence.Id

【讨论】:

以上是关于启动程序时,在类路径资源中定义名称为 'entityManagerFactory' 的 bean 创建时出错的主要内容,如果未能解决你的问题,请参考以下文章

在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误

Spring:创建在类路径资源中定义的名称为“entityManagerFactory”的bean时出错

在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误:调用 init 方法失败

在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误

弹簧靴 |在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误

如何解决在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误?