Description:
Parameter 0 of constructor in com.pzh.code.chion.service.impl.db1.UserServiceImpl required a bean of type 'com.pzh.code.chion.repository.db1.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.pzh.code.chion.repository.db1.UserRepository' in your configuration.
Process finished with exit code 1
User.java
package com.pzh.code.chion.model.db1;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(schema = "cb41477_chion", name = "users")
@Data
public class User extends BaseEntity {
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "rub")
private Integer rub = 0;
@Column(name = "onix")
private Integer onix = 0;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
private List<Role> roles;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id", referencedColumnName = "user_id")
private Vote votes;
}
UserRepository.java
package com.pzh.code.chion.repository.db1;
import com.pzh.code.chion.model.db1.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String name);
User findByEmail(String email);
Boolean existsByUsername(String name);
//Boolean existsByEmail(String email);
}
UserServiceImpl.java
package com.pzh.code.chion.service.impl.db1;
import com.pzh.code.chion.repository.db1.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.pzh.code.chion.model.db1.Role;
import com.pzh.code.chion.model.db1.Status;
import com.pzh.code.chion.model.db1.User;
import com.pzh.code.chion.repository.db1.RoleRepository;
import com.pzh.code.chion.service.db1.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final PasswordEncoder passwordEncoder;
@Autowired
public UserServiceImpl(UserRepository userRepository, RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = new BCryptPasswordEncoder();
}
@Override
@Bean
public User register(User user) {
Role roleUser = roleRepository.findByName("ROLE_USER");
List<Role> userRoles = new ArrayList<>();
userRoles.add(roleUser);
user.setPassword("{bcrypt}" passwordEncoder.encode(user.getPassword()));
user.setRoles(userRoles);
user.setStatus(Status.ACTIVE);
User registeredUser = userRepository.save(user);
log.info("IN register - user: {} successfully registered", registeredUser);
return registeredUser;
}
@Override
@Bean
public User save(User user) {
User savedUser = userRepository.save(user);
log.info("IN save - user: {} successfully saved", savedUser);
return savedUser;
}
@Override
public List<User> getAll() {
List<User> result = userRepository.findAll();
log.info("IN getAll - {} users found", result.size());
return result;
}
@Override
public User findByUsername(String username) {
User result = userRepository.findByUsername(username);
log.info("IN findByUsername - user: {} found by username: {}", result, username);
return result;
}
@Override
public User findByEmail(String email) {
User result = userRepository.findByEmail(email);
log.info("IN findByEmail - user: {} found by email: {}", result, email);
return result;
}
@Override
public User findById(Long id) {
User result = userRepository.findById(id).orElse(null);
if (result == null) {
log.warn("IN findById - no user found by id: {}", id);
return null;
}
log.info("IN findById - user: {} found by id: {}", result);
return result;
}
@Override
public void delete(Long id) {
userRepository.deleteById(id);
log.info("IN delete - user with id: {} successfully deleted");
}
}
UserService.java
package com.pzh.code.chion.service.db1;
import com.pzh.code.chion.model.db1.User;
import java.util.List;
public interface UserService {
User register(User user);
User save(User user);
List<User> getAll();
User findByUsername(String username);
User findByEmail(String email);
User findById(Long id);
void delete(Long id);
}
SpringDataBaseConfig.java
package com.pzh.code.chion.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
@PropertySource({ "classpath:application.properties" })
@EnableJpaRepositories(
basePackages = "com.pzh.code.chion.model.db1",
entityManagerFactoryRef = "primaryEntityManager",
transactionManagerRef = "primaryTransactionManager"
)
public class SpringDataBaseConfig {
@Autowired
private Environment env;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean primaryEntityManager() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(primaryDataSource());
em.setPackagesToScan(
new String[] { "com.pzh.code.chion.model.db1" });
HibernateJpaVendorAdapter vendorAdapter
= new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Primary
@Bean
public DataSource primaryDataSource() {
DriverManagerDataSource dataSource
= new DriverManagerDataSource();
dataSource.setDriverClassName(
env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
@Primary
@Bean
public PlatformTransactionManager primaryTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
primaryEntityManager().getObject());
return transactionManager;
}
}
SpringMGDataBaseConfig.java
package com.pzh.code.chion.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
@PropertySource({ "classpath:application.properties" })
@EnableJpaRepositories(
basePackages = "com.pzh.code.chion.model.db2",
entityManagerFactoryRef = "mgEntityManager",
transactionManagerRef = "mgTransactionManager"
)
public class SpringMGDataBaseConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean mgEntityManager() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(mgDataSource());
em.setPackagesToScan(
new String[] { "com.pzh.code.chion.model.db2" });
HibernateJpaVendorAdapter vendorAdapter
= new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
public DataSource mgDataSource() {
DriverManagerDataSource dataSource
= new DriverManagerDataSource();
dataSource.setDriverClassName(
env.getProperty("spring.mg-datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.mg-datasource.url"));
dataSource.setUsername(env.getProperty("spring.mg-datasource.username"));
dataSource.setPassword(env.getProperty("spring.mg-datasource.password"));
return dataSource;
}
@Bean
public PlatformTransactionManager mgTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
mgEntityManager().getObject());
return transactionManager;
}
}
i tried to:
@Component
@Service
@Repository
etc... More than 10 posts fixing a problem like my problem
The problem appeared after I connected the second database using this link https://www.baeldung.com/spring-data-jpa-multiple-databases
CodePudding user response:
The repository is not discoverable as you are specifying another root classpath. In your @EnableJpaRepositories configuration change the base package from :
basePackages = "com.pzh.code.chion.model.db1"
to
basePackages = "com.pzh.code.chion.repository.db1"
same for the second datasource, in which you are again specifying the entity/models directory instead of the actual Repositories.