Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
*.properties
.DS_Store
*.txt
*.class
*.jar
*.war
Expand Down
52 changes: 52 additions & 0 deletions Misha100896/pom.xml
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>
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";
}

}
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();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

statement не стоит переиспользовать, он сразу делает класс непригодным для многопоточного использования


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();
Copy link
Owner

Choose a reason for hiding this comment

The 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);
}
}
}
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 "";
}
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 {
}
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 "";
}
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);
}
}
}
Loading