org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'filmDAOImpl': Unsatisfied dependency expressed through method 'setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in testgroup.filmography.config.HibernateConfig: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError:
ссылка на гидхаб проекта
https://github.com/maxsouldrake/Filmography
Ошибка при создания бина! Помогите
HibernateConfig.java---------------------------------
package testgroup.filmography.config;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@ComponentScan(basePackages = "testgroup.filmography")
@EnableTransactionManagement
@PropertySource(value = "classpath:db.properties")
public class HibernateConfig {
private Environment environment;
@Autowired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
return properties;
}
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("testgroup.filmography.model");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
filmServiceImpl.java------------------------------------------------------------------
package testgroup.filmography.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import testgroup.filmography.dao.FilmDAO;
import testgroup.filmography.model.Film;
import java.util.List;
@Service
public class FilmServiceImpl implements FilmService {
private FilmDAO filmDAO;
@Autowired
public void setFilmDAO(FilmDAO filmDAO) {
this.filmDAO = filmDAO;
}
@Override
@Transactional
public List<Film> allFilms(int page) {
return filmDAO.allFilms(page);
}
@Override
@Transactional
public void add(Film film) {
filmDAO.add(film);
}
@Override
@Transactional
public void delete(Film film) {
filmDAO.delete(film);
}
@Override
@Transactional
public void edit(Film film) {
filmDAO.edit(film);
}
@Override
@Transactional
public Film getById(int id) {
return filmDAO.getById(id);
}
@Override
@Transactional
public int filmsCount() {
return filmDAO.filmsCount();
}
@Override
@Transactional
public boolean checkTitle(String title) {
return filmDAO.checkTitle(title);
}
}
film.java-----------------------------------
package testgroup.filmography.model;
import javax.persistence.*;
@Entity
@Table(name = "films")
public class Film {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "title")
private String title;
@Column(name = "year")
private int year;
@Column(name = "genre")
private String genre;
@Column(name = "watched")
private boolean watched;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public boolean isWatched() {
return watched;
}
public void setWatched(boolean watched) {
this.watched = watched;
}
@Override
public String toString() {
return id + " " + title + " " + year + " " + genre + " " + watched;
}
}
filmDAO.java------------------------
package testgroup.filmography.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import testgroup.filmography.model.Film;
import java.util.List;
@Repository
public class FilmDAOImpl implements FilmDAO {
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@SuppressWarnings("unchecked")
public List<Film> allFilms(int page) {
Session session = sessionFactory.getCurrentSession();
return session.createQuery("from Film").setFirstResult(10 * (page - 1)).setMaxResults(10).list();
}
@Override
public void add(Film film) {
Session session = sessionFactory.getCurrentSession();
session.persist(film);
}
@Override
public void delete(Film film) {
Session session = sessionFactory.getCurrentSession();
session.delete(film);
}
@Override
public void edit(Film film) {
Session session = sessionFactory.getCurrentSession();
session.update(film);
}
@Override
public Film getById(int id) {
Session session = sessionFactory.getCurrentSession();
return session.get(Film.class, id);
}
@Override
public int filmsCount() {
Session session = sessionFactory.getCurrentSession();
return session.createQuery("select count(*) from Film", Number.class).getSingleResult().intValue();
}
@Override
public boolean checkTitle(String title) {
Session session = sessionFactory.getCurrentSession();
Query query;
query = session.createQuery("from Film where title = :title");
query.setParameter("title", title);
return query.list().isEmpty();
}
}
Алибек
17 уровень
spring mvc + hibernate
Решен
Комментарии (5)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Ярослав Java Developer Master
24 июля 2019, 07:08
Есть подозрение, что вы скопировали сырой конфиг, но даже не подключили зависимости. Зайдите в этот гайдик, посмотрите зависимости в Maven и сравните с вашими, может чего не хватает:
Bootstrapping Hibernate 5 with Spring
+2
Алибек
24 июля 2019, 08:59
Вам огромное спасибо, решил задачу! Благодарю!
+1
JustinianJudge в Mega City OneMaster
23 июля 2019, 11:43
В блокноте спринг дебажить удовольствие такое себе, хотя может тут зрячие сразу увидят.
Как минимум, оформляй код через форматирование тегом < code > , при чем код весь до последнего класса и буквы, но в идеале такое на гитхаб заливай и ссылку давай, хотя конечно коммитить нерабочее дело сомнительное.
Также давай скриншоты ошибок и сам внимательно читай логи и что пишут.
В поднятии контекста спринга слово не там написал и у тебя не запустится, нужно внимательно все просматривать, делать шаг за шагом фиксируя изменения, чтобы можно было вычленить что эту ошибку дает.
0
Алибек
24 июля 2019, 03:44
шаг за шагов выполнил
ошибка вышел из этих строк кода, но не пойму где тут ошибка
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("testgroup.filmography.model");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
0
Алибек
24 июля 2019, 03:45
ссылка на гидхаб
https://github.com/maxsouldrake/Filmography
0