-
Notifications
You must be signed in to change notification settings - Fork 39
Иванов Михаил, 495, MiniORM #185
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Misha100896
wants to merge
6
commits into
akormushin:master
Choose a base branch
from
Misha100896:miniORM
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0715384
help
Misha100896 051b57f
Merge branch 'master' of https://github.com/akormushin/fizteh-java-2015
Misha100896 e4b29ed
twitter stream
Misha100896 4cb8994
ModuleTests
Misha100896 46a82a8
threads
Misha100896 dbbadb2
miniORM
Misha100896 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| *.properties | ||
| .DS_Store | ||
| *.txt | ||
| *.class | ||
| *.jar | ||
| *.war | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| <?xml version="1.0"?> | ||
| <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" | ||
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> | ||
| <modelVersion>4.0.0</modelVersion> | ||
| <parent> | ||
| <groupId>ru.fizteh.fivt.students</groupId> | ||
| <artifactId>parent</artifactId> | ||
| <version>1.0-SNAPSHOT</version> | ||
| </parent> | ||
| <groupId>ru.fizteh.fivt.students</groupId> | ||
| <artifactId>Misha100896</artifactId> | ||
| <version>1.0-SNAPSHOT</version> | ||
| <name>Misha100896</name> | ||
| <url>http://maven.apache.org</url> | ||
| <properties> | ||
| <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||
| </properties> | ||
| <dependencies> | ||
| <dependency> | ||
| <groupId>junit</groupId> | ||
| <artifactId>junit</artifactId> | ||
| <version>3.8.1</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.twitter4j</groupId> | ||
| <artifactId>twitter4j-core</artifactId> | ||
| <version>[4.0,)</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.twitter4j</groupId> | ||
| <artifactId>twitter4j-stream</artifactId> | ||
| <version>4.0.4</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.beust</groupId> | ||
| <artifactId>jcommander</artifactId> | ||
| <version>1.48</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.maps</groupId> | ||
| <artifactId>google-maps-services</artifactId> | ||
| <version>0.1.1</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>junit</groupId> | ||
| <artifactId>junit</artifactId> | ||
| <version>4.12</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| </dependencies> | ||
| </project> |
38 changes: 38 additions & 0 deletions
38
Misha100896/src/main/java/ru/fizteh/fivt/students/miniorm/ClassConverter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package ru.fizteh.fivt.students.miniorm; | ||
|
|
||
| import java.sql.Time; | ||
| import java.sql.Timestamp; | ||
| import java.util.Date; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.UUID; | ||
|
|
||
|
|
||
| public class | ||
| ClassConverter { | ||
| private static Map<Class, String> classes; | ||
| static { | ||
| classes = new HashMap<>(); | ||
| classes.put(Integer.class, "INTEGER"); | ||
| classes.put(Boolean.class, "BOOLEAN"); | ||
| classes.put(Byte.class, "TINYINT"); | ||
| classes.put(Short.class, "SMALLINT"); | ||
| classes.put(Long.class, "BIGINT"); | ||
| classes.put(Double.class, "DOUBLE"); | ||
| classes.put(Float.class, "FLOAT"); | ||
| classes.put(Time.class, "TIME"); | ||
| classes.put(Date.class, "DATE"); | ||
| classes.put(Timestamp.class, "TIMESTAMP"); | ||
| classes.put(Character.class, "CHAR"); | ||
| classes.put(String.class, "CLOB"); | ||
| classes.put(UUID.class, "UUID"); | ||
| } | ||
|
|
||
| public static String convert(final Class currClass) { | ||
| if (classes.containsKey(currClass)) { | ||
| return classes.get(currClass); | ||
| } | ||
| return "OTHER"; | ||
| } | ||
|
|
||
| } |
236 changes: 236 additions & 0 deletions
236
Misha100896/src/main/java/ru/fizteh/fivt/students/miniorm/DatabaseService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| package ru.fizteh.fivt.students.miniorm; | ||
|
|
||
| import com.google.common.base.Caseformat; | ||
| import ru.fizteh.fivt.students.miniorm.annotations.Column; | ||
| import ru.fizteh.fivt.students.miniorm.annotations.PrimaryKey; | ||
| import ru.fizteh.fivt.students.miniorm.annotations.Table; | ||
| import ru.fizteh.fivt.students.miniorm.exception.HandlerOfException; | ||
|
|
||
| import javax.management.OperationsException; | ||
| import java.lang.reflect.Field; | ||
| import java.sql.*; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| public class DatabaseService<T> { | ||
|
|
||
| private Connection connection = null; | ||
| private Statement statement = null; | ||
| private ResultSet resultSet = null; | ||
| private Field primaryKey = null; | ||
| private List<Field> columns = null; | ||
| private Field[] fields; | ||
| private String[] namesOfColumns; | ||
| private Class<T> tableClass = null; | ||
| private String tableName = ""; | ||
| private int primaryKeyFieldNumber = -1; | ||
|
|
||
| private boolean hasTableYet = false; | ||
|
|
||
| DatabaseService(final Class<T> elementClass) throws ClassNotFoundException, | ||
| SQLException, InstantiationException, IllegalAccessException { | ||
|
|
||
| Class.forName("org.h2.Driver").newInstance(); | ||
| //путь к файлу с БД, соединение с драйверами БД | ||
| connection = DriverManager.getConnection("jdbc:h2:~/test", "test", "test"); | ||
| statement = connection.createStatement(); | ||
|
|
||
| columns = new ArrayList<>(); | ||
| tableClass = elementClass; | ||
| Table table = tableClass.getAnnotation(Table.class); | ||
| if (table == null) { | ||
| throw new IllegalArgumentException("Class should be annotated with Table"); | ||
| } | ||
| tableName = table.name(); | ||
| if (tableName.equals("")) { | ||
| tableName = "MY_TABLE"; | ||
| } | ||
| int i = 0; | ||
| for (Field elem : tableClass.getDeclaredFields()) { | ||
| if (elem.getAnnotation(Column.class) != null) { | ||
| columns.add(elem); | ||
| } | ||
| if (elem.getAnnotation(PrimaryKey.class) != null) { | ||
| if (elem.getAnnotation(Column.class) == null) { | ||
| throw new IllegalArgumentException("Not all fields are columns"); | ||
| } | ||
| if (primaryKey != null) { | ||
| throw new IllegalArgumentException("Not one primary Key"); | ||
| } | ||
| primaryKey = elem; | ||
| primaryKeyFieldNumber = i; | ||
| } | ||
| ++i; | ||
| } | ||
|
|
||
| resultSet = connection.getMetaData().getTables(null, null, | ||
| CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, tableName), null); | ||
| resultSet.next(); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. resultset надо закрывать после использования |
||
| } | ||
| public final <K> T queryById(final K id) throws OperationsException, | ||
| SQLException, IllegalAccessException, InstantiationException { | ||
| if (!hasTableYet) { | ||
| throw new OperationsException("Для данного запроа необходимо создать таблицу"); | ||
| } | ||
| if (primaryKey == null) { | ||
| throw new OperationsException("Должен суущестовать первичный ключ"); | ||
| } | ||
|
|
||
| StringBuilder newRequest = new StringBuilder(); | ||
| newRequest.append("SELECT * FROM ").append(tableName).append(" WHERE ") | ||
| .append(columns.get(primaryKeyFieldNumber).getAnnotation(Column.class) | ||
| .name()).append(" = ").append(id.toString()); | ||
| resultSet = statement.executeQuery(newRequest.toString()); | ||
| List<T> list = new ArrayList<>(); | ||
| while (resultSet.next()) { | ||
| T item = tableClass.newInstance(); | ||
| for (Field field: columns) { | ||
| if (field.getType().equals(Integer.class)) { | ||
| field.set(item, resultSet.getInt(field.getAnnotation(Column.class).name())); | ||
| } | ||
| if (field.getType().equals(String.class)) { | ||
| field.set(item, resultSet.getString(field.getAnnotation(Column.class).name())); | ||
| } | ||
| } | ||
| list.add(item); | ||
| } | ||
| if (list.size() == 0) { | ||
| return null; | ||
| } | ||
| if (list.size() > 1) { | ||
| throw new OperationsException("Ошибка получения результата"); | ||
| } | ||
| return list.get(0); | ||
| } | ||
|
|
||
| final List<T> queryForAll() throws OperationsException, SQLException, IllegalAccessException, | ||
| InstantiationException { | ||
|
|
||
| if (!hasTableYet) { | ||
| throw new OperationsException("Для данного запроа необходимо создать таблицу"); | ||
| } | ||
| if (primaryKey == null) { | ||
| throw new OperationsException("Должен суущестовать первичный ключ"); | ||
| } | ||
| StringBuilder newRequest = new StringBuilder(); | ||
| newRequest.append("SELECT * FROM ").append(tableName); | ||
| resultSet = statement.executeQuery(newRequest.toString()); | ||
| List<T> list = new ArrayList<>(); | ||
| while (resultSet.next()) { | ||
| T item = tableClass.newInstance(); | ||
| for (Field field: columns) { | ||
| if (field.getType().equals(Integer.class)) { | ||
| field.set(item, resultSet.getInt(field.getAnnotation(Column.class).name())); | ||
| } | ||
| if (field.getType().equals(String.class)) { | ||
| field.set(item, resultSet.getString(field.getAnnotation(Column.class).name())); | ||
| } | ||
| } | ||
| list.add(item); | ||
| } | ||
| return list; | ||
| } | ||
|
|
||
| final void insert(final T key) throws SQLException { | ||
| StringBuilder newRequest = new StringBuilder(); | ||
| newRequest.append("INSERT INTO ").append(tableName).append(" VALUES("); | ||
| boolean first = true; | ||
| for (Field field:columns) { | ||
| if (!first) { | ||
| newRequest.append(", "); | ||
| } else { | ||
| first = false; | ||
| } | ||
| newRequest.append("?"); | ||
| } | ||
| newRequest.append(")"); | ||
| //System.out.println(newRequest); | ||
| PreparedStatement preparedStatement = connection.prepareStatement(newRequest.toString()); | ||
|
|
||
| for (int i = 0; i < columns.size(); i++) { | ||
| try { | ||
| preparedStatement.setObject(i + 1, columns.get(i).get(key)); | ||
| } catch (IllegalAccessException e) { | ||
| HandlerOfException.handler(e); | ||
| } | ||
| } | ||
| //System.out.println(preparedStatement.toString()); | ||
| preparedStatement.execute(); | ||
|
|
||
| } | ||
|
|
||
| final void update(final T key) throws SQLException { | ||
| StringBuilder newRequest = new StringBuilder().append("UPDATE ").append(tableName).append(" SET "); | ||
| for (int i = 0; i < columns.size(); ++i) { | ||
| if (i != 0) { | ||
| newRequest.append(", "); | ||
| } | ||
| newRequest.append(columns.get(i).getAnnotation(Column.class).name()).append(" = ?"); | ||
| } | ||
|
|
||
| newRequest.append(" WHERE ").append(columns.get(primaryKeyFieldNumber).getAnnotation(Column.class).name()) | ||
| .append(" = ?"); | ||
| PreparedStatement prepareStatement = connection.prepareStatement(newRequest.toString()); | ||
| for (int i = 0; i < columns.size(); i++) { | ||
| try { | ||
| prepareStatement.setObject(1, columns.get(i).get(key)); | ||
| prepareStatement.setObject(2, columns.get(primaryKeyFieldNumber).get(key)); | ||
| } catch (IllegalAccessException e) { | ||
| HandlerOfException.handler(e); | ||
| } | ||
| prepareStatement.execute(); | ||
| } | ||
|
|
||
|
|
||
|
|
||
| } | ||
|
|
||
|
|
||
| final void delete(final T key) throws SQLException { | ||
| StringBuilder newRequest = new StringBuilder(); | ||
| newRequest.append("DELETE FROM ").append(tableName).append(columns.get(primaryKeyFieldNumber) | ||
| .getAnnotation(Column.class).name()).append(" = ").append("?"); | ||
| PreparedStatement preparedStatement = connection.prepareStatement(newRequest.toString()); | ||
| try { | ||
| preparedStatement.setObject(1, columns.get(primaryKeyFieldNumber).get(key)); | ||
| preparedStatement.execute(); | ||
| } catch (IllegalAccessException e) { | ||
| HandlerOfException.handler(e); | ||
| } | ||
| } | ||
|
|
||
| final void createTable() throws OperationsException, SQLException { | ||
| if (hasTableYet) { | ||
| throw new OperationsException("Невозможно повторно создать таблицу"); | ||
| } | ||
| hasTableYet = true; | ||
| StringBuilder newRequest = new StringBuilder(); | ||
| newRequest.append("CREATE TABLE IF NOT EXISTS ").append(tableName).append(" ("); | ||
| int i = 0; | ||
| for (Field field : columns) { | ||
| //System.out.println(field.getType().toString()); | ||
| if (i != 0) { | ||
| newRequest.append(", "); | ||
| } | ||
| newRequest.append(field.getAnnotation(Column.class).name()).append(" "); | ||
| newRequest.append(ClassConverter.convert(columns.get(i).getType())).append(" "); | ||
| if (field.isAnnotationPresent(PrimaryKey.class)) { | ||
| newRequest.append("PRIMARY KEY"); | ||
| primaryKeyFieldNumber = i; | ||
| } | ||
| i++; | ||
| } | ||
| newRequest.append(") "); | ||
| //System.out.println(newRequest); | ||
| statement.execute(newRequest.toString()); | ||
| } | ||
|
|
||
| final void dropTable() { | ||
| try { | ||
| statement.execute("DROP TABLE IF EXISTS " + tableName); | ||
| hasTableYet = false; | ||
| } catch (SQLException e) { | ||
| HandlerOfException.handler(e); | ||
| } | ||
| } | ||
| } | ||
12 changes: 12 additions & 0 deletions
12
Misha100896/src/main/java/ru/fizteh/fivt/students/miniorm/annotations/Column.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package ru.fizteh.fivt.students.miniorm.annotations; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @Target(value = ElementType.FIELD) | ||
| @Retention(value = RetentionPolicy.RUNTIME) | ||
| public @interface Column { | ||
| String name() default ""; | ||
| } |
11 changes: 11 additions & 0 deletions
11
Misha100896/src/main/java/ru/fizteh/fivt/students/miniorm/annotations/PrimaryKey.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package ru.fizteh.fivt.students.miniorm.annotations; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @Target(value = ElementType.FIELD) | ||
| @Retention(value = RetentionPolicy.RUNTIME) | ||
| public @interface PrimaryKey { | ||
| } |
12 changes: 12 additions & 0 deletions
12
Misha100896/src/main/java/ru/fizteh/fivt/students/miniorm/annotations/Table.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package ru.fizteh.fivt.students.miniorm.annotations; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @Target(value = ElementType.TYPE) | ||
| @Retention(value = RetentionPolicy.RUNTIME) | ||
| public @interface Table { | ||
| String name() default ""; | ||
| } |
23 changes: 23 additions & 0 deletions
23
Misha100896/src/main/java/ru/fizteh/fivt/students/miniorm/exception/HandlerOfException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package ru.fizteh.fivt.students.miniorm.exception; | ||
|
|
||
| public class HandlerOfException { | ||
| static final String USER_MOD = "user"; | ||
|
|
||
| public static void handler(final String message, final Throwable cause) { | ||
| System.err.println(message + ". " + cause.getMessage()); | ||
| System.exit(1); | ||
| } | ||
| public static void handler(final Throwable cause) { | ||
| System.err.println(cause.getMessage()); | ||
| System.exit(1); | ||
| } | ||
|
|
||
| public static void handler(final Throwable cause, final String mod) { | ||
| if (mod.equals(USER_MOD)) { | ||
| System.err.println(cause.getMessage()); | ||
| } else { | ||
| System.err.println(cause.getMessage()); | ||
| System.exit(1); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
statement не стоит переиспользовать, он сразу делает класс непригодным для многопоточного использования