diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 00000000..27c1d1dd
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Datasource local storage ignored files
+/../../../../../../:\Users\Vit\IdeaProjects\CoreTaskTemplate\.idea/dataSources/
+/dataSources.local.xml
+# Editor-based HTTP Client requests
+/httpRequests/
diff --git a/.idea/.name b/.idea/.name
new file mode 100644
index 00000000..24736517
--- /dev/null
+++ b/.idea/.name
@@ -0,0 +1 @@
+TaskJDBC
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 00000000..e9ed1a37
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml
new file mode 100644
index 00000000..6775395a
--- /dev/null
+++ b/.idea/dataSources.xml
@@ -0,0 +1,15 @@
+
+
+
+
+ mysql.8
+ true
+ com.mysql.jdbc.Driver
+ jdbc:mysql://localhost:3306/business
+
+
+
+ Etc/UTC
+
+
+
\ No newline at end of file
diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml
new file mode 100644
index 00000000..712ab9d9
--- /dev/null
+++ b/.idea/jarRepositories.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__antlr_antlr_2_7_7.xml b/.idea/libraries/Maven__antlr_antlr_2_7_7.xml
new file mode 100644
index 00000000..b8d93d8e
--- /dev/null
+++ b/.idea/libraries/Maven__antlr_antlr_2_7_7.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__dom4j_dom4j_1_6_1.xml b/.idea/libraries/Maven__dom4j_dom4j_1_6_1.xml
new file mode 100644
index 00000000..14681ee8
--- /dev/null
+++ b/.idea/libraries/Maven__dom4j_dom4j_1_6_1.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__junit_junit_4_12.xml b/.idea/libraries/Maven__junit_junit_4_12.xml
new file mode 100644
index 00000000..d4110417
--- /dev/null
+++ b/.idea/libraries/Maven__junit_junit_4_12.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_47.xml b/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_47.xml
new file mode 100644
index 00000000..8ed561b0
--- /dev/null
+++ b/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_47.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml b/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml
new file mode 100644
index 00000000..f58bbc11
--- /dev/null
+++ b/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_hibernate_common_hibernate_commons_annotations_4_0_5_Final.xml b/.idea/libraries/Maven__org_hibernate_common_hibernate_commons_annotations_4_0_5_Final.xml
new file mode 100644
index 00000000..9ed6d297
--- /dev/null
+++ b/.idea/libraries/Maven__org_hibernate_common_hibernate_commons_annotations_4_0_5_Final.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_hibernate_hibernate_core_4_3_10_Final.xml b/.idea/libraries/Maven__org_hibernate_hibernate_core_4_3_10_Final.xml
new file mode 100644
index 00000000..0f9bf7c2
--- /dev/null
+++ b/.idea/libraries/Maven__org_hibernate_hibernate_core_4_3_10_Final.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_hibernate_javax_persistence_hibernate_jpa_2_1_api_1_0_2_Final.xml b/.idea/libraries/Maven__org_hibernate_javax_persistence_hibernate_jpa_2_1_api_1_0_2_Final.xml
new file mode 100644
index 00000000..1d8ce405
--- /dev/null
+++ b/.idea/libraries/Maven__org_hibernate_javax_persistence_hibernate_jpa_2_1_api_1_0_2_Final.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_javassist_javassist_3_18_1_GA.xml b/.idea/libraries/Maven__org_javassist_javassist_3_18_1_GA.xml
new file mode 100644
index 00000000..1f907308
--- /dev/null
+++ b/.idea/libraries/Maven__org_javassist_javassist_3_18_1_GA.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_jboss_jandex_1_1_0_Final.xml b/.idea/libraries/Maven__org_jboss_jandex_1_1_0_Final.xml
new file mode 100644
index 00000000..d3cd0897
--- /dev/null
+++ b/.idea/libraries/Maven__org_jboss_jandex_1_1_0_Final.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_jboss_logging_jboss_logging_3_1_3_GA.xml b/.idea/libraries/Maven__org_jboss_logging_jboss_logging_3_1_3_GA.xml
new file mode 100644
index 00000000..815ab4d8
--- /dev/null
+++ b/.idea/libraries/Maven__org_jboss_logging_jboss_logging_3_1_3_GA.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_jboss_logging_jboss_logging_annotations_1_2_0_Beta1.xml b/.idea/libraries/Maven__org_jboss_logging_jboss_logging_annotations_1_2_0_Beta1.xml
new file mode 100644
index 00000000..715be298
--- /dev/null
+++ b/.idea/libraries/Maven__org_jboss_logging_jboss_logging_annotations_1_2_0_Beta1.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__org_jboss_spec_javax_transaction_jboss_transaction_api_1_2_spec_1_0_0_Final.xml b/.idea/libraries/Maven__org_jboss_spec_javax_transaction_jboss_transaction_api_1_2_spec_1_0_0_Final.xml
new file mode 100644
index 00000000..2ab91298
--- /dev/null
+++ b/.idea/libraries/Maven__org_jboss_spec_javax_transaction_jboss_transaction_api_1_2_spec_1_0_0_Final.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__xml_apis_xml_apis_1_0_b2.xml b/.idea/libraries/Maven__xml_apis_xml_apis_1_0_b2.xml
new file mode 100644
index 00000000..c36e7171
--- /dev/null
+++ b/.idea/libraries/Maven__xml_apis_xml_apis_1_0_b2.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 00000000..2154258d
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 00000000..882550cd
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 00000000..35eb1ddf
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/TaskJDBC.iml b/TaskJDBC.iml
new file mode 100644
index 00000000..eb93f079
--- /dev/null
+++ b/TaskJDBC.iml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 0605a4c0..7ebeb70a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -13,8 +13,8 @@
org.apache.maven.plugins
maven-compiler-plugin
- 7
- 7
+ 9
+ 9
@@ -33,7 +33,7 @@
mysql
mysql-connector-java
- 5.1.38
+ 8.0.20
@@ -47,6 +47,11 @@
hibernate-core
4.3.10.Final
-
+
+ mysql
+ mysql-connector-java
+ 5.1.47
+
+
\ No newline at end of file
diff --git a/src/main/java/jm/task/core/jdbc/Main.java b/src/main/java/jm/task/core/jdbc/Main.java
index f6e43b0f..29e98100 100644
--- a/src/main/java/jm/task/core/jdbc/Main.java
+++ b/src/main/java/jm/task/core/jdbc/Main.java
@@ -1,7 +1,50 @@
package jm.task.core.jdbc;
+import com.mysql.fabric.jdbc.FabricMySQLDriver;
+import jm.task.core.jdbc.dao.UserDaoHibernateImpl;
+import jm.task.core.jdbc.model.User;
+import jm.task.core.jdbc.service.UserService;
+import jm.task.core.jdbc.service.UserServiceImpl;
+import jm.task.core.jdbc.util.Util;
+import java.util.Iterator;
+import java.sql.*;
+import java.util.List;
+import java.util.ArrayList;
+
+
public class Main {
- public static void main(String[] args) {
- // реализуйте алгоритм здесь
+
+ public static void main(String[] args) throws SQLException {
+//через hibernate
+ new UserServiceImpl().createUsersTable();// добавление таблицы
+
+ new UserServiceImpl().saveUser("Александр", "Пушкин", (byte) 37);
+ new UserServiceImpl().saveUser("Владимир", "Высотский", (byte) 41);
+ new UserServiceImpl().saveUser("Зинаида", "Серебрякова", (byte) 69);
+ new UserServiceImpl().saveUser("ВладимирДоп", "Набоков", (byte) 65);
+ new UserServiceImpl().saveUser("new", "new_Набоков", (byte) 65);
+
+// new UserDaoHibernateImpl().removeUserById(2);
+
+ List arr = new UserServiceImpl().getAllUsers();
+ arr.stream().forEach(user -> System.out.println(user.toString()));
+ new UserServiceImpl().cleanUsersTable();// Работет
+
+
+
+ Util.getSessionFactory().close();
+ //new UserServiceImpl().dropUsersTable();// Удаление таблицы
+//------------
+
+ //new UserServiceImpl().removeUserById(3);
+
+
+ //List arr = new UserServiceImpl().getAllUsers();
+ //arr.stream().forEach(user -> System.out.println(user.toString()));
+
+ //new UserServiceImpl().cleanUsersTable();// Раблтет
+ //new UserServiceImpl().dropUsersTable();// Удаление таблицы
+
+
}
}
diff --git a/src/main/java/jm/task/core/jdbc/dao/UserDao.java b/src/main/java/jm/task/core/jdbc/dao/UserDao.java
index 27069baf..ebb05fab 100644
--- a/src/main/java/jm/task/core/jdbc/dao/UserDao.java
+++ b/src/main/java/jm/task/core/jdbc/dao/UserDao.java
@@ -2,18 +2,19 @@
import jm.task.core.jdbc.model.User;
+import java.sql.SQLException;
import java.util.List;
public interface UserDao {
- void createUsersTable();
+ void createUsersTable() throws SQLException;
- void dropUsersTable();
+ void dropUsersTable() throws SQLException;
- void saveUser(String name, String lastName, byte age);
+ void saveUser(String name, String lastName, byte age) throws SQLException;
- void removeUserById(long id);
+ void removeUserById(long id) throws SQLException;
- List getAllUsers();
+ List getAllUsers() throws SQLException;
- void cleanUsersTable();
+ void cleanUsersTable() throws SQLException;
}
diff --git a/src/main/java/jm/task/core/jdbc/dao/UserDaoHibernateImpl.java b/src/main/java/jm/task/core/jdbc/dao/UserDaoHibernateImpl.java
index dc2d0636..5c87a145 100644
--- a/src/main/java/jm/task/core/jdbc/dao/UserDaoHibernateImpl.java
+++ b/src/main/java/jm/task/core/jdbc/dao/UserDaoHibernateImpl.java
@@ -1,42 +1,92 @@
package jm.task.core.jdbc.dao;
import jm.task.core.jdbc.model.User;
+import jm.task.core.jdbc.util.Util;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
import java.util.List;
public class UserDaoHibernateImpl implements UserDao {
+ String table = "new_table";
public UserDaoHibernateImpl() {
}
-
-
+// Сюда по новой записать методы
@Override
public void createUsersTable() {
-
+ String sql = "CREATE TABLE IF NOT EXISTS `mydbtest2`.`"+ table + "` (\n" +
+ " `id` INT NOT NULL AUTO_INCREMENT,\n" +
+ " `name` VARCHAR(45) NULL,\n" +
+ " `lastname` VARCHAR(45) NULL,\n" +
+ " `age` TINYINT NULL,\n" +
+ " PRIMARY KEY (`id`));";
+ Session session = Util.getSession();
+ session.createSQLQuery(sql).executeUpdate();//прочитать подробнее почему executeUpdate озвращает int
+ Transaction transaction = session.beginTransaction();
+ transaction.commit();
+ //System.out.println("Таблица готова");
+ session.close();
}
@Override
public void dropUsersTable() {
-
+ try {
+ Session session = Util.getSession();
+ Transaction transaction = session.beginTransaction();
+ String sql = "DROP TABLE IF EXISTS new_table";
+ session.createSQLQuery(sql).executeUpdate();
+ transaction.commit();
+ session.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
@Override
public void saveUser(String name, String lastName, byte age) {
+ Session session = Util.getSession();
+ Transaction transaction = session.beginTransaction();
+ session.save(new User(name, lastName, age));
+ transaction.commit();
+ session.close();
}
@Override
public void removeUserById(long id) {
-
+ Session session = Util.getSession();
+ Transaction transaction = session.beginTransaction();
+
+ Query query = session.createQuery("DELETE User WHERE id = :id");
+// String SQL = "DELETE FROM " + table + " WHERE id = " + id;
+// Query query = session.createSQLQuery(SQL);
+ query.setParameter("id", id);
+ query.executeUpdate();
+ transaction.commit();
+ session.close();
}
@Override
- public List getAllUsers() {
- return null;
+
+ public List getAllUsers()
+ {
+ Session session = Util.getSession();
+ List user =null;
+ user = session.createQuery("From User").list();
+ session.close();
+ return user;
}
@Override
public void cleanUsersTable() {
-
+ Session session = Util.getSession();
+ Transaction transaction = session.beginTransaction();//
+ String HQL= "DELETE FROM User";
+ session.createQuery(HQL).executeUpdate();
+ transaction.commit();
+ session.close();
}
+
}
diff --git a/src/main/java/jm/task/core/jdbc/dao/UserDaoJDBCImpl.java b/src/main/java/jm/task/core/jdbc/dao/UserDaoJDBCImpl.java
index a6c6c359..e752a329 100644
--- a/src/main/java/jm/task/core/jdbc/dao/UserDaoJDBCImpl.java
+++ b/src/main/java/jm/task/core/jdbc/dao/UserDaoJDBCImpl.java
@@ -1,35 +1,137 @@
package jm.task.core.jdbc.dao;
import jm.task.core.jdbc.model.User;
+import jm.task.core.jdbc.util.Util;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
import java.util.List;
public class UserDaoJDBCImpl implements UserDao {
+ private static final String URL ="jdbc:mysql://localhost:3306/mydbtest2?autoReconnect=true&useSSL=false";
+ private static final String USERNAME = "root";
+ private static final String PASSWORD = "root";
+ String table = "new_table2";
+
public UserDaoJDBCImpl() {
}
- public void createUsersTable() {
+ public void createUsersTable() throws SQLException {
+
+ Util util = new Util();
+ Connection conn = util.getConnection(URL,USERNAME,PASSWORD);
+
+ Statement statement = conn.createStatement();
+ String SQL = "CREATE TABLE IF NOT EXISTS `mydbtest2`.`"+ table + "` (\n" +
+ " `id` INT NOT NULL AUTO_INCREMENT,\n" +
+ " `name` VARCHAR(45) NULL,\n" +
+ " `lastname` VARCHAR(45) NULL,\n" +
+ " `age` TINYINT NULL,\n" +
+ " PRIMARY KEY (`id`));";
+ //statement.executeUpdate("USE new_table2;");//назначить бд используемой
+ statement.executeUpdate(SQL);
+ System.out.println("Базу " +"new_table2" + " создали.");
+ statement.close();
+ conn.close();
}
- public void dropUsersTable() {
+ public void dropUsersTable() throws SQLException {
+ Util util = new Util();
+ Connection conn = util.getConnection(URL,USERNAME,PASSWORD);
+ String SQL = "DROP TABLE IF EXISTS " + table; // String table = "new_table2";
+ Statement statement = conn.createStatement();// создаем соединение
+
+ statement.executeUpdate("USE mydbtest2");// Установили бд в качестве используемой
+ try {
+ statement.executeUpdate(SQL);
+ } catch (SQLException throwables) {
+ System.out.println("Не удалось удалить");
+ }
+ System.out.println("Базу " +"new_table2" + " удалили.");
+ statement.close();
+ conn.close();
}
- public void saveUser(String name, String lastName, byte age) {
+ public void saveUser(String name, String lastName, byte age) throws SQLException {
+ //добавить вывод в консиль
+ Util util = new Util();
+ Connection conn = util.getConnection(URL,USERNAME,PASSWORD);
+ String SQL = "INSERT `" + table + "`(`name`, `lastname`, `age`) VALUES ('" +
+ name + "', '" + lastName + "', '" + age + "')";
+ Statement statement = conn.createStatement();// создаем соединение
+ statement.executeUpdate("USE mydbtest2");// Установили бд в качестве используемой
+ try {
+ statement.executeUpdate(SQL);
+ } catch (SQLException throwables) {
+ System.out.println("Не удалось Сохранить юзера");
+ }
+ System.out.println(" User с именем – " + name + " добавлен в базу данных");
+ statement.close();
+ conn.close();
}
- public void removeUserById(long id) {
+ public void removeUserById(long id) throws SQLException {
+ String SQL = "DELETE FROM " + table + " WHERE id = " + id;
+ Util util = new Util();
+ Connection conn = util.getConnection(URL,USERNAME,PASSWORD);
+
+ Statement statement = conn.createStatement();// создаем соединение
+ statement.executeUpdate("USE mydbtest2");// Установили бд в качестве используемой
+ try {
+ statement.executeUpdate(SQL);
+ } catch (SQLException throwables) {
+ System.out.println("Не удалось удалить юзера");
+ }
+ System.out.println("удалили юзера с номером " +id);
+ statement.close();
+ conn.close();
}
- public List getAllUsers() {
- return null;
+ public List getAllUsers() throws SQLException {
+ String SQL = "SELECT * FROM " + table ;
+ List listUsers = new ArrayList();
+ Util util = new Util();
+ Connection conn = util.getConnection(URL,USERNAME,PASSWORD);
+ Statement statement = conn.createStatement();
+ ResultSet resultSet = statement.executeQuery(SQL);
+ // добавить запрос
+
+ while (resultSet.next()) {
+ int i = resultSet.getInt("id");
+ String name = resultSet.getString("name");
+ String lastname = resultSet.getString("lastname");
+ byte age = (byte) resultSet.getInt("age");
+
+ User User = new User(name, lastname, age);
+ listUsers.add(User);
+ }
+ return listUsers;
+
}
- public void cleanUsersTable() {
+ public void cleanUsersTable() throws SQLException {
+ String SQL = "TRUNCATE TABLE " + table;
+ Util util = new Util();
+ Connection conn = util.getConnection(URL,USERNAME,PASSWORD);
+
+ Statement statement = conn.createStatement();// создаем соединение
+ statement.executeUpdate("USE mydbtest2");// Установили бд в качестве используемой
+ try {
+ statement.executeUpdate(SQL);
+ } catch (SQLException throwables) {
+ System.out.println("Не удалось очистить базу");
+ }
+ System.out.println("Базу очистили");
+ statement.close();
+ conn.close();
}
}
diff --git a/src/main/java/jm/task/core/jdbc/model/User.java b/src/main/java/jm/task/core/jdbc/model/User.java
index 21b054f6..e51cf7a6 100644
--- a/src/main/java/jm/task/core/jdbc/model/User.java
+++ b/src/main/java/jm/task/core/jdbc/model/User.java
@@ -1,12 +1,14 @@
package jm.task.core.jdbc.model;
-import javax.persistence.Column;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import javax.persistence.*;
+
+@Entity//Эта аннотация позволяет Java-объектам вашего класса быть связанными с БД.
+@Table(name = "new_table")//тут надо написать название таблицы (name = "Название")
-@Table
public class User {
- @Id
+
+ @Id// Отсутствует сеттер так как это указание, что поле является идентификатором объектов этого класса
+ @GeneratedValue(strategy = GenerationType.IDENTITY) //проверить надо ли
private Long id;
@Column
@@ -59,4 +61,12 @@ public Byte getAge() {
public void setAge(Byte age) {
this.age = age;
}
+
+ @Override
+ public String toString(){
+ return "User " + "name = " + name +
+ ", lastName='" + lastName +
+ ", age=" + age;
+ }
+
}
diff --git a/src/main/java/jm/task/core/jdbc/service/UserService.java b/src/main/java/jm/task/core/jdbc/service/UserService.java
index 80542c68..e1d1a7c4 100644
--- a/src/main/java/jm/task/core/jdbc/service/UserService.java
+++ b/src/main/java/jm/task/core/jdbc/service/UserService.java
@@ -2,18 +2,19 @@
import jm.task.core.jdbc.model.User;
+import java.sql.SQLException;
import java.util.List;
public interface UserService {
- void createUsersTable();
+ void createUsersTable() throws SQLException;
- void dropUsersTable();
+ void dropUsersTable() throws SQLException;
- void saveUser(String name, String lastName, byte age);
+ void saveUser(String name, String lastName, byte age) throws SQLException;
- void removeUserById(long id);
+ void removeUserById(long id) throws SQLException;
- List getAllUsers();
+ List getAllUsers() throws SQLException;
- void cleanUsersTable();
+ void cleanUsersTable() throws SQLException;
}
diff --git a/src/main/java/jm/task/core/jdbc/service/UserServiceImpl.java b/src/main/java/jm/task/core/jdbc/service/UserServiceImpl.java
index b05bd191..82604abf 100644
--- a/src/main/java/jm/task/core/jdbc/service/UserServiceImpl.java
+++ b/src/main/java/jm/task/core/jdbc/service/UserServiceImpl.java
@@ -1,31 +1,46 @@
package jm.task.core.jdbc.service;
+import jm.task.core.jdbc.dao.UserDaoHibernateImpl;
+import jm.task.core.jdbc.dao.UserDaoJDBCImpl;
import jm.task.core.jdbc.model.User;
+import jm.task.core.jdbc.util.Util;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
import java.util.List;
public class UserServiceImpl implements UserService {
- public void createUsersTable() {
-
- }
+ // Надо поменять ообъект на Hibernate
- public void dropUsersTable() {
+ private final UserDaoHibernateImpl userDaoJDBC = new UserDaoHibernateImpl();
+ //private final UserDaoJDBCImpl userDaoJDBC = new UserDaoJDBCImpl();
+ public void createUsersTable() throws SQLException {
+ userDaoJDBC.createUsersTable();
+ // sessionFactory.close();
}
- public void saveUser(String name, String lastName, byte age) {
-
+ public void dropUsersTable() throws SQLException {
+ userDaoJDBC.dropUsersTable();
}
- public void removeUserById(long id) {
+ public void saveUser(String name, String lastName, byte age) throws SQLException {
+ userDaoJDBC.saveUser(name, lastName, age);
}
- public List getAllUsers() {
- return null;
+ public void removeUserById(long id) throws SQLException {
+ userDaoJDBC.removeUserById(id);
}
- public void cleanUsersTable() {
+ public List getAllUsers() throws SQLException {
+return userDaoJDBC.getAllUsers();
+ }
+ public void cleanUsersTable() throws SQLException {
+ userDaoJDBC.cleanUsersTable();
}
}
diff --git a/src/main/java/jm/task/core/jdbc/util/Util.java b/src/main/java/jm/task/core/jdbc/util/Util.java
index 59e462ba..eed5a35c 100644
--- a/src/main/java/jm/task/core/jdbc/util/Util.java
+++ b/src/main/java/jm/task/core/jdbc/util/Util.java
@@ -1,5 +1,90 @@
package jm.task.core.jdbc.util;
+import com.mysql.fabric.jdbc.FabricMySQLDriver;
+import jm.task.core.jdbc.model.User;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.cfg.Environment;
+
+import org.hibernate.service.ServiceRegistry;
+import org.hibernate.cfg.Configuration;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+
public class Util {
- // реализуйте настройку соеденения с БД
+ private static final String URL ="jdbc:mysql://localhost:3306/mydbtest2?autoReconnect=true&useSSL=false";
+ private static final String USERNAME = "root";
+ private static final String PASSWORD = "root";
+
+//-----Hibernate
+ private static SessionFactory sessionFactory;
+ private static ServiceRegistry serviceRegistry;
+
+ static {
+ try {
+ Configuration configuration = getConfig();
+ //configuration.configure();
+ serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
+ configuration.getProperties()).build();
+
+ sessionFactory = configuration.buildSessionFactory(serviceRegistry);// соединение создание фабрики
+ } catch (HibernateException xe) {
+ xe.printStackTrace();
+ }
+ }
+ public static Configuration getConfig() {
+
+ Properties properties = new Properties();
+ properties.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
+ properties.setProperty("hibernate.connection.url", URL);
+ properties.setProperty("hibernate.connection.username",USERNAME);
+ properties.setProperty("hibernate.connection.password",PASSWORD);
+ properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
+ // properties.setProperty("hibernate.show_sql", "true");// Показывает запросы
+ properties.setProperty("hibernate.hbm2ddl.auto", "update");// Прочитать отдельно
+ properties.setProperty("hibernate.current_session_context_class", "thread");
+
+ Configuration configuration = new Configuration();
+ configuration.setProperties(properties);
+ configuration .addAnnotatedClass(User.class);//передаем класс с аннотациями
+
+ return configuration;
+}
+ public static Session getSession () {
+ return sessionFactory.openSession();
+ }
+
+ public static SessionFactory getSessionFactory() {
+ return sessionFactory;
+ }
+
+ //-----
+ private Connection connection;
+ {
+ /* public Util(){// в конструкторе регистрируем драйвер, а соединение в методе
+ try {
+ DriverManager.registerDriver(new FabricMySQLDriver());
+ } catch (SQLException ex) {
+ System.out.println("Ошибка регистриции драйвера");
+ return;
+ }*/
+ }
+
+ public Connection getConnection(String url, String username, String password) throws SQLException {
+
+ /* if (connection != null)
+ return connection;
+ connection = DriverManager.getConnection(url, username, password);
+ //System.out.println("Соединение установленно");*/
+ return connection;
+
+
+ }
+
+
}