Deniss Zadorozhniy
Deniss Zadorozhniy

Reputation: 45

When starting the program, getting Error creating bean with name 'entityManagerFactory' defined in class path resource

This error appears, I read on the sites to fix it I need to add various dependencies. I have already added everything I could, it has not disappeared. Tell me what is wrong please.

my implementation

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'

Class User

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;
}

Class Role

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();

}

Class 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());
 }
}

Logs

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

Class UserService

@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;
}

}

I tried all the tips I found and nothing helped. Can you please tell me what is my mistake here?

Upvotes: 0

Views: 259

Answers (1)

Marcus Hert da Coregio
Marcus Hert da Coregio

Reputation: 6308

the error is org.hibernate.AnnotationException: No identifier specified for entity: com.project.project.model.Role.

Hibernate is telling you that your entity Role has not an id associated. This is because you @Id annotation in your entity is from org.springframework.data.annotation package, and not from javax.persistence.

Try changing the import for @Id to javax.persistence.Id

Upvotes: 1

Related Questions