Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.entities;
- import org.hibernate.annotations.GenericGenerator;
- import javax.persistence.*;
- import java.time.LocalDateTime;
- @Entity
- public class AccountEntity {
- private Long id;
- @Column(nullable = false)
- private ClientEntity client;
- private String login;
- private String password;
- private LocalDateTime created;
- public AccountEntity() {
- }
- public AccountEntity(ClientEntity client, String login, String password, LocalDateTime created) {
- this.client = client;
- this.login = login;
- this.password = password;
- this.created = created;
- }
- @Id
- @GeneratedValue(generator = "increment")
- @GenericGenerator(name = "increment", strategy = "increment")
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- @ManyToOne(fetch = FetchType.EAGER)
- public ClientEntity getClient() {
- return client;
- }
- public void setClient(ClientEntity client) {
- this.client = client;
- }
- public String getLogin() {
- return login;
- }
- public void setLogin(String login) {
- this.login = login;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public LocalDateTime getCreated() {
- return created;
- }
- public void setCreated(LocalDateTime created) {
- this.created = created;
- }
- }
- package com.example.entities;
- import org.hibernate.annotations.GenericGenerator;
- import javax.persistence.*;
- import java.util.List;
- @Entity
- public class ClientEntity {
- private Long id;
- private String name;
- private String email;
- private List<AccountEntity> accountEntities;
- public ClientEntity() {
- }
- public ClientEntity(String name, String email, List<AccountEntity> accountEntities) {
- this.name = name;
- this.email = email;
- this.accountEntities = accountEntities;
- }
- @Id
- @GeneratedValue(generator = "increment")
- @GenericGenerator(name = "increment", strategy = "increment")
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
- public List<AccountEntity> getAccountEntities() {
- return accountEntities;
- }
- public void setAccountEntities(List<AccountEntity> accountEntities) {
- this.accountEntities = accountEntities;
- }
- public void addAccount(AccountEntity accountEntity) {
- if (accountEntity != null) {
- accountEntities.add(accountEntity);
- }
- }
- public void removeAccount(Long id) {
- accountEntities.removeIf(account -> account.getId().equals(id));
- }
- }
- package com.example.services;
- import com.example.entities.AccountEntity;
- import com.example.entities.ClientEntity;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class AccountService {
- private final static Logger log = LoggerFactory.getLogger(AccountService.class.getName());
- public static void createAccount() {
- try {
- Long id = IOService.inputId();
- ClientEntity client = PersistenceService.checkIfExistsAndReturn(ClientEntity.class, id);
- AccountEntity account = IOService.createAccount(client);
- client.addAccount(account);
- PersistenceService.mergeClient(client);
- IOService.printToConsole("Account was created.");
- } catch (Exception e) {
- IOService.printToConsole("Account wasn't created.");
- log.error("Account wasn't created.", e);
- }
- }
- public static void deleteAccount() {
- try {
- Long id = IOService.inputId();
- ClientEntity client = PersistenceService.checkIfExistsAndReturn(AccountEntity.class, id).getClient();
- client.removeAccount(id);
- PersistenceService.mergeClient(client);
- IOService.printToConsole("Account with id = " + id + " was deleted.");
- } catch (Exception e) {
- IOService.printToConsole("Account wasn't deleted.");
- log.error("Account wasn't deleted.", e);
- }
- }
- public static void changeAccount() {
- try {
- Long id = IOService.inputId();
- AccountEntity account = PersistenceService.checkIfExistsAndReturn(AccountEntity.class, id);
- account = IOService.changeAccount(account);
- PersistenceService.mergeAccount(account);
- IOService.printToConsole("Account was updated.");
- } catch (Exception e) {
- IOService.printToConsole("Account wasn't changed.");
- log.error("Account wasn't changed.", e);
- }
- }
- }
- package com.example.services;
- import com.example.entities.ClientEntity;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class ClientService {
- private final static Logger log = LoggerFactory.getLogger(ClientService.class.getName());
- public static void displayAllClientsInfo() {
- try {
- IOService.displayAllClientsInfo(PersistenceService.getAllClients());
- log.info("Method ClientService.displayAllClientsInfo() was called.");
- } catch (Exception e) {
- log.error("Error in ClientService.displayAllClientsInfo()", e);
- }
- }
- public static void deleteClient() {
- try {
- Long id = IOService.inputId();
- PersistenceService.deleteClient(id);
- IOService.printToConsole("Client with id = " + id + " was deleted.");
- log.info("Client with id = " + id + " was deleted by ClientService.deleteClient().");
- } catch (Exception e) {
- IOService.printToConsole("Client wasn't found.");
- log.error("Client wasn't found.", e);
- }
- }
- public static void createClient() {
- try {
- ClientEntity client = IOService.createClient();
- PersistenceService.saveClient(client);
- IOService.printToConsole("Client created.");
- log.info("Client created. ID = " + client.getId());
- } catch (Exception e) {
- log.error("Client wasn't created.", e);
- }
- }
- }
- package com.example.services;
- import com.example.entities.AccountEntity;
- import com.example.entities.ClientEntity;
- import org.apache.commons.lang.StringUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.time.LocalDateTime;
- import java.time.format.DateTimeFormatter;
- import java.util.ArrayList;
- import java.util.List;
- public class IOService {
- private final static Logger log = LoggerFactory.getLogger(IOService.class.getName());
- private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- public static void displayAllClientsInfo(List<ClientEntity> clients) {
- if (clients.size() > 0) {
- printToConsole(StringUtils.center("Clients", 55) + StringUtils.center("Accounts", 85));
- printToConsole(StringUtils.repeat("-", 140));
- String columnsNames = String.format("%1$5s%2$25s%3$27s%4$3s%5$30s%6$25s%7$25s", "id", "e-mail", "name |",
- "id", "created", "login", "password");
- printToConsole(columnsNames);
- printToConsole(StringUtils.repeat("=", 140));
- StringBuilder clientInfo = new StringBuilder();
- for (ClientEntity client : clients) {
- clientInfo.append(String.format("%1$5d%2$25s%3$25s |", client.getId(), client.getEmail(),
- client.getName()));
- printToConsole(clientInfo);
- clientInfo.delete(0, clientInfo.length());
- List<AccountEntity> accounts = client.getAccountEntities();
- for (AccountEntity ac : accounts) {
- clientInfo.append(String.format("%1$60d%2$30s%3$25s%4$25s", ac.getId(), ac.getCreated(), ac.getLogin(),
- ac.getPassword()));
- clientInfo.setCharAt(56, '|');
- printToConsole(clientInfo);
- clientInfo.delete(0, clientInfo.length());
- }
- clientInfo.delete(0, clientInfo.length());
- printToConsole(StringUtils.repeat("-", 140));
- }
- } else {
- printToConsole("No data to display.");
- log.info("No data to display. IOService.displayAllClientsInfo()");
- }
- }
- public static Long inputId() throws IOException {
- printToConsole("Input id: ");
- return Long.parseLong(br.readLine());
- }
- public static int inputMenuItemNumber(int min, int max) throws IOException {
- int selection = 0;
- while (selection < min || selection > max) {
- printToConsole("To continue, enter the menu item number: ");
- selection = Integer.parseInt(br.readLine());
- }
- return selection;
- }
- public static ClientEntity createClient() throws IOException {
- ClientEntity client = new ClientEntity();
- printToConsole("Input client name: ");
- client.setName(br.readLine());
- printToConsole("Input client e-mail: ");
- client.setEmail(br.readLine());
- printToConsole("Input number of accounts for client: ");
- int numberOfAccounts = Integer.parseInt(br.readLine());
- List<AccountEntity> accountEntities = new ArrayList<>();
- while (numberOfAccounts-- > 0) {
- accountEntities.add(createAccount(client));
- }
- client.setAccountEntities(accountEntities);
- return client;
- }
- public static AccountEntity createAccount(ClientEntity client) throws IOException {
- printToConsole("Input login: ");
- String login = br.readLine();
- printToConsole("Input password: ");
- String password = br.readLine();
- LocalDateTime date = LocalDateTime.now();
- return new AccountEntity(client, login, password, date);
- }
- public static AccountEntity changeAccount(AccountEntity account) throws IOException {
- printToConsole("Input new login: ");
- account.setLogin(br.readLine());
- printToConsole("Input new password: ");
- account.setPassword(br.readLine());
- printToConsole("Input new date in format like this "2011-12-03T10:15:30" (ISO Local Date and Time): ");
- DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
- LocalDateTime date = LocalDateTime.parse(br.readLine(), formatter);
- account.setCreated(date);
- return account;
- }
- public static <T> void printToConsole(T message) {
- System.out.println(message);
- }
- }
- package com.example.services;
- import com.example.entities.AccountEntity;
- import com.example.entities.ClientEntity;
- import com.example.utils.HibernateUtil;
- import javassist.NotFoundException;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import javax.persistence.EntityManager;
- import java.util.List;
- public class PersistenceService {
- private final static Logger log = LoggerFactory.getLogger(PersistenceService.class.getName());
- public static List<ClientEntity> getAllClients() {
- EntityManager entityManager = HibernateUtil.getEntityManager();
- List<ClientEntity> clientEntities =
- entityManager.createQuery("SELECT c FROM ClientEntity c", ClientEntity.class).getResultList();
- entityManager.close();
- log.info("Got all client entities from DB.");
- return clientEntities;
- }
- public static void deleteClient(Long id) throws NotFoundException {
- EntityManager entityManager = HibernateUtil.getEntityManager();
- ClientEntity clientEntity = checkIfExistsAndReturn(ClientEntity.class, id);
- entityManager.getTransaction().begin();
- entityManager.remove(entityManager.contains(clientEntity) ? clientEntity : entityManager.merge(clientEntity));
- entityManager.getTransaction().commit();
- entityManager.close();
- log.info("Client was deleted. ID = " + id);
- }
- public static void saveClient(ClientEntity client) {
- EntityManager entityManager = HibernateUtil.getEntityManager();
- entityManager.getTransaction().begin();
- entityManager.persist(client);
- entityManager.getTransaction().commit();
- entityManager.close();
- log.info("Client was saved. ID = " + client.getId());
- }
- public static void mergeClient(ClientEntity client) {
- EntityManager entityManager = HibernateUtil.getEntityManager();
- entityManager.getTransaction().begin();
- entityManager.merge(client);
- entityManager.getTransaction().commit();
- entityManager.close();
- log.info("Client was merged. ID = " + client.getId());
- }
- public static void mergeAccount(AccountEntity account) {
- EntityManager entityManager = HibernateUtil.getEntityManager();
- entityManager.getTransaction().begin();
- entityManager.merge(account);
- entityManager.getTransaction().commit();
- entityManager.close();
- log.info("Account was merged. ID = " + account.getId());
- }
- public static <T> T checkIfExistsAndReturn(Class<T> clas, Long id) throws NotFoundException {
- EntityManager entityManager = HibernateUtil.getEntityManager();
- T t = entityManager.find(clas, id);
- if (t == null) {
- throw new NotFoundException("Wrong id: there are no " + clas.getSimpleName() + " with such id.");
- }
- entityManager.close();
- return t;
- }
- }
- package com.example.utils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import javax.persistence.EntityManager;
- import javax.persistence.EntityManagerFactory;
- import javax.persistence.Persistence;
- public class HibernateUtil {
- private final static Logger log = LoggerFactory.getLogger(HibernateUtil.class.getName());
- private static final EntityManagerFactory entityManagerFactory;
- static {
- entityManagerFactory = Persistence.createEntityManagerFactory("com.example.jpa");
- }
- public static EntityManagerFactory getEntityManagerFactory() {
- return entityManagerFactory;
- }
- public static EntityManager getEntityManager() {
- return entityManagerFactory.createEntityManager();
- }
- public static void closeEntityManagerFactory() {
- entityManagerFactory.close();
- log.info("EntityManagerFactory was closed.");
- }
- }
- package com.example.utils;
- import com.example.services.AccountService;
- import com.example.services.ClientService;
- import com.example.services.IOService;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class Menu {
- private final static Logger log = LoggerFactory.getLogger(Menu.class.getName());
- private static int selection = 0;
- private static int MAX_NUMBER_ITEM = 7;
- private static int MIN_NUMBER_ITEM = 1;
- public static boolean toContinue = true;
- public static void displayMenu() {
- System.out.println("1) Create client.");
- System.out.println("2) Delete client.");
- System.out.println("3) Create account.");
- System.out.println("4) Change account.");
- System.out.println("5) Delete account.");
- System.out.println("6) Display list of clients and their accounts.");
- System.out.println("7) EXIT.");
- }
- public static void tryToSelectMenuItem() {
- try {
- selection = IOService.inputMenuItemNumber(MIN_NUMBER_ITEM, MAX_NUMBER_ITEM);
- } catch (Exception e) {
- log.error("Error in input.", e);
- }
- }
- public static void processSelectedMenuItem() {
- switch (selection) {
- case 1: {
- ClientService.createClient();
- break;
- }
- case 2: {
- ClientService.deleteClient();
- break;
- }
- case 3: {
- AccountService.createAccount();
- break;
- }
- case 4: {
- AccountService.changeAccount();
- break;
- }
- case 5: {
- AccountService.deleteAccount();
- break;
- }
- case 6: {
- ClientService.displayAllClientsInfo();
- break;
- }
- case 7: {
- toContinue = false;
- HibernateUtil.closeEntityManagerFactory();
- break;
- }
- }
- selection = 0;
- }
- }
- package com.example;
- import com.example.utils.Menu;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class App {
- private final static Logger log = LoggerFactory.getLogger(App.class.getName());
- public static void main(String[] args) {
- log.info("App started.");
- while (Menu.toContinue) {
- Menu.displayMenu();
- Menu.tryToSelectMenuItem();
- Menu.processSelectedMenuItem();
- }
- log.info("App closed.");
- }
- }
- <persistence xmlns="http://java.sun.com/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
- version="2.0">
- <persistence-unit name="com.example.jpa">
- <class>com.example.entities.AccountEntity</class>
- <class>com.example.entities.ClientEntity</class>
- <properties>
- <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
- <property name="javax.persistence.jdbc.url"
- value="jdbc:mysql://localhost:3306/hibernate_task?useSSL=false" />
- <property name="javax.persistence.jdbc.user" value="root" />
- <property name="javax.persistence.jdbc.password" value="root" />
- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
- <property name="hibernate.show_sql" value="false" />
- <property name="hibernate.hbm2ddl.auto" value="update" />
- </properties>
- </persistence-unit>
- </persistence>
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>logs/%d{yyyy-MM-dd}.log</fileNamePattern>
- </rollingPolicy>
- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
- </encoder>
- </appender>
- <logger name="org.hibernate" level="ERROR" />
- <root level="INFO">
- <appender-ref ref="FILE" />
- </root>
- </configuration>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement