Advertisement
Guest User

Untitled

a guest
Jul 13th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.00 KB | None | 0 0
  1. package com.example.entities;
  2.  
  3. import org.hibernate.annotations.GenericGenerator;
  4.  
  5. import javax.persistence.*;
  6. import java.time.LocalDateTime;
  7.  
  8. @Entity
  9. public class AccountEntity {
  10. private Long id;
  11. @Column(nullable = false)
  12. private ClientEntity client;
  13. private String login;
  14. private String password;
  15. private LocalDateTime created;
  16.  
  17. public AccountEntity() {
  18. }
  19.  
  20. public AccountEntity(ClientEntity client, String login, String password, LocalDateTime created) {
  21. this.client = client;
  22. this.login = login;
  23. this.password = password;
  24. this.created = created;
  25. }
  26.  
  27. @Id
  28. @GeneratedValue(generator = "increment")
  29. @GenericGenerator(name = "increment", strategy = "increment")
  30. public Long getId() {
  31. return id;
  32. }
  33.  
  34. public void setId(Long id) {
  35. this.id = id;
  36. }
  37.  
  38. @ManyToOne(fetch = FetchType.EAGER)
  39. public ClientEntity getClient() {
  40. return client;
  41. }
  42.  
  43. public void setClient(ClientEntity client) {
  44. this.client = client;
  45. }
  46.  
  47. public String getLogin() {
  48. return login;
  49. }
  50.  
  51. public void setLogin(String login) {
  52. this.login = login;
  53. }
  54.  
  55. public String getPassword() {
  56. return password;
  57. }
  58.  
  59. public void setPassword(String password) {
  60. this.password = password;
  61. }
  62.  
  63. public LocalDateTime getCreated() {
  64. return created;
  65. }
  66.  
  67. public void setCreated(LocalDateTime created) {
  68. this.created = created;
  69. }
  70. }
  71.  
  72. package com.example.entities;
  73.  
  74. import org.hibernate.annotations.GenericGenerator;
  75.  
  76. import javax.persistence.*;
  77. import java.util.List;
  78.  
  79. @Entity
  80. public class ClientEntity {
  81. private Long id;
  82. private String name;
  83. private String email;
  84. private List<AccountEntity> accountEntities;
  85.  
  86. public ClientEntity() {
  87. }
  88.  
  89. public ClientEntity(String name, String email, List<AccountEntity> accountEntities) {
  90. this.name = name;
  91. this.email = email;
  92. this.accountEntities = accountEntities;
  93. }
  94.  
  95. @Id
  96. @GeneratedValue(generator = "increment")
  97. @GenericGenerator(name = "increment", strategy = "increment")
  98. public Long getId() {
  99. return id;
  100. }
  101.  
  102. public void setId(Long id) {
  103. this.id = id;
  104. }
  105.  
  106. public String getName() {
  107. return name;
  108. }
  109.  
  110. public void setName(String name) {
  111. this.name = name;
  112. }
  113.  
  114. public String getEmail() {
  115. return email;
  116. }
  117.  
  118. public void setEmail(String email) {
  119. this.email = email;
  120. }
  121.  
  122. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  123. public List<AccountEntity> getAccountEntities() {
  124. return accountEntities;
  125. }
  126.  
  127. public void setAccountEntities(List<AccountEntity> accountEntities) {
  128. this.accountEntities = accountEntities;
  129. }
  130.  
  131. public void addAccount(AccountEntity accountEntity) {
  132. if (accountEntity != null) {
  133. accountEntities.add(accountEntity);
  134. }
  135. }
  136.  
  137. public void removeAccount(Long id) {
  138. accountEntities.removeIf(account -> account.getId().equals(id));
  139. }
  140. }
  141.  
  142. package com.example.services;
  143.  
  144. import com.example.entities.AccountEntity;
  145. import com.example.entities.ClientEntity;
  146. import org.slf4j.Logger;
  147. import org.slf4j.LoggerFactory;
  148.  
  149. public class AccountService {
  150. private final static Logger log = LoggerFactory.getLogger(AccountService.class.getName());
  151.  
  152. public static void createAccount() {
  153. try {
  154. Long id = IOService.inputId();
  155. ClientEntity client = PersistenceService.checkIfExistsAndReturn(ClientEntity.class, id);
  156. AccountEntity account = IOService.createAccount(client);
  157. client.addAccount(account);
  158. PersistenceService.mergeClient(client);
  159. IOService.printToConsole("Account was created.");
  160. } catch (Exception e) {
  161. IOService.printToConsole("Account wasn't created.");
  162. log.error("Account wasn't created.", e);
  163. }
  164. }
  165.  
  166. public static void deleteAccount() {
  167. try {
  168. Long id = IOService.inputId();
  169. ClientEntity client = PersistenceService.checkIfExistsAndReturn(AccountEntity.class, id).getClient();
  170. client.removeAccount(id);
  171. PersistenceService.mergeClient(client);
  172. IOService.printToConsole("Account with id = " + id + " was deleted.");
  173. } catch (Exception e) {
  174. IOService.printToConsole("Account wasn't deleted.");
  175. log.error("Account wasn't deleted.", e);
  176. }
  177. }
  178.  
  179. public static void changeAccount() {
  180. try {
  181. Long id = IOService.inputId();
  182. AccountEntity account = PersistenceService.checkIfExistsAndReturn(AccountEntity.class, id);
  183. account = IOService.changeAccount(account);
  184. PersistenceService.mergeAccount(account);
  185. IOService.printToConsole("Account was updated.");
  186. } catch (Exception e) {
  187. IOService.printToConsole("Account wasn't changed.");
  188. log.error("Account wasn't changed.", e);
  189. }
  190. }
  191. }
  192.  
  193. package com.example.services;
  194.  
  195. import com.example.entities.ClientEntity;
  196. import org.slf4j.Logger;
  197. import org.slf4j.LoggerFactory;
  198.  
  199. public class ClientService {
  200. private final static Logger log = LoggerFactory.getLogger(ClientService.class.getName());
  201.  
  202. public static void displayAllClientsInfo() {
  203. try {
  204. IOService.displayAllClientsInfo(PersistenceService.getAllClients());
  205. log.info("Method ClientService.displayAllClientsInfo() was called.");
  206. } catch (Exception e) {
  207. log.error("Error in ClientService.displayAllClientsInfo()", e);
  208. }
  209. }
  210.  
  211. public static void deleteClient() {
  212. try {
  213. Long id = IOService.inputId();
  214. PersistenceService.deleteClient(id);
  215. IOService.printToConsole("Client with id = " + id + " was deleted.");
  216. log.info("Client with id = " + id + " was deleted by ClientService.deleteClient().");
  217. } catch (Exception e) {
  218. IOService.printToConsole("Client wasn't found.");
  219. log.error("Client wasn't found.", e);
  220. }
  221. }
  222.  
  223. public static void createClient() {
  224. try {
  225. ClientEntity client = IOService.createClient();
  226. PersistenceService.saveClient(client);
  227. IOService.printToConsole("Client created.");
  228. log.info("Client created. ID = " + client.getId());
  229. } catch (Exception e) {
  230. log.error("Client wasn't created.", e);
  231. }
  232. }
  233. }
  234.  
  235. package com.example.services;
  236.  
  237. import com.example.entities.AccountEntity;
  238. import com.example.entities.ClientEntity;
  239. import org.apache.commons.lang.StringUtils;
  240. import org.slf4j.Logger;
  241. import org.slf4j.LoggerFactory;
  242.  
  243. import java.io.BufferedReader;
  244. import java.io.IOException;
  245. import java.io.InputStreamReader;
  246. import java.time.LocalDateTime;
  247. import java.time.format.DateTimeFormatter;
  248. import java.util.ArrayList;
  249. import java.util.List;
  250.  
  251. public class IOService {
  252. private final static Logger log = LoggerFactory.getLogger(IOService.class.getName());
  253. private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  254.  
  255. public static void displayAllClientsInfo(List<ClientEntity> clients) {
  256. if (clients.size() > 0) {
  257. printToConsole(StringUtils.center("Clients", 55) + StringUtils.center("Accounts", 85));
  258. printToConsole(StringUtils.repeat("-", 140));
  259. String columnsNames = String.format("%1$5s%2$25s%3$27s%4$3s%5$30s%6$25s%7$25s", "id", "e-mail", "name |",
  260. "id", "created", "login", "password");
  261. printToConsole(columnsNames);
  262. printToConsole(StringUtils.repeat("=", 140));
  263. StringBuilder clientInfo = new StringBuilder();
  264. for (ClientEntity client : clients) {
  265. clientInfo.append(String.format("%1$5d%2$25s%3$25s |", client.getId(), client.getEmail(),
  266. client.getName()));
  267. printToConsole(clientInfo);
  268. clientInfo.delete(0, clientInfo.length());
  269. List<AccountEntity> accounts = client.getAccountEntities();
  270. for (AccountEntity ac : accounts) {
  271. clientInfo.append(String.format("%1$60d%2$30s%3$25s%4$25s", ac.getId(), ac.getCreated(), ac.getLogin(),
  272. ac.getPassword()));
  273. clientInfo.setCharAt(56, '|');
  274. printToConsole(clientInfo);
  275. clientInfo.delete(0, clientInfo.length());
  276. }
  277. clientInfo.delete(0, clientInfo.length());
  278. printToConsole(StringUtils.repeat("-", 140));
  279. }
  280. } else {
  281. printToConsole("No data to display.");
  282. log.info("No data to display. IOService.displayAllClientsInfo()");
  283. }
  284. }
  285.  
  286. public static Long inputId() throws IOException {
  287. printToConsole("Input id: ");
  288. return Long.parseLong(br.readLine());
  289. }
  290.  
  291. public static int inputMenuItemNumber(int min, int max) throws IOException {
  292. int selection = 0;
  293. while (selection < min || selection > max) {
  294. printToConsole("To continue, enter the menu item number: ");
  295. selection = Integer.parseInt(br.readLine());
  296. }
  297. return selection;
  298. }
  299.  
  300. public static ClientEntity createClient() throws IOException {
  301. ClientEntity client = new ClientEntity();
  302. printToConsole("Input client name: ");
  303. client.setName(br.readLine());
  304. printToConsole("Input client e-mail: ");
  305. client.setEmail(br.readLine());
  306. printToConsole("Input number of accounts for client: ");
  307. int numberOfAccounts = Integer.parseInt(br.readLine());
  308. List<AccountEntity> accountEntities = new ArrayList<>();
  309. while (numberOfAccounts-- > 0) {
  310. accountEntities.add(createAccount(client));
  311. }
  312. client.setAccountEntities(accountEntities);
  313. return client;
  314. }
  315.  
  316. public static AccountEntity createAccount(ClientEntity client) throws IOException {
  317. printToConsole("Input login: ");
  318. String login = br.readLine();
  319. printToConsole("Input password: ");
  320. String password = br.readLine();
  321. LocalDateTime date = LocalDateTime.now();
  322. return new AccountEntity(client, login, password, date);
  323. }
  324.  
  325. public static AccountEntity changeAccount(AccountEntity account) throws IOException {
  326. printToConsole("Input new login: ");
  327. account.setLogin(br.readLine());
  328. printToConsole("Input new password: ");
  329. account.setPassword(br.readLine());
  330. printToConsole("Input new date in format like this "2011-12-03T10:15:30" (ISO Local Date and Time): ");
  331. DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
  332. LocalDateTime date = LocalDateTime.parse(br.readLine(), formatter);
  333. account.setCreated(date);
  334. return account;
  335. }
  336.  
  337. public static <T> void printToConsole(T message) {
  338. System.out.println(message);
  339. }
  340. }
  341.  
  342. package com.example.services;
  343.  
  344. import com.example.entities.AccountEntity;
  345. import com.example.entities.ClientEntity;
  346. import com.example.utils.HibernateUtil;
  347. import javassist.NotFoundException;
  348. import org.slf4j.Logger;
  349. import org.slf4j.LoggerFactory;
  350.  
  351. import javax.persistence.EntityManager;
  352. import java.util.List;
  353.  
  354. public class PersistenceService {
  355. private final static Logger log = LoggerFactory.getLogger(PersistenceService.class.getName());
  356.  
  357. public static List<ClientEntity> getAllClients() {
  358. EntityManager entityManager = HibernateUtil.getEntityManager();
  359. List<ClientEntity> clientEntities =
  360. entityManager.createQuery("SELECT c FROM ClientEntity c", ClientEntity.class).getResultList();
  361. entityManager.close();
  362. log.info("Got all client entities from DB.");
  363. return clientEntities;
  364. }
  365.  
  366. public static void deleteClient(Long id) throws NotFoundException {
  367. EntityManager entityManager = HibernateUtil.getEntityManager();
  368. ClientEntity clientEntity = checkIfExistsAndReturn(ClientEntity.class, id);
  369. entityManager.getTransaction().begin();
  370. entityManager.remove(entityManager.contains(clientEntity) ? clientEntity : entityManager.merge(clientEntity));
  371. entityManager.getTransaction().commit();
  372. entityManager.close();
  373. log.info("Client was deleted. ID = " + id);
  374. }
  375.  
  376. public static void saveClient(ClientEntity client) {
  377. EntityManager entityManager = HibernateUtil.getEntityManager();
  378. entityManager.getTransaction().begin();
  379. entityManager.persist(client);
  380. entityManager.getTransaction().commit();
  381. entityManager.close();
  382. log.info("Client was saved. ID = " + client.getId());
  383. }
  384.  
  385. public static void mergeClient(ClientEntity client) {
  386. EntityManager entityManager = HibernateUtil.getEntityManager();
  387. entityManager.getTransaction().begin();
  388. entityManager.merge(client);
  389. entityManager.getTransaction().commit();
  390. entityManager.close();
  391. log.info("Client was merged. ID = " + client.getId());
  392. }
  393.  
  394. public static void mergeAccount(AccountEntity account) {
  395. EntityManager entityManager = HibernateUtil.getEntityManager();
  396. entityManager.getTransaction().begin();
  397. entityManager.merge(account);
  398. entityManager.getTransaction().commit();
  399. entityManager.close();
  400. log.info("Account was merged. ID = " + account.getId());
  401. }
  402.  
  403. public static <T> T checkIfExistsAndReturn(Class<T> clas, Long id) throws NotFoundException {
  404. EntityManager entityManager = HibernateUtil.getEntityManager();
  405. T t = entityManager.find(clas, id);
  406. if (t == null) {
  407. throw new NotFoundException("Wrong id: there are no " + clas.getSimpleName() + " with such id.");
  408. }
  409. entityManager.close();
  410. return t;
  411. }
  412. }
  413.  
  414. package com.example.utils;
  415.  
  416. import org.slf4j.Logger;
  417. import org.slf4j.LoggerFactory;
  418.  
  419. import javax.persistence.EntityManager;
  420. import javax.persistence.EntityManagerFactory;
  421. import javax.persistence.Persistence;
  422.  
  423. public class HibernateUtil {
  424. private final static Logger log = LoggerFactory.getLogger(HibernateUtil.class.getName());
  425. private static final EntityManagerFactory entityManagerFactory;
  426.  
  427. static {
  428. entityManagerFactory = Persistence.createEntityManagerFactory("com.example.jpa");
  429. }
  430.  
  431. public static EntityManagerFactory getEntityManagerFactory() {
  432. return entityManagerFactory;
  433. }
  434.  
  435. public static EntityManager getEntityManager() {
  436. return entityManagerFactory.createEntityManager();
  437. }
  438.  
  439. public static void closeEntityManagerFactory() {
  440. entityManagerFactory.close();
  441. log.info("EntityManagerFactory was closed.");
  442. }
  443. }
  444.  
  445. package com.example.utils;
  446.  
  447. import com.example.services.AccountService;
  448. import com.example.services.ClientService;
  449. import com.example.services.IOService;
  450. import org.slf4j.Logger;
  451. import org.slf4j.LoggerFactory;
  452.  
  453. public class Menu {
  454. private final static Logger log = LoggerFactory.getLogger(Menu.class.getName());
  455. private static int selection = 0;
  456. private static int MAX_NUMBER_ITEM = 7;
  457. private static int MIN_NUMBER_ITEM = 1;
  458. public static boolean toContinue = true;
  459.  
  460. public static void displayMenu() {
  461. System.out.println("1) Create client.");
  462. System.out.println("2) Delete client.");
  463. System.out.println("3) Create account.");
  464. System.out.println("4) Change account.");
  465. System.out.println("5) Delete account.");
  466. System.out.println("6) Display list of clients and their accounts.");
  467. System.out.println("7) EXIT.");
  468. }
  469.  
  470. public static void tryToSelectMenuItem() {
  471. try {
  472. selection = IOService.inputMenuItemNumber(MIN_NUMBER_ITEM, MAX_NUMBER_ITEM);
  473. } catch (Exception e) {
  474. log.error("Error in input.", e);
  475. }
  476. }
  477.  
  478. public static void processSelectedMenuItem() {
  479. switch (selection) {
  480. case 1: {
  481. ClientService.createClient();
  482. break;
  483. }
  484. case 2: {
  485. ClientService.deleteClient();
  486. break;
  487. }
  488. case 3: {
  489. AccountService.createAccount();
  490. break;
  491. }
  492. case 4: {
  493. AccountService.changeAccount();
  494. break;
  495. }
  496. case 5: {
  497. AccountService.deleteAccount();
  498. break;
  499. }
  500. case 6: {
  501. ClientService.displayAllClientsInfo();
  502. break;
  503. }
  504. case 7: {
  505. toContinue = false;
  506. HibernateUtil.closeEntityManagerFactory();
  507. break;
  508. }
  509. }
  510. selection = 0;
  511. }
  512. }
  513.  
  514. package com.example;
  515.  
  516. import com.example.utils.Menu;
  517. import org.slf4j.Logger;
  518. import org.slf4j.LoggerFactory;
  519.  
  520. public class App {
  521. private final static Logger log = LoggerFactory.getLogger(App.class.getName());
  522.  
  523. public static void main(String[] args) {
  524. log.info("App started.");
  525. while (Menu.toContinue) {
  526. Menu.displayMenu();
  527. Menu.tryToSelectMenuItem();
  528. Menu.processSelectedMenuItem();
  529. }
  530. log.info("App closed.");
  531. }
  532. }
  533.  
  534. <persistence xmlns="http://java.sun.com/xml/ns/persistence"
  535. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  536. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
  537. version="2.0">
  538. <persistence-unit name="com.example.jpa">
  539. <class>com.example.entities.AccountEntity</class>
  540. <class>com.example.entities.ClientEntity</class>
  541. <properties>
  542. <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
  543. <property name="javax.persistence.jdbc.url"
  544. value="jdbc:mysql://localhost:3306/hibernate_task?useSSL=false" />
  545. <property name="javax.persistence.jdbc.user" value="root" />
  546. <property name="javax.persistence.jdbc.password" value="root" />
  547. <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
  548. <property name="hibernate.show_sql" value="false" />
  549. <property name="hibernate.hbm2ddl.auto" value="update" />
  550. </properties>
  551. </persistence-unit>
  552. </persistence>
  553.  
  554. <?xml version="1.0" encoding="UTF-8"?>
  555. <configuration>
  556. <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  557. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  558. <fileNamePattern>logs/%d{yyyy-MM-dd}.log</fileNamePattern>
  559. </rollingPolicy>
  560.  
  561. <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
  562. <maxFileSize>5MB</maxFileSize>
  563. </triggeringPolicy>
  564.  
  565. <encoder>
  566. <pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  567. </encoder>
  568. </appender>
  569.  
  570. <logger name="org.hibernate" level="ERROR" />
  571.  
  572. <root level="INFO">
  573. <appender-ref ref="FILE" />
  574. </root>
  575. </configuration>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement