feat: change dao to use databse

This commit is contained in:
Sergey Krylov 2026-03-03 05:21:08 +03:00
parent 2771cb354e
commit ba4dbe61db
4 changed files with 218 additions and 55 deletions

BIN
lib/postgresql-42.7.10.jar Normal file

Binary file not shown.

0
media/profiles/4 Normal file
View File

View File

@ -1,92 +1,257 @@
package ru.charm.back.dao;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import ru.charm.back.model.Gender;
import ru.charm.back.model.Profile;
import ru.charm.back.model.Role;
import ru.charm.back.model.Status;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.sql.*;
import java.sql.Date;
import java.util.*;
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ProfileDao {
private static final ProfileDao INSTANCE = new ProfileDao();
public static final String URL = "jdbc:postgresql://localhost:5434/charm_repository";
public static final String USER = "postgres";
public static final String PASSWORD = "123456";
private final AtomicLong idStorage;
private final ConcurrentHashMap<Long, Profile> storage;
private ProfileDao() {
this.storage = new ConcurrentHashMap<>();
Profile profile = new Profile();
profile.setId(1L);
profile.setEmail("ivanov@mail.ru");
profile.setPassword("123");
profile.setName("Ivan");
profile.setSurname("Ivanov");
profile.setBirthDate(LocalDate.parse("2001-12-03"));
profile.setAbout("I am QA");
profile.setGender(Gender.MALE);
profile.setStatus(Status.ACTIVE);
profile.setRole(Role.ADMIN);
this.storage.put(1L, profile);
Profile profile1 = new Profile();
profile1.setId(2L);
profile1.setEmail("sidorova@mail.ru");
profile1.setPassword("456");
profile1.setName("Elena");
profile1.setSurname("Sidorova");
profile1.setBirthDate(LocalDate.parse("1999-09-01"));
profile1.setAbout("I am Java Dev");
profile1.setGender(Gender.FEMALE);
profile1.setStatus(Status.INACTIVE);
profile1.setRole(Role.USER);
this.storage.put(2L, profile1);
this.idStorage = new AtomicLong(3L);
}
@SneakyThrows
public static ProfileDao getInstance() {
Class.forName("org.postgresql.Driver");
return INSTANCE;
}
public Profile save(Profile profile) {
profile.setId(idStorage.getAndIncrement());
storage.put(profile.getId(), profile);
return profile;
try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
) {
String sql = "INSERT INTO profile(email, password) VALUES ('%s', '%s')".formatted(profile.getEmail(), profile.getPassword());
int insertCount = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet res = statement.getGeneratedKeys();
if (res.next()) {
profile.setId(res.getLong("id"));
}
return profile;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Optional<Profile> findById(Long id) {
if (id == null) return Optional.empty();
return Optional.ofNullable(storage.get(id));
try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
) {
String sql = "SELECT * FROM profile WHERE id = %s".formatted(id);
ResultSet res = statement.executeQuery(sql);
Profile profile = null;
if (res.next()) {
profile = mapToProfile(res);
}
return Optional.ofNullable(profile);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Profile> findAll() {
return new ArrayList<>(storage.values());
try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
) {
String sql = "SELECT * FROM profile" ;
ResultSet res = statement.executeQuery(sql);
List<Profile> profiles = new ArrayList<>();
while (res.next()) {
profiles.add(mapToProfile(res));
}
return profiles;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Optional<Profile> findByEmailAndPassword(String email, String password) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement()) {
//language=POSTGRES-PSQL
String sql = "SELECT * FROM profile WHERE email = '%s' AND password = '%s'";
ResultSet rs = stmt.executeQuery(String.format(sql, email, password));
Profile profile = null;
if (rs.next()) {
profile = mapToProfile(rs);
}
return Optional.ofNullable(profile);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void update(Profile profile) {
Long id = profile.getId();
if (id == null) return;
storage.put(id, profile);
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement()) {
List<Object> args = new ArrayList<>();
StringBuilder queryBuilder = new StringBuilder("UPDATE profile SET email = '%s', password = '%s'");
args.add(profile.getEmail());
args.add(profile.getPassword());
if (profile.getName() != null) {
queryBuilder.append(", name = '%s'");
args.add(profile.getName());
}
if (profile.getSurname() != null) {
queryBuilder.append(", surname = '%s'");
args.add(profile.getSurname());
}
if (profile.getBirthDate() != null) {
queryBuilder.append(", birth_date = '%s'");
args.add(Date.valueOf(profile.getBirthDate()));
}
if (profile.getAbout() != null) {
queryBuilder.append(", about = '%s'");
args.add(profile.getAbout());
}
if (profile.getGender() != null) {
queryBuilder.append(", gender = '%s'");
args.add(profile.getGender());
}
if (profile.getStatus() != null) {
queryBuilder.append(", status = '%s'");
args.add(profile.getStatus());
}
if (profile.getPhoto() != null) {
queryBuilder.append(", photo = '%s'");
args.add(profile.getPhoto());
}
queryBuilder.append(" WHERE id = %s");
args.add(profile.getId());
String sql = queryBuilder.toString().formatted(args.toArray());
log.debug("Final update sql: {}", sql);
int updateCount = stmt.executeUpdate(sql);
log.debug("Update count: {}", updateCount);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public boolean delete(Long id) {
if (id == null) return false;
return storage.remove(id) != null;
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement()) {
//language=POSTGRES-PSQL
String sql = "DELETE FROM profile WHERE id = %s".formatted(id);
int deleteCount = stmt.executeUpdate(sql);
log.debug("Delete count: {}", deleteCount);
return deleteCount > 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Set<String> getAllEmails() {
return storage.values().stream().map(Profile::getEmail).collect(Collectors.toSet());
try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
) {
String sql = "SELECT email FROM profile" ;
ResultSet res = statement.executeQuery(sql);
ArrayList<String> emails = new ArrayList<>();
while (res.next()) {
emails.add(res.getString("email"));
}
return new HashSet<>(emails);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Optional<Profile> findByEmail(String email) {
if (email == null) return Optional.empty();
try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
) {
String sql = "SELECT * FROM profile WHERE email = '%s'".formatted(email);
ResultSet res = statement.executeQuery(sql);
Profile profile = null;
if (res.next()) {
profile = mapToProfile(res);
}
return Optional.ofNullable(profile);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Boolean existsByEmail(String email) {
try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement();
) {
String sql = "SELECT * FROM profile WHERE email = '%s'".formatted(email);
ResultSet res = statement.executeQuery(sql);
return res.next();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private Profile mapToProfile(ResultSet rs) throws SQLException {
Profile result = new Profile();
result.setId(rs.getLong("id"));
result.setEmail(rs.getString("email"));
result.setPassword(rs.getString("password"));
result.setName(rs.getString("name"));
result.setSurname(rs.getString("surname"));
Date birthDate = rs.getDate("birth_date");
if (birthDate != null) {
result.setBirthDate(birthDate.toLocalDate());
}
result.setAbout(rs.getString("about"));
String gender = rs.getString("gender");
if (gender != null) {
result.setGender(Gender.valueOf(gender));
}
result.setPhoto(rs.getString("photo"));
String status = rs.getString("status");
if (status != null) {
result.setStatus(Status.valueOf(status));
}
String role = rs.getString("role");
if (role != null) {
result.setRole(Role.valueOf(role));
}
return result;
return storage.values().stream().filter(profile -> profile.getEmail().equals(email)).findFirst();
}
}

View File

@ -25,8 +25,6 @@ public class RegistrationDtoToProfileMapper implements Mapper<RegistrationDto, P
public Profile map(RegistrationDto dto, Profile profile) {
profile.setEmail(dto.getEmail());
profile.setPassword(dto.getPassword());
profile.setStatus(Status.INACTIVE);
profile.setRole(Role.USER);
return profile;
}
}