В нем я использую Spring + Hibernate для работы с базой данных MySQL и Project Lombok для работы с аннотациями сущностей User. Казалось бы, я все настроил по инструкциям в Интернете, но у меня Spring не хочет запускаться.
Пытаюсь выполнить следующий код:
Код: Выделить всё
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
ApplicationContext context = new AnnotationConfigApplicationContext("applicationContext.xml");
UserDaoHibernateImpl userService = context.getBean(UserDaoHibernateImpl.class);
userService.createUsersTable();
}
}
Консоль:
Код: Выделить всё
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'jm.task.core.jdbc.dao.UserDaoHibernateImpl' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:343)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1261)
at jm.task.core.jdbc.Application.main(Application.java:17)
Мое дерево проекта:
Код: Выделить всё
/kata_preproj_with_lombok
│ pom.xml
├── /src
│ ├── /main
│ │ ├── /java
│ │ │ ├── /jm.task.core.jdbc
│ │ │ │ ├── Application.class // this is the Main class I'm trying to run
│ │ │ │ ├── /dao
│ │ │ │ │ ├── Userdao.java
│ │ │ │ │ ├── UserDaoHibernateImpl.java
│ │ │ │ ├── /model
│ │ │ │ │ ├── User.class // entity
│ │ │ │ ├── /service // dao business logic
│ │ │ │ │ ├── UserService.class
│ │ │ │ │ ├── UserServiceImpl.class // contains UserDaoHibernateImpl methods
│ │ │ │ ├── Util // connection directory
│ │ │ │ │ ├── Util.class
│ │ ├── /resources
│ │ │ ├── database.properties // properties for connecting to the MySQL database (task requirement)
│ │ │ ├── log4j.properties // logger properties
│ │ │ ├── applicationContext.xml // Spring config with beans
├── /test
│ ├── /java
│ │ ├── UserServiceTest.java // contains all tests for project
Код: Выделить всё
@Repository
@Transactional
public class UserDaoHibernateImpl implements UserDao {
private static final Logger logger = LoggerFactory.getLogger(UserDaoHibernateImpl.class);
private final SessionFactory sessionFactory;
@Autowired
public UserDaoHibernateImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@Transactional
public void createUsersTable() {
logger.debug("Creating users table");
try {
Session session = sessionFactory.getCurrentSession();
NativeQuery query = session.createNativeQuery("CREATE TABLE IF NOT EXISTS users (" +
"id BIGINT PRIMARY KEY AUTO_INCREMENT," +
"name VARCHAR(45)," +
"lastname VARCHAR(45)," +
"age TINYINT)");
query.executeUpdate();
logger.info("Users table created successfully.");
} catch (Exception e) {
logger.error("Error creating Users table.", e);
throw new RuntimeException(e);
}
}
@Override
@Transactional
public void dropUsersTable() {
logger.debug("Start dropping users table");
try {
Session session = sessionFactory.getCurrentSession();
NativeQuery query = session.createNativeQuery("DROP TABLE IF EXISTS users");
query.executeUpdate();
logger.info("Users table dropped successfully.");
} catch (Exception e) {
logger.error("Error dropping Users table.", e);
throw new RuntimeException(e);
}
}
@Override
@Transactional
public void saveUser(String name, String lastName, byte age) {
logger.debug("Start saving User");
try {
Session session = sessionFactory.getCurrentSession();
User user = new User(null, name, lastName, age);
session.save(user);
logger.info("User saved: {}", user);
} catch (Exception e) {
logger.error("Error saving User.", e);
throw new RuntimeException(e);
}
}
@Override
@Transactional
public void removeUserById(long id) {
logger.debug("Start deleting User with id: {}", id);
try {
Session session = sessionFactory.getCurrentSession();
User user = session.get(User.class, id);
if (user != null) {
session.delete(user);
logger.info("User deleted with id: {}", id);
}
} catch (Exception e) {
logger.error("Error deleting User with id: {}", id, e);
throw new RuntimeException(e);
}
}
@Override
@Transactional(readOnly = true)
public List getAllUsers() {
logger.debug("Start retrieving all Users");
try {
Session session = sessionFactory.getCurrentSession();
List users = session.createQuery("from User", User.class).getResultList();
logger.info("All users retrieved.");
return users;
} catch (Exception e) {
logger.error("Error retrieving all users.", e);
throw new RuntimeException(e);
}
}
@Override
@Transactional
public void cleanUsersTable() {
logger.debug("Start cleaning Users table");
try {
Session session = sessionFactory.getCurrentSession();
NativeQuery query = session.createNativeQuery("TRUNCATE TABLE users");
query.executeUpdate();
logger.info("Users table cleaned successfully.");
} catch (Exception e) {
logger.error("Error cleaning Users table.", e);
throw new RuntimeException(e);
}
}
}
Код: Выделить всё
@Data // equals and hashCode; getters and setters; and more
@NoArgsConstructor // constructor without args for Reflection API that uses in Hibernate
@AllArgsConstructor // constructor with all args from fields of class
@Builder // for creating and initializing class
@Entity // this class is entity of Hibernate
@Table(name = "users") // table name of database
public class User implements Serializable {
@Serial
private static final long serialVersionUID = 42L;
@Id // primary (first) key ---- ID type needs to be Serializable
@GeneratedValue(strategy = GenerationType.IDENTITY) // auto increment ID value in table
@Column(name = "id") // column name in table (default is property name)
private Long id;
@Column(name = "name") // this name needs for great mapping
private String name;
@Column(name = "lastname")
private String lastName;
@Column(name = "age")
private Byte age;
}
Код: Выделить всё
@Service
public class UserServiceImpl implements UserService {
private final UserDaoHibernateImpl userDao;
@Autowired
public UserServiceImpl(UserDaoHibernateImpl userDao) {
this.userDao = userDao;
}
@Override
@Transactional
public void createUsersTable() throws SQLException {
userDao.createUsersTable();
}
@Override
@Transactional
public void dropUsersTable() throws SQLException {
userDao.dropUsersTable();
}
@Override
@Transactional
public void saveUser(String name, String lastName, byte age) throws SQLException {
userDao.saveUser(name, lastName, age);
}
@Override
@Transactional
public void removeUserById(long id) throws SQLException {
userDao.removeUserById(id);
}
@Override
@Transactional
public List getAllUsers() throws SQLException {
return userDao.getAllUsers();
}
@Override
@Transactional
public void cleanUsersTable() throws SQLException {
userDao.cleanUsersTable();
}
}
Код: Выделить всё
public class Util {
static ResourceBundle bundle = ResourceBundle.getBundle("database"); // database.properties
// для JDBC присоединения
public static Connection getConnection() {
// переменные хранения данных от значений обращенных ссылок
String url = bundle.getString("mysql.url");
String username = bundle.getString("mysql.username");
String password = bundle.getString("mysql.password");
// реализация подключения
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Код: Выделить всё
org.hibernate.dialect.MySQLDialect
true
update
Код: Выделить всё
"SpringApplication.run(Application.class, args);"Также в следующем коде:
Код: Выделить всё
UserDaoHibernateImpl userService = context.getBean(UserDaoHibernateImpl.class);В настройках IDEA установила конфигурацию Spring, чтобы IDEA знала, что это конфигурация.
ChatGPT не смог мне помочь с этим вопросом
Подробнее здесь: https://stackoverflow.com/questions/790 ... mysql-code
Мобильная версия