Skip to content

Commit ba51c6c

Browse files
Initial
1 parent 9f5fcda commit ba51c6c

File tree

16 files changed

+713
-2
lines changed

16 files changed

+713
-2
lines changed

.github/workflows/ci.yml

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
name: Main CI
2+
3+
on:
4+
push:
5+
branches: [ main ]
6+
pull_request:
7+
branches: [ main ]
8+
9+
jobs:
10+
build:
11+
runs-on: ubuntu-latest
12+
13+
steps:
14+
- name: Checkout code
15+
uses: actions/checkout@v4
16+
17+
- name: Set up Docker Compose
18+
run: docker compose version
19+
20+
- name: Start services with Docker Compose
21+
run: docker compose up -d
22+
23+
- name: Wait for PostgreSQL
24+
run: |
25+
until docker exec $(docker ps -qf "name=db") pg_isready -U postgres; do
26+
echo "Waiting for PostgreSQL..."
27+
sleep 2
28+
done
29+
30+
- name: Set up OpenJDK 21
31+
uses: actions/setup-java@v4
32+
with:
33+
distribution: 'temurin'
34+
java-version: '21'
35+
36+
- name: Build with Maven
37+
run: mvn clean install
38+
39+
- name: Run tests
40+
run: mvn test
41+
42+
- name: Run Checkstyle
43+
run: mvn checkstyle:check

.gitignore

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,30 @@
1919
*.tar.gz
2020
*.rar
2121

22-
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
22+
# virtual machine crash logs
2323
hs_err_pid*
2424
replay_pid*
25+
26+
# IntelliJ IDEA
27+
.idea/
28+
*.iml
29+
*.iws
30+
*.ipr
31+
out/
32+
33+
# Maven
34+
target/
35+
pom.xml.tag
36+
pom.xml.releaseBackup
37+
pom.xml.versionsBackup
38+
pom.xml.next
39+
release.properties
40+
dependency-reduced-pom.xml
41+
buildNumber.properties
42+
.mvn/timing.properties
43+
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
44+
.mvn/wrapper/maven-wrapper.jar
45+
46+
# OS-specific
47+
.DS_Store
48+
Thumbs.db

README.md

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,52 @@
1-
# user-service-hibernate
1+
# User Service Hibernate
2+
3+
**User Service Hibernate** — консольное Java-приложение для управления пользователями с помощью Hibernate и PostgreSQL.
4+
Реализованы основные CRUD-операции (создание, чтение, обновление, удаление) через удобное меню.
5+
6+
---
7+
8+
## Технологии
9+
10+
- Java 22
11+
- Hibernate ORM
12+
- PostgreSQL (через Docker)
13+
- SLF4J + Logback (логирование)
14+
- JUnit 5 (тестирование)
15+
- Maven (сборка и зависимости)
16+
- Checkstyle (проверка стиля кода)
17+
18+
---
19+
20+
## Запуск проекта
21+
22+
### 1. Клонировать репозиторий
23+
24+
```sh
25+
git clone https://github.com/ТВОЙ_ЛОГИН/user-service-hibernate.git
26+
cd user-service-hibernate
27+
```
28+
### 2 Запустить базу данных PostgreSQL
29+
```sh
30+
docker compose up -d
31+
```
32+
### 3. Собрать проект и проверить стиль кода
33+
34+
```sh
35+
mvn clean install
36+
mvn checkstyle:check
37+
```
38+
### 4. Запустить тесты
39+
40+
```sh
41+
mvn test
42+
```
43+
### 5. Запустить приложение
44+
45+
46+
```sh
47+
mvn exec:java -Dexec.mainClass="myuserservice.App"
48+
```
49+
50+
### 6. Пример работы приложения
51+
![img_1.png](readme-resources/img_1.png)
52+
![img_2.png](readme-resources/img_2.png)

docker-compose.yml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
version: '3.8'
2+
services:
3+
db:
4+
image: postgres:14.1-alpine
5+
restart: always
6+
environment:
7+
- POSTGRES_USER=postgres
8+
- POSTGRES_PASSWORD=postgres
9+
ports:
10+
- '5432:5432'
11+
volumes:
12+
- db:/var/lib/postgresql/data
13+
volumes:
14+
db:
15+
driver: local

pom.xml

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4+
https://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>myuserservice</groupId>
8+
<artifactId>user-service-hibernate</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<properties>
12+
<maven.compiler.source>21</maven.compiler.source>
13+
<maven.compiler.target>21</maven.compiler.target>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
</properties>
16+
17+
<dependencies>
18+
19+
<dependency>
20+
<groupId>org.hibernate.orm</groupId>
21+
<artifactId>hibernate-core</artifactId>
22+
<version>6.4.4.Final</version>
23+
</dependency>
24+
25+
<dependency>
26+
<groupId>org.postgresql</groupId>
27+
<artifactId>postgresql</artifactId>
28+
<version>42.7.3</version>
29+
</dependency>
30+
31+
<dependency>
32+
<groupId>org.slf4j</groupId>
33+
<artifactId>slf4j-api</artifactId>
34+
<version>2.0.13</version>
35+
</dependency>
36+
<dependency>
37+
<groupId>ch.qos.logback</groupId>
38+
<artifactId>logback-classic</artifactId>
39+
<version>1.4.14</version>
40+
</dependency>
41+
42+
<dependency>
43+
<groupId>org.junit.jupiter</groupId>
44+
<artifactId>junit-jupiter</artifactId>
45+
<version>5.10.2</version>
46+
<scope>test</scope>
47+
</dependency>
48+
</dependencies>
49+
50+
<build>
51+
<plugins>
52+
<plugin>
53+
<groupId>org.apache.maven.plugins</groupId>
54+
<artifactId>maven-checkstyle-plugin</artifactId>
55+
<version>3.3.1</version>
56+
<executions>
57+
<execution>
58+
<id>checkstyle-validation</id>
59+
<phase>verify</phase>
60+
<goals>
61+
<goal>check</goal>
62+
</goals>
63+
</execution>
64+
</executions>
65+
<configuration>
66+
<configLocation>google_checks.xml</configLocation>
67+
<encoding>UTF-8</encoding>
68+
<consoleOutput>true</consoleOutput>
69+
<failsOnError>true</failsOnError>
70+
<includeTestSourceDirectory>true</includeTestSourceDirectory>
71+
<sourceDirectories>
72+
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
73+
<sourceDirectory>${project.basedir}/src/test/java</sourceDirectory>
74+
</sourceDirectories>
75+
</configuration>
76+
</plugin>
77+
</plugins>
78+
</build>
79+
80+
<reporting>
81+
<plugins>
82+
<plugin>
83+
<groupId>org.apache.maven.plugins</groupId>
84+
<artifactId>maven-checkstyle-plugin</artifactId>
85+
<version>3.3.1</version>
86+
<configuration>
87+
<configLocation>checkstyle/checkstyle.xml</configLocation>
88+
<encoding>UTF-8</encoding>
89+
<failsOnError>true</failsOnError>
90+
</configuration>
91+
</plugin>
92+
</plugins>
93+
</reporting>
94+
</project>

readme-resources/img_1.png

23.1 KB
Loading

readme-resources/img_2.png

60.9 KB
Loading
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
package myuserservice;
2+
3+
import myuserservice.dao.UserDao;
4+
import myuserservice.dao.UserDaoImpl;
5+
import myuserservice.entity.User;
6+
import myuserservice.util.HibernateUtil;
7+
import org.hibernate.Session;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
import java.util.List;
12+
import java.util.Scanner;
13+
14+
public class App {
15+
private static final Logger log = LoggerFactory.getLogger(App.class);
16+
private static final Scanner scanner = new Scanner(System.in);
17+
private static final UserDao userDao = new UserDaoImpl();
18+
19+
public static void main(String[] args) {
20+
try {
21+
while (true) {
22+
System.out.println("""
23+
=== Меню ===
24+
1. Добавить пользователя
25+
2. Показать всех
26+
3. Найти по ID
27+
4. Обновить пользователя
28+
5. Удалить пользователя
29+
0. Выход
30+
""");
31+
32+
33+
String choice = scanner.nextLine();
34+
switch (choice) {
35+
case "1" -> createUser();
36+
case "2" -> listUsers();
37+
case "3" -> findUser();
38+
case "4" -> updateUser();
39+
case "5" -> deleteUser();
40+
case "0" -> {
41+
log.info("Выход из приложения.");
42+
return;
43+
}
44+
default -> System.out.println("Неверный ввод.");
45+
}
46+
}
47+
} finally {
48+
scanner.close();
49+
}
50+
}
51+
52+
private static void createUser() {
53+
System.out.print("Имя: ");
54+
String name = scanner.nextLine();
55+
System.out.print("Email: ");
56+
String email = scanner.nextLine();
57+
System.out.print("Возраст: ");
58+
int age = readInt("Возраст: ");
59+
60+
User user = new User();
61+
user.setName(name);
62+
user.setEmail(email);
63+
user.setAge(age);
64+
65+
userDao.save(user);
66+
log.info("Пользователь {} успешно добавлен.", user);
67+
}
68+
69+
private static void listUsers() {
70+
List<User> users = userDao.findAll();
71+
if (users.isEmpty()) {
72+
log.info("Пользователей не найдено.");
73+
} else {
74+
users.forEach(user -> log.info(user.toString()));
75+
}
76+
}
77+
78+
private static void findUser() {
79+
long id = readLong("ID: ");
80+
User user = userDao.findById(id);
81+
if (user != null) {
82+
log.info("Найден пользователь: {}", user);
83+
} else {
84+
log.warn("Пользователь с ID {} не найден.", id);
85+
}
86+
}
87+
88+
89+
private static void updateUser() {
90+
long id = readLong("ID: ");
91+
User user = userDao.findById(id);
92+
if (user == null) {
93+
log.warn("Пользователь с ID={} не найден", id);
94+
return;
95+
}
96+
97+
System.out.print("Новое имя: ");
98+
user.setName(scanner.nextLine());
99+
System.out.print("Новый email: ");
100+
user.setEmail(scanner.nextLine());
101+
System.out.print("Новый возраст: ");
102+
user.setAge(Integer.parseInt(scanner.nextLine()));
103+
104+
userDao.update(user);
105+
log.info("Пользователь обновлён: {}", user);
106+
}
107+
108+
private static void deleteUser() {
109+
long id = readLong("ID: ");
110+
userDao.delete(id);
111+
log.info("Пользователь с ID {} удалён.", id);
112+
}
113+
114+
private static int readInt(String prompt) {
115+
while (true) {
116+
System.out.print(prompt);
117+
try {
118+
return Integer.parseInt(scanner.nextLine());
119+
} catch (NumberFormatException e) {
120+
System.out.println("Введите корректное число.");
121+
log.warn("Ошибка при вводе целого числа", e);
122+
}
123+
}
124+
}
125+
126+
private static long readLong(String prompt) {
127+
while (true) {
128+
System.out.print(prompt);
129+
try {
130+
return Long.parseLong(scanner.nextLine());
131+
} catch (NumberFormatException e) {
132+
System.out.println("Введите корректный ID.");
133+
log.warn("Ошибка при вводе ID", e);
134+
}
135+
}
136+
}
137+
138+
}
139+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package myuserservice.dao;
2+
3+
import myuserservice.entity.User;
4+
import java.util.List;
5+
6+
public interface UserDao {
7+
void save(User user);
8+
User findById(Long id);
9+
List<User> findAll();
10+
void update(User user);
11+
void delete(Long id);
12+
}

0 commit comments

Comments
 (0)