我在com.example.daoImpl.FileDaoImpl中遇到错误字段fieldentityManagerFactory,需要找不到类型为'javax.persistence.EntityManagerFactory'的bean。
这是我的主班
@SpringBootApplication(scanBasePackages = "com")
@EnableConfigurationProperties({ FileStorageProperties.class })
@ComponentScan({ "com" })
@EntityScan("com.example.model")
@EnableJpaRepositories(basePackages="com", entityManagerFactoryRef="emf")
public class DemoApplication {
final static Logger logger = Logger.getLogger(DemoApplication.class);
public static void main(String[] args) {
logger.info("Application is Started");
new File(FileUploadController.uploadDirectory).mkdir();
SpringApplication.run(DemoApplication.class, args);
}
}
这是我的FileDaoImpl类
@Repository
public class FileDaoImpl implements FileDao{
@Autowired
EntityManagerFactory entityManagerFactory;
@Override
public void encryptKey(EncryptKeys keys) {
EntityManager em = entityManagerFactory.createEntityManager();
em.persist(keys);
}
服务等级
@Service
public class FileStorageService {
@Autowired
FileDao filedao;
public void encryptKey(EncryptKeys encryptKeys) {
filedao.encryptKey(encryptKeys);
}
此代码有什么问题。
答案 0 :(得分:0)
尝试
@PersistenceContext
private EntityManager entityManager;
以及下面的测试用例,对我有用
@Service
@Transactional
public class TestRepo {
@PersistenceContext
private EntityManager entityManager;
public void testPersist(){
User user = new User();
user.setUsername("persistTest");
user.setPassword("testPwd");
user.setRole("testRole");
user.setUserId("testId");
entityManager.persist(user);
}
}
答案 1 :(得分:0)
@EnableJpaRepositories(basePackages="com", entityManagerFactoryRef="emf")
它试图查找bean“ emf”以将其用作entityManagerFactoryRef,我不知道您在其他地方声明了此bean,但如果不这样做,请这么做
@Bean(name = "emf")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = builder
.dataSource(dataSource)
.packages("com")
.persistenceUnit("someNameForUnit")
.build();
/* HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", hbm2ddl);
properties.put("hibernate.dialect", hibernateDialog);
properties.put("hibernate.show_sql", showSql);
properties.put("hibernate.format_sql", formatSql);
em.setJpaPropertyMap(properties); */ this can set some property of jpa
return em;
}
但是我认为最好的解决方案是让spring boot像上面提到的那样完成这项工作。
答案 2 :(得分:0)
请进行以下更改,然后尝试
@SpringBootApplication(scanBasePackages = "com")
@EnableConfigurationProperties({ FileStorageProperties.class })
//@ComponentScan({ "com" }) not needed since SpringBootApplication will fulfill this
@EntityScan("com.example.model")
@EnableJpaRepositories("com") // allow spring-boot-starter-data-jpa to do the needful
public class DemoApplication {
final static Logger logger = Logger.getLogger(DemoApplication.class);
public static void main(String[] args) {
logger.info("Application is Started");
new File(FileUploadController.uploadDirectory).mkdir();
SpringApplication.run(DemoApplication.class, args);
}
}