chore(hw-03): sync user-service code from hw-02
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
.PHONY: up down build run
|
||||
|
||||
up:
|
||||
docker compose up -d
|
||||
|
||||
down:
|
||||
docker compose down
|
||||
|
||||
build:
|
||||
mvn clean package
|
||||
|
||||
run:
|
||||
mvn exec:java
|
||||
@@ -0,0 +1,16 @@
|
||||
# User Service
|
||||
|
||||
## Описание
|
||||
|
||||
Консольное Java-приложение для CRUD-операций над сущностью `User` с использованием Hibernate и PostgreSQL без Spring.
|
||||
|
||||
PostgreSQL запускается в Docker через Docker Compose.
|
||||
|
||||
## Команды Makefile
|
||||
|
||||
| Команда | Описание |
|
||||
| ------------ | ---------------------- |
|
||||
| `make up` | Запустить PostgreSQL. |
|
||||
| `make down` | Остановить PostgreSQL. |
|
||||
| `make build` | Собрать Maven-проект. |
|
||||
| `make run` | Запустить приложение. |
|
||||
@@ -0,0 +1,15 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
container_name: user-service-postgres
|
||||
environment:
|
||||
POSTGRES_DB: user_service
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>user-service</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<name>user-service</name>
|
||||
<!-- FIXME change it to the project's website -->
|
||||
<url>http://www.example.com</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.release>17</maven.compiler.release>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>5.11.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Optionally: parameterized tests support -->
|
||||
|
||||
<!-- JUnit -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Hibernate ORM -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>7.4.10.Final</version>
|
||||
</dependency>
|
||||
|
||||
<!-- PostgreSQL JDBC Driver -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.8</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to
|
||||
parent pom) -->
|
||||
<plugins>
|
||||
<!-- clean lifecycle, see
|
||||
https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
|
||||
<plugin>
|
||||
<artifactId>maven-clean-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
<!-- default lifecycle, jar packaging: see
|
||||
https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.3.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
</plugin>
|
||||
<!-- site lifecycle, see
|
||||
https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
|
||||
<plugin>
|
||||
<artifactId>maven-site-plugin</artifactId>
|
||||
<version>3.12.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-project-info-reports-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<configuration>
|
||||
<mainClass>com.example.Main</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.example;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
UserDao userDao = new UserDao();
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
printMenu();
|
||||
|
||||
String choice = scanner.nextLine();
|
||||
|
||||
clearConsole();
|
||||
|
||||
try {
|
||||
switch (choice) {
|
||||
case "1" -> createUser(userDao, scanner);
|
||||
case "2" -> findUser(userDao, scanner);
|
||||
case "3" -> updateUser(userDao, scanner);
|
||||
case "4" -> deleteUser(userDao, scanner);
|
||||
case "0" -> {
|
||||
return;
|
||||
}
|
||||
default -> System.out.println("Неизвестная команда.");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
System.out.println("Ошибка: введите корректное число.");
|
||||
} catch (RuntimeException e) {
|
||||
System.out.println("Ошибка при работе с базой данных.");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
scanner.close();
|
||||
userDao.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static void printMenu() {
|
||||
System.out.println("\n1. Создать пользователя");
|
||||
System.out.println("2. Найти пользователя");
|
||||
System.out.println("3. Обновить пользователя");
|
||||
System.out.println("4. Удалить пользователя");
|
||||
System.out.println("0. Выход");
|
||||
System.out.print("Выберите действие: ");
|
||||
}
|
||||
|
||||
private static void createUser(UserDao userDao, Scanner scanner) {
|
||||
User user = new User();
|
||||
|
||||
System.out.print("Имя: ");
|
||||
user.setName(scanner.nextLine());
|
||||
|
||||
System.out.print("Email: ");
|
||||
user.setEmail(scanner.nextLine());
|
||||
|
||||
System.out.print("Возраст: ");
|
||||
user.setAge(Integer.parseInt(scanner.nextLine()));
|
||||
|
||||
userDao.create(user);
|
||||
|
||||
System.out.println("Пользователь создан: " + user);
|
||||
}
|
||||
|
||||
private static void findUser(UserDao userDao, Scanner scanner) {
|
||||
System.out.print("ID пользователя: ");
|
||||
Long id = Long.parseLong(scanner.nextLine());
|
||||
|
||||
User user = userDao.findById(id);
|
||||
|
||||
if (user != null) {
|
||||
System.out.println(user);
|
||||
} else {
|
||||
System.out.println("Пользователь не найден.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void updateUser(UserDao userDao, Scanner scanner) {
|
||||
System.out.print("ID пользователя: ");
|
||||
Long id = Long.parseLong(scanner.nextLine());
|
||||
|
||||
User user = userDao.findById(id);
|
||||
|
||||
if (user == null) {
|
||||
System.out.println("Пользователь не найден.");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.print("Новое имя: ");
|
||||
user.setName(scanner.nextLine());
|
||||
|
||||
System.out.print("Новый email: ");
|
||||
user.setEmail(scanner.nextLine());
|
||||
|
||||
System.out.print("Новый возраст: ");
|
||||
user.setAge(Integer.parseInt(scanner.nextLine()));
|
||||
|
||||
userDao.update(user);
|
||||
|
||||
System.out.println("Пользователь обновлён.");
|
||||
}
|
||||
|
||||
private static void deleteUser(UserDao userDao, Scanner scanner) {
|
||||
System.out.print("ID пользователя: ");
|
||||
Long id = Long.parseLong(scanner.nextLine());
|
||||
|
||||
userDao.deleteById(id);
|
||||
|
||||
System.out.println("Пользователь удалён.");
|
||||
}
|
||||
|
||||
private static void clearConsole() {
|
||||
System.out.print("\033[H\033[2J");
|
||||
System.out.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.example;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 255)
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer age;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
protected User() {}
|
||||
|
||||
public User(String name, String email, Integer age) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{"
|
||||
+ "id="
|
||||
+ id
|
||||
+ ", name='"
|
||||
+ name
|
||||
+ '\''
|
||||
+ ", email='"
|
||||
+ email
|
||||
+ '\''
|
||||
+ ", age="
|
||||
+ age
|
||||
+ ", createdAt="
|
||||
+ createdAt
|
||||
+ '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.example;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
|
||||
public class UserDao {
|
||||
|
||||
private final SessionFactory sessionFactory;
|
||||
|
||||
public UserDao() {
|
||||
sessionFactory =
|
||||
new Configuration().configure().addAnnotatedClass(User.class).buildSessionFactory();
|
||||
}
|
||||
|
||||
public User create(User user) {
|
||||
Transaction transaction = null;
|
||||
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
transaction = session.beginTransaction();
|
||||
|
||||
session.persist(user);
|
||||
|
||||
transaction.commit();
|
||||
|
||||
return user;
|
||||
} catch (HibernateException e) {
|
||||
handleException(transaction, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public User findById(Long id) {
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
return session.find(User.class, id);
|
||||
} catch (HibernateException e) {
|
||||
handleException(null, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public User update(User user) {
|
||||
Transaction transaction = null;
|
||||
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
transaction = session.beginTransaction();
|
||||
|
||||
User updatedUser = session.merge(user);
|
||||
|
||||
transaction.commit();
|
||||
|
||||
return updatedUser;
|
||||
} catch (HibernateException e) {
|
||||
handleException(transaction, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteById(Long id) {
|
||||
Transaction transaction = null;
|
||||
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
transaction = session.beginTransaction();
|
||||
|
||||
User user = session.find(User.class, id);
|
||||
|
||||
if (user != null) {
|
||||
session.remove(user);
|
||||
}
|
||||
|
||||
transaction.commit();
|
||||
} catch (HibernateException e) {
|
||||
handleException(transaction, e);
|
||||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
|
||||
private void handleException(Transaction transaction, HibernateException e) {
|
||||
if (transaction != null) {
|
||||
try {
|
||||
transaction.rollback();
|
||||
} catch (HibernateException rollbackException) {
|
||||
System.err.println("Ошибка при откате транзакции.");
|
||||
}
|
||||
}
|
||||
|
||||
System.err.println("Ошибка при работе с Hibernate: " + e.getMessage());
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
|
||||
<property name="hibernate.connection.driver_class"> org.postgresql.Driver </property>
|
||||
|
||||
<property name="hibernate.connection.url"> jdbc:postgresql://localhost:5432/user_service </property>
|
||||
|
||||
<property name="hibernate.connection.username"> postgres </property>
|
||||
|
||||
<property name="hibernate.connection.password"> postgres </property>
|
||||
|
||||
<property name="hibernate.dialect"> org.hibernate.dialect.PostgreSQLDialect </property>
|
||||
|
||||
<property name="hibernate.show_sql"> true </property>
|
||||
|
||||
<property name="hibernate.format_sql"> true </property>
|
||||
|
||||
<property name="hibernate.hbm2ddl.auto"> update </property>
|
||||
|
||||
<!-- SQL logging -->
|
||||
|
||||
<property name="hibernate.show_sql">true</property>
|
||||
|
||||
<property name="hibernate.format_sql">true</property>
|
||||
|
||||
<property name="hibernate.highlight_sql">true</property>
|
||||
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
||||
Reference in New Issue
Block a user