Как правильно описать конфигурационные классы Hibernate и Spring в проекте

0
07 апр 2019 13:18
Доброго времени, ребята!

Пытаюсь использовать Hibernate в Spring. Проблема с правильным описанием конфигурационных классов для Hibernate, ну и возможно для Spring.
При создании сессии выдаёт исключение, что не может создать объект сессии из-за невозможности открыть JDBS-соединение. В инете причины решения не нашёл (.
Может кто-нибудь поможет разобраться за умеренную плату, курсач горит (

Quote:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'geographKoordsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'GeographKoordsDao': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)


@Configuration
@ComponentScan(basePackages = { "config","controller","dao","entity","service"})
@EnableWebMvc
@EnableTransactionManagement
//@EnableJpaRepositories("") //включаем возможность использования JPARepository и говорим, где их искать
public class HibernateConfig {
    private static Logger logger=LoggerFactory.getLogger(HibernateConfig.class);
 
    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = null;
        try {
            dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/dbfastwater?useSSL=false");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
        } catch (Exception e) {
            logger.error("MysqlDataSource bean cannot be created!", e);
        }
        return dataSource;
    }
 
    private Properties hibernateProperties() {
        Properties hibernateProp = new Properties();
        hibernateProp.put("hibernate.dialect", "org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect");
        hibernateProp.put("connection.driver_class", "com.mysql.jdbc.Driver");
        hibernateProp.put("hibernate.format_sql", true);
        hibernateProp.put("hibernate.use_sql_comments", true);
        hibernateProp.put("hibernate.show_sql", true);
        hibernateProp.put("hibernate.max_fetch_depth", 3);
        hibernateProp.put("hibernate.jdbc.batch_size", 10);
        hibernateProp.put("hibernate.jdbc.fetch_size", 50);
        hibernateProp.put("hibernate.hbm2ddl.auto","update");
        return hibernateProp;
    }
 
    @Bean
    public SessionFactory sessionFactory() throws IOException {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(getDataSource());
        sessionFactoryBean.setPackagesToScan("entity","dao","service");
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        sessionFactoryBean.afterPropertiesSet();
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        return sessionFactoryBean.getObject();
    }
 
    @Bean
    public PlatformTransactionManager transactionManager() throws IOException {
        HibernateTransactionManager transactionManager=new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory());
        return transactionManager;
    }
}

package config;

@Configuration
@ComponentScan(basePackages = { "config","controller","dao","entity","service"})
public class SpringConfig {

}


package config;

public class MainWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(final ServletContext servletContext) throws ServletException {
        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext context =
                new AnnotationConfigWebApplicationContext();

        context.register(HibernateConfig.class, WebConfig.class,SpringConfig.class);
        context.setServletContext(servletContext);

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic dispather =
                servletContext.addServlet("dispather", servlet);
        dispather.setLoadOnStartup(1);
        dispather.addMapping("/");
    }
}

@Service
@SuppressWarnings("unchecked")
@Transactional
@Repository("GeographKoordsDao")
public class GeographKoordsService implements GeographKoordsDao {

    private static final Log logger = LogFactory.getLog(GeographKoordsService.class);
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional(readOnly = true)
    public List<Geographkoords> getAll() {
     return sessionFactory.getCurrentSession().createQuery("select e FROM Geographkoords e",Geographkoords.class).list();
    }

    @Resource(name = "sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

@Controller
@RequestMapping("/water")
public class UserController {

    @Autowired
    private GeographKoordsDao geographKoordsService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)//Mapping web context, на который будет реагировать метод
    public @ResponseBody List<Geographkoords> getAllUsers() {
        List<Geographkoords> listGejgraphKoords=geographKoordsService.getAll();
        return listGejgraphKoords;
    }
}




Ответов: 1

0
15 апр 2019 02:29
Думаю, проблема в этом:
  @Autowired
    private GeographKoordsDao geographKoordsService;

и
@Repository("GeographKoordsDao")


Spring не может найти geographKoordsService, потому что он у вас на самом деле GeographKoordsDao
Модераторы: Нет
Сейчас эту тему просматривают: Нет