diff --git a/README.md b/README.md index 2117254..bcf1327 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,15 @@ "name" : "H2", "driver" : "org.h2.Driver", "url" : "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", - "username" : "", - "password" : "" + "username" : "****", + "password" : "****" + }, + { + "name" : "ORACLE", + "driver" : "oracle.jdbc.driver.OracleDriver", + "url" : "jdbc:oracle:thin:@server:port:SID", + "username" : "****", + "password" : "****" } ] ``` @@ -25,9 +32,11 @@ @Select(sql = "select * from users") public List fetchAll(); - @Delete(sql = "delete from users where id = ?") + @Delete(sql = "delete from users where id = #{id}") public int delete(int id); + @Insert(sql = "insert into users (firstname, lastname, employee_id) values (#{firstname}, #{lastname}, #{employeeID})") + public int insert(@Param("firstname") String first, @Param("lastname") String last, @Param("employeeID") int id); } ``` @@ -75,7 +84,7 @@ @Delete public int deleteAll(User... users); -@Delete(sql = "delete from users where id = ?") +@Delete(sql = "delete from users where id = #{id}") public int deleteById(int id); ``` @@ -88,8 +97,8 @@ @Update public int updateAll(User... users); -@Update(sql = "update users set firstname = ? where id = ?") -public int updateFirstName(String name, int id); +@Update(sql = "update users set firstname = #{firstname} where id = #{id}") +public int updateFirstName(@Param("firstname") String firstname, @Param("id") int id); ``` Insert @@ -101,8 +110,8 @@ @Insert public int insertAll(User... users); -@Insert(sql = "insert into users (firstname, lastname, employee_id) values (?, ?, ?)") -public int insert(String firstName, String lastName, int employeeID); +@Insert(sql = "insert into users (firstname, lastname, employee_id) values (#{firstname}, #{lastname}, #{employeeID})") +public int insert(@Param("firstname") String first, @Param("lastname") String last, @Param("employeeID") int id); ``` Insert Batch @@ -162,10 +171,10 @@ ** Note: ** Paging can be passed in at any point in the argument list ```java -@Select(sql = "select * from users where lastname = ?") -public findByLastName(Paging paging, String lastName); +@Select(sql = "select * from users where lastname = #{lastname}") +public findByLastName(Paging paging, @Param("lastname") String lastname); // or -public findByLastName(String lastName, Paging paging); +public findByLastName(@Param("lastname") String lastname, Paging paging); ``` diff --git a/src/main/java/com/ljunggren/storm/StormRepository.java b/src/main/java/com/ljunggren/storm/StormRepository.java index d0927cc..2218ba3 100644 --- a/src/main/java/com/ljunggren/storm/StormRepository.java +++ b/src/main/java/com/ljunggren/storm/StormRepository.java @@ -3,6 +3,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.lang.reflect.Parameter; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.Arrays; @@ -21,8 +22,8 @@ import com.ljunggren.storm.crud.QueryChain; import com.ljunggren.storm.crud.SelectQuery; import com.ljunggren.storm.crud.UpdateQuery; -import com.ljunggren.storm.exceptions.StormException; -import com.ljunggren.storm.utils.AnnotationUtils; +import com.ljunggren.storm.exception.StormException; +import com.ljunggren.storm.util.AnnotationUtils; public class StormRepository implements InvocationHandler { @@ -61,8 +62,9 @@ Iterator annotations = Arrays.stream(method.getAnnotations()).iterator(); Type returnType = method.getGenericReturnType(); Object[] argsAsArrays = convertCollectionsToArray(args); + Parameter[] parameters = method.getParameters(); try { - return execute(annotations, argsAsArrays, returnType); + return execute(annotations, parameters, argsAsArrays, returnType); } catch (Exception e) { throw new StormException(e.getMessage()); } @@ -81,10 +83,10 @@ }).toArray(); } - private Object execute(Iterator annotations, Object[] args, Type returnType) throws Exception { + private Object execute(Iterator annotations, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { if (annotations.hasNext()) { - Object object = getQueryChain().execute(annotations.next(), context, args, returnType); - return object == null ? execute(annotations, args, returnType) : object; + Object object = getQueryChain().execute(annotations.next(), context, parameters, arguments, returnType); + return object == null ? execute(annotations, parameters, arguments, returnType) : object; } return null; } diff --git a/src/main/java/com/ljunggren/storm/annotation/Param.java b/src/main/java/com/ljunggren/storm/annotation/Param.java new file mode 100644 index 0000000..dba4c5f --- /dev/null +++ b/src/main/java/com/ljunggren/storm/annotation/Param.java @@ -0,0 +1,14 @@ +package com.ljunggren.storm.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface Param { + + String value(); + +} diff --git a/src/main/java/com/ljunggren/storm/builders/DeleteQueryBuilder.java b/src/main/java/com/ljunggren/storm/builders/DeleteQueryBuilder.java index 44c04c3..1f56845 100644 --- a/src/main/java/com/ljunggren/storm/builders/DeleteQueryBuilder.java +++ b/src/main/java/com/ljunggren/storm/builders/DeleteQueryBuilder.java @@ -5,7 +5,7 @@ import com.ljunggren.reflectionUtils.ReflectionUtils; import com.ljunggren.storm.annotation.entity.Id; -import com.ljunggren.storm.utils.AnnotationUtils; +import com.ljunggren.storm.util.AnnotationUtils; public class DeleteQueryBuilder extends QueryBuilder { diff --git a/src/main/java/com/ljunggren/storm/builders/InsertBatchQueryBuilder.java b/src/main/java/com/ljunggren/storm/builders/InsertBatchQueryBuilder.java index c43cd94..021f3c2 100644 --- a/src/main/java/com/ljunggren/storm/builders/InsertBatchQueryBuilder.java +++ b/src/main/java/com/ljunggren/storm/builders/InsertBatchQueryBuilder.java @@ -6,8 +6,8 @@ import java.util.stream.Collectors; import com.ljunggren.reflectionUtils.ReflectionUtils; -import com.ljunggren.storm.utils.AnnotationUtils; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.AnnotationUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class InsertBatchQueryBuilder extends QueryBuilder { diff --git a/src/main/java/com/ljunggren/storm/builders/InsertQueryBuilder.java b/src/main/java/com/ljunggren/storm/builders/InsertQueryBuilder.java index 2c7c57a..eb34329 100644 --- a/src/main/java/com/ljunggren/storm/builders/InsertQueryBuilder.java +++ b/src/main/java/com/ljunggren/storm/builders/InsertQueryBuilder.java @@ -7,8 +7,8 @@ import org.apache.commons.lang3.StringUtils; import com.ljunggren.reflectionUtils.ReflectionUtils; -import com.ljunggren.storm.utils.AnnotationUtils; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.AnnotationUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class InsertQueryBuilder extends QueryBuilder { diff --git a/src/main/java/com/ljunggren/storm/builders/QueryBuilder.java b/src/main/java/com/ljunggren/storm/builders/QueryBuilder.java index f5a2320..8d3ac8c 100644 --- a/src/main/java/com/ljunggren/storm/builders/QueryBuilder.java +++ b/src/main/java/com/ljunggren/storm/builders/QueryBuilder.java @@ -8,12 +8,12 @@ import com.ljunggren.reflectionUtils.ReflectionUtils; import com.ljunggren.storm.annotation.entity.ColumnProperty; import com.ljunggren.storm.annotation.entity.Table; -import com.ljunggren.storm.utils.AnnotationUtils; +import com.ljunggren.storm.util.AnnotationUtils; public abstract class QueryBuilder { public abstract String buildSQL(); - public abstract Object[] getArgs() throws IllegalAccessException ; + public abstract Object[] getArgs() throws IllegalAccessException; protected String getTableName(Class clazz) { Table table = AnnotationUtils.getAnnotationFromClass(Table.class, clazz); diff --git a/src/main/java/com/ljunggren/storm/builders/UpdateQueryBuilder.java b/src/main/java/com/ljunggren/storm/builders/UpdateQueryBuilder.java index e75e69a..4f3dcb9 100644 --- a/src/main/java/com/ljunggren/storm/builders/UpdateQueryBuilder.java +++ b/src/main/java/com/ljunggren/storm/builders/UpdateQueryBuilder.java @@ -8,8 +8,8 @@ import com.ljunggren.reflectionUtils.ReflectionUtils; import com.ljunggren.storm.annotation.entity.Id; -import com.ljunggren.storm.utils.AnnotationUtils; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.AnnotationUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class UpdateQueryBuilder extends QueryBuilder { diff --git a/src/main/java/com/ljunggren/storm/context/Context.java b/src/main/java/com/ljunggren/storm/context/Context.java index 76c3c3e..504d8ee 100644 --- a/src/main/java/com/ljunggren/storm/context/Context.java +++ b/src/main/java/com/ljunggren/storm/context/Context.java @@ -4,7 +4,7 @@ import java.sql.DriverManager; import java.sql.SQLException; -import com.ljunggren.storm.exceptions.ContextException; +import com.ljunggren.storm.exception.ContextException; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/com/ljunggren/storm/context/ContextFactory.java b/src/main/java/com/ljunggren/storm/context/ContextFactory.java index 7638d68..b753246 100644 --- a/src/main/java/com/ljunggren/storm/context/ContextFactory.java +++ b/src/main/java/com/ljunggren/storm/context/ContextFactory.java @@ -7,8 +7,8 @@ import org.apache.commons.io.IOUtils; import com.fasterxml.jackson.core.JsonProcessingException; -import com.ljunggren.storm.exceptions.ContextException; -import com.ljunggren.storm.utils.JSONUtils; +import com.ljunggren.storm.exception.ContextException; +import com.ljunggren.storm.util.JSONUtils; public class ContextFactory { diff --git a/src/main/java/com/ljunggren/storm/crud/CatchAllQuery.java b/src/main/java/com/ljunggren/storm/crud/CatchAllQuery.java index a2d4535..ba0bf32 100644 --- a/src/main/java/com/ljunggren/storm/crud/CatchAllQuery.java +++ b/src/main/java/com/ljunggren/storm/crud/CatchAllQuery.java @@ -1,6 +1,7 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import com.ljunggren.storm.context.Context; @@ -12,7 +13,7 @@ } @Override - public Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception { + public Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { return null; } diff --git a/src/main/java/com/ljunggren/storm/crud/DeleteQuery.java b/src/main/java/com/ljunggren/storm/crud/DeleteQuery.java index 13700b4..8b31466 100644 --- a/src/main/java/com/ljunggren/storm/crud/DeleteQuery.java +++ b/src/main/java/com/ljunggren/storm/crud/DeleteQuery.java @@ -1,6 +1,7 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.function.Consumer; @@ -11,7 +12,7 @@ import com.ljunggren.storm.builders.DeleteQueryBuilder; import com.ljunggren.storm.builders.QueryBuilder; import com.ljunggren.storm.context.Context; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class DeleteQuery extends QueryChain { @@ -20,16 +21,16 @@ } @Override - public Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception { + public Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { if (annotation.annotationType() == Delete.class) { String sql = ((Delete) annotation).sql(); - return sql.isEmpty() ? executeNonNativeQuery(context, args, returnType) : executeUpdate(sql, context, args, returnType); + return sql.isEmpty() ? executeNonNativeQuery(context, arguments, returnType) : executeUpdate(sql, context, parameters, arguments, returnType); } - return nextChain.execute(annotation, context, args, returnType); + return nextChain.execute(annotation, context, parameters, arguments, returnType); } - private int executeNonNativeQuery(Context context, Object[] args, Type returnType) { - return Arrays.stream(args).map(ExceptionUtils.rethrowFunction(arg -> executeNonNativeQuery(context, arg, returnType))) + private int executeNonNativeQuery(Context context, Object[] arguments, Type returnType) { + return Arrays.stream(arguments).map(ExceptionUtils.rethrowFunction(arg -> executeNonNativeQuery(context, arg, returnType))) .collect(Collectors.summingInt(Integer::intValue)); } @@ -42,5 +43,5 @@ Object[] generatedArgs = queryBuilder.getArgs(); return executeUpdate(sql, context, generatedArgs, returnType); } - + } diff --git a/src/main/java/com/ljunggren/storm/crud/InsertBatchQuery.java b/src/main/java/com/ljunggren/storm/crud/InsertBatchQuery.java index c34bbcb..6a429cb 100644 --- a/src/main/java/com/ljunggren/storm/crud/InsertBatchQuery.java +++ b/src/main/java/com/ljunggren/storm/crud/InsertBatchQuery.java @@ -1,6 +1,7 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.function.Consumer; @@ -10,7 +11,7 @@ import com.ljunggren.storm.builders.InsertBatchQueryBuilder; import com.ljunggren.storm.builders.QueryBuilder; import com.ljunggren.storm.context.Context; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class InsertBatchQuery extends QueryChain { @@ -19,11 +20,11 @@ } @Override - public Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception { + public Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { if (annotation.annotationType() == InsertBatch.class) { - return executeNonNativeQuery(context, args, returnType); + return executeNonNativeQuery(context, arguments, returnType); } - return nextChain.execute(annotation, context, args, returnType); + return nextChain.execute(annotation, context, parameters, arguments, returnType); } private int executeNonNativeQuery(Context context, Object[] args, Type returnType) { diff --git a/src/main/java/com/ljunggren/storm/crud/InsertQuery.java b/src/main/java/com/ljunggren/storm/crud/InsertQuery.java index 3925b89..42aefac 100644 --- a/src/main/java/com/ljunggren/storm/crud/InsertQuery.java +++ b/src/main/java/com/ljunggren/storm/crud/InsertQuery.java @@ -1,6 +1,7 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.function.Consumer; @@ -11,7 +12,7 @@ import com.ljunggren.storm.builders.InsertQueryBuilder; import com.ljunggren.storm.builders.QueryBuilder; import com.ljunggren.storm.context.Context; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class InsertQuery extends QueryChain { @@ -20,12 +21,12 @@ } @Override - public Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception { + public Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { if (annotation.annotationType() == Insert.class) { String sql = ((Insert) annotation).sql(); - return sql.isEmpty() ? executeNonNativeQuery(context, args, returnType) : executeUpdate(sql, context, args, returnType); + return sql.isEmpty() ? executeNonNativeQuery(context, arguments, returnType) : executeUpdate(sql, context, parameters, arguments, returnType); } - return nextChain.execute(annotation, context, args, returnType); + return nextChain.execute(annotation, context, parameters, arguments, returnType); } private int executeNonNativeQuery(Context context, Object[] args, Type returnType) { @@ -33,11 +34,11 @@ .collect(Collectors.summingInt(Integer::intValue)); } - private int executeNonNativeQuery(Context context, Object arg, Type returnType) throws Exception { - if (ReflectionUtils.isArray(arg.getClass())) { - return executeNonNativeQuery(context, (Object[]) arg, returnType); + private int executeNonNativeQuery(Context context, Object arguments, Type returnType) throws Exception { + if (ReflectionUtils.isArray(arguments.getClass())) { + return executeNonNativeQuery(context, (Object[]) arguments, returnType); } - QueryBuilder queryBuilder = new InsertQueryBuilder(arg); + QueryBuilder queryBuilder = new InsertQueryBuilder(arguments); String sql = queryBuilder.buildSQL(); Object[] generatedArgs = queryBuilder.getArgs(); return executeUpdate(sql, context, generatedArgs, returnType); diff --git a/src/main/java/com/ljunggren/storm/crud/QueryChain.java b/src/main/java/com/ljunggren/storm/crud/QueryChain.java index e0e9780..7519a27 100644 --- a/src/main/java/com/ljunggren/storm/crud/QueryChain.java +++ b/src/main/java/com/ljunggren/storm/crud/QueryChain.java @@ -1,16 +1,21 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.List; +import java.util.Map; import java.util.function.Consumer; import java.util.stream.IntStream; import com.ljunggren.storm.context.Context; +import com.ljunggren.storm.exception.StormException; import com.ljunggren.storm.mapper.ResultSetMapper; +import com.ljunggren.storm.util.ParameterUtils; public abstract class QueryChain { @@ -27,15 +32,15 @@ return this; } - public abstract Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception; - protected Object executeQuery(String sql, Context context, Object[] args, Type returnType) throws Exception { + public abstract Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception; + + protected Object executeQuery(String sql, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = context.getConnection(); - preparedStatement = connection.prepareStatement(sql); - setParameters(preparedStatement, args); + preparedStatement = generatePreparedStatement(connection, sql, parameters, arguments); ResultSet resultSet = preparedStatement.executeQuery(); return new ResultSetMapper(resultSet, returnType).map(); } finally { @@ -46,13 +51,12 @@ } } - protected int executeUpdate(String sql, Context context, Object[] args, Type returnType) throws SQLException { + protected int executeUpdate(String sql, Context context, Object[] arguments, Type returnType) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = context.getConnection(); - preparedStatement = connection.prepareStatement(sql); - setParameters(preparedStatement, args); + preparedStatement = generatePreparedStatement(connection, sql, arguments); return preparedStatement.executeUpdate(); } finally { if (peek != null) { @@ -62,15 +66,61 @@ } } - protected int executeBatch(String sql, Context context, Object[] argsArray, Type returnType) throws SQLException { + protected int executeUpdate(String sql, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = context.getConnection(); - preparedStatement = connection.prepareStatement(sql); - for (Object args: argsArray) { + preparedStatement = generatePreparedStatement(connection, sql, parameters, arguments); + return preparedStatement.executeUpdate(); + } finally { + if (peek != null) { + peek.accept(preparedStatement.toString()); + } + closeConnection(connection); + } + } + + private PreparedStatement generatePreparedStatement(Connection connection, String sql, Object[] arguments) throws SQLException { + PreparedStatement preparedStatement = connection.prepareStatement(sql); + if (arguments == null) { + return preparedStatement; + } + for (int i = 0; i < arguments.length; i++) { + preparedStatement.setObject(i + 1, arguments[i]); + } + return preparedStatement; + } + + private PreparedStatement generatePreparedStatement(Connection connection, String sql, Parameter[] parameters, Object[] arguments) throws SQLException { + List parameterIds = ParameterUtils.findParameterIds(sql); + String preparedSql = ParameterUtils.replaceParamaterIdsWithQuestionMarks(sql); + PreparedStatement preparedStatement = connection.prepareStatement(preparedSql); + Map parameterArgumentMap = ParameterUtils.mapArgumentsToParameterNames(parameters, arguments); + if (parameterArgumentMap.isEmpty() && parameters.length == 1) { + preparedStatement.setObject(1, arguments[0]); + return preparedStatement; + } + if (parameterArgumentMap.isEmpty() && parameters.length > 1) { + throw new StormException("Multiple Storm parameters must be annotated with @Param"); + } + for (int i = 0; i < parameterIds.size(); i++) { + preparedStatement.setObject(i + 1, parameterArgumentMap.get(parameterIds.get(i))); + } + return preparedStatement; + } + + + protected int executeBatch(String sql, Context context, Object[] argumentArray, Type returnType) throws SQLException { + Connection connection = null; + PreparedStatement preparedStatement = null; + try { + connection = context.getConnection(); + String preparedSql = ParameterUtils.replaceParamaterIdsWithQuestionMarks(sql); + preparedStatement = connection.prepareStatement(preparedSql); + for (Object arguments: argumentArray) { // TODO: Refactor so args does not have to be cast to array - setParameters(preparedStatement, (Object[]) args); + setParameters(preparedStatement, (Object[]) arguments); preparedStatement.addBatch(); if (peek != null) { peek.accept(preparedStatement.toString()); @@ -82,7 +132,7 @@ closeConnection(connection); } } - + private void setParameters(PreparedStatement preparedStatement, Object[] args) throws SQLException { if (args != null) { for (int i = 0; i < args.length; i++) { diff --git a/src/main/java/com/ljunggren/storm/crud/SelectQuery.java b/src/main/java/com/ljunggren/storm/crud/SelectQuery.java index 14c3e35..f4da4d8 100644 --- a/src/main/java/com/ljunggren/storm/crud/SelectQuery.java +++ b/src/main/java/com/ljunggren/storm/crud/SelectQuery.java @@ -1,6 +1,7 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.function.Consumer; @@ -18,29 +19,31 @@ } @Override - public Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception { + public Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { if (annotation.annotationType() == Select.class) { String sql = ((Select) annotation).sql(); - Paging paging = findPaging(args); - return paging == null ? executeQuery(sql, context, args, returnType) : executePagedQuery(sql, context, args, returnType, paging); + Paging paging = findPaging(arguments); + return paging == null ? executeQuery(sql, context, parameters, arguments, returnType) : + executePagedQuery(sql, context, parameters, arguments, returnType, paging); } - return nextChain.execute(annotation, context, args, returnType); + return nextChain.execute(annotation, context, parameters, arguments, returnType); } - private Paging findPaging(Object[] args) { - if (args == null) { + private Paging findPaging(Object[] arguments) { + if (arguments == null) { return null; } - return (Paging) Arrays.stream(args).filter(arg -> arg.getClass() == Paging.class) + return (Paging) Arrays.stream(arguments).filter(argument -> argument.getClass() == Paging.class) .findFirst() .orElse(null); } - private Object executePagedQuery(String sql, Context context, Object[] args, Type returnType, Paging paging) throws Exception { - QueryBuilder queryBuilder = new PagingQueryBuilder(sql, args, paging); + private Object executePagedQuery(String sql, Context context, Parameter[] parameters, Object[] arguments, Type returnType, Paging paging) throws Exception { + parameters = Arrays.stream(parameters).filter(parameter -> parameter.getType() != Paging.class).toArray(Parameter[]::new); + arguments = Arrays.stream(arguments).filter(argument -> argument.getClass() != Paging.class).toArray(Object[]::new); + QueryBuilder queryBuilder = new PagingQueryBuilder(sql, arguments, paging); String pagingSQL = queryBuilder.buildSQL(); - Object[] generatedArgs = queryBuilder.getArgs(); - return executeQuery(pagingSQL, context, generatedArgs, returnType); + return executeQuery(pagingSQL, context, parameters, arguments, returnType); } } diff --git a/src/main/java/com/ljunggren/storm/crud/UpdateQuery.java b/src/main/java/com/ljunggren/storm/crud/UpdateQuery.java index 1a42ea8..d5dbf3a 100644 --- a/src/main/java/com/ljunggren/storm/crud/UpdateQuery.java +++ b/src/main/java/com/ljunggren/storm/crud/UpdateQuery.java @@ -1,6 +1,7 @@ package com.ljunggren.storm.crud; import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.function.Consumer; @@ -11,7 +12,7 @@ import com.ljunggren.storm.builders.QueryBuilder; import com.ljunggren.storm.builders.UpdateQueryBuilder; import com.ljunggren.storm.context.Context; -import com.ljunggren.storm.utils.ExceptionUtils; +import com.ljunggren.storm.util.ExceptionUtils; public class UpdateQuery extends QueryChain { @@ -20,24 +21,25 @@ } @Override - public Object execute(Annotation annotation, Context context, Object[] args, Type returnType) throws Exception { + public Object execute(Annotation annotation, Context context, Parameter[] parameters, Object[] arguments, Type returnType) throws Exception { if (annotation.annotationType() == Update.class) { String sql = ((Update) annotation).sql(); - return sql.isEmpty() ? executeNonNativeQuery(context, args, returnType) : executeUpdate(sql, context, args, returnType); + return sql.isEmpty() ? executeNonNativeQuery(context, arguments, returnType) : + executeUpdate(sql, context, parameters, arguments, returnType); } - return nextChain.execute(annotation, context, args, returnType); + return nextChain.execute(annotation, context, parameters, arguments, returnType); } - private int executeNonNativeQuery(Context context, Object[] args, Type returnType) { - return Arrays.stream(args).map(ExceptionUtils.rethrowFunction(arg -> executeNonNativeQuery(context, arg, returnType))) + private int executeNonNativeQuery(Context context, Object[] arguments, Type returnType) { + return Arrays.stream(arguments).map(ExceptionUtils.rethrowFunction(argument -> executeNonNativeQuery(context, argument, returnType))) .collect(Collectors.summingInt(Integer::intValue)); } - private int executeNonNativeQuery(Context context, Object arg, Type returnType) throws Exception { - if (ReflectionUtils.isArray(arg.getClass())) { - return executeNonNativeQuery(context, (Object[]) arg, returnType); + private int executeNonNativeQuery(Context context, Object argument, Type returnType) throws Exception { + if (ReflectionUtils.isArray(argument.getClass())) { + return executeNonNativeQuery(context, (Object[]) argument, returnType); } - QueryBuilder queryBuilder = new UpdateQueryBuilder(arg); + QueryBuilder queryBuilder = new UpdateQueryBuilder(argument); String sql = queryBuilder.buildSQL(); Object[] generatedArgs = queryBuilder.getArgs(); return executeUpdate(sql, context, generatedArgs, returnType); diff --git a/src/main/java/com/ljunggren/storm/exception/ContextException.java b/src/main/java/com/ljunggren/storm/exception/ContextException.java new file mode 100644 index 0000000..0beceab --- /dev/null +++ b/src/main/java/com/ljunggren/storm/exception/ContextException.java @@ -0,0 +1,11 @@ +package com.ljunggren.storm.exception; + +public class ContextException extends RuntimeException { + + private static final long serialVersionUID = 3884552155337373601L; + + public ContextException(String message) { + super(message); + } + +} diff --git a/src/main/java/com/ljunggren/storm/exception/StormException.java b/src/main/java/com/ljunggren/storm/exception/StormException.java new file mode 100644 index 0000000..692ef3b --- /dev/null +++ b/src/main/java/com/ljunggren/storm/exception/StormException.java @@ -0,0 +1,11 @@ +package com.ljunggren.storm.exception; + +public class StormException extends RuntimeException { + + private static final long serialVersionUID = 1478572986254603169L; + + public StormException(String message) { + super(message); + } + +} diff --git a/src/main/java/com/ljunggren/storm/exceptions/ContextException.java b/src/main/java/com/ljunggren/storm/exceptions/ContextException.java deleted file mode 100644 index e91346c..0000000 --- a/src/main/java/com/ljunggren/storm/exceptions/ContextException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ljunggren.storm.exceptions; - -public class ContextException extends RuntimeException { - - private static final long serialVersionUID = 3884552155337373601L; - - public ContextException(String message) { - super(message); - } - -} diff --git a/src/main/java/com/ljunggren/storm/exceptions/StormException.java b/src/main/java/com/ljunggren/storm/exceptions/StormException.java deleted file mode 100644 index b126ad6..0000000 --- a/src/main/java/com/ljunggren/storm/exceptions/StormException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ljunggren.storm.exceptions; - -public class StormException extends RuntimeException { - - private static final long serialVersionUID = 1478572986254603169L; - - public StormException(String message) { - super(message); - } - -} diff --git a/src/main/java/com/ljunggren/storm/mapper/MapperChain.java b/src/main/java/com/ljunggren/storm/mapper/MapperChain.java index 6b44f0a..1873705 100644 --- a/src/main/java/com/ljunggren/storm/mapper/MapperChain.java +++ b/src/main/java/com/ljunggren/storm/mapper/MapperChain.java @@ -12,7 +12,7 @@ import com.ljunggren.reflectionUtils.ReflectionUtils; import com.ljunggren.storm.annotation.entity.ColumnProperty; -import com.ljunggren.storm.utils.AnnotationUtils; +import com.ljunggren.storm.util.AnnotationUtils; public abstract class MapperChain { diff --git a/src/main/java/com/ljunggren/storm/util/AnnotationUtils.java b/src/main/java/com/ljunggren/storm/util/AnnotationUtils.java new file mode 100644 index 0000000..f77e9b4 --- /dev/null +++ b/src/main/java/com/ljunggren/storm/util/AnnotationUtils.java @@ -0,0 +1,52 @@ +package com.ljunggren.storm.util; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; + +import com.ljunggren.storm.annotation.entity.Id; +import com.ljunggren.storm.annotation.entity.Transient; +import com.ljunggren.storm.entity.Generated; + +public class AnnotationUtils { + + @SuppressWarnings("unchecked") + public static T findFieldByAnnotation(Class annotationClazz, List fields) { + return (T) fields.stream() + .filter(field -> AnnotationUtils.getAnnotationFromField(Id.class, field) != null) + .findFirst() + .orElse(null); + } + + @SuppressWarnings("unchecked") + public static T getAnnotationFromField(Class annotationClazz, Field field) { + return (T) Arrays.stream(field.getAnnotations()) + .filter(annotation -> annotation.annotationType() == annotationClazz) + .findFirst() + .orElse(null); + } + + @SuppressWarnings("unchecked") + public static T getAnnotationFromClass(Class annotationClazz, Class clazz) { + return (T) Arrays.stream(clazz.getAnnotations()) + .filter(annotation -> annotation.annotationType() == annotationClazz) + .findFirst() + .orElse(null); + } + + public static boolean isAutoGeneratedId(Field field) { + if (field == null) { + return false; + } + Id id = getAnnotationFromField(Id.class, field); + if (id == null) { + return false; + } + return id.generated() == Generated.AUTO; + } + + public static boolean isTransient(Field field) { + return getAnnotationFromField(Transient.class, field) != null; + } + +} diff --git a/src/main/java/com/ljunggren/storm/util/ExceptionUtils.java b/src/main/java/com/ljunggren/storm/util/ExceptionUtils.java new file mode 100644 index 0000000..e6113b5 --- /dev/null +++ b/src/main/java/com/ljunggren/storm/util/ExceptionUtils.java @@ -0,0 +1,22 @@ +package com.ljunggren.storm.util; + +import java.util.function.Function; + +public class ExceptionUtils { + + @FunctionalInterface + public interface FunctionWithException { + R apply(T t) throws E; + } + + public static Function rethrowFunction(FunctionWithException fe) { + return arg -> { + try { + return fe.apply(arg); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + +} diff --git a/src/main/java/com/ljunggren/storm/util/JSONUtils.java b/src/main/java/com/ljunggren/storm/util/JSONUtils.java new file mode 100644 index 0000000..29561a9 --- /dev/null +++ b/src/main/java/com/ljunggren/storm/util/JSONUtils.java @@ -0,0 +1,40 @@ +package com.ljunggren.storm.util; + +import java.io.IOException; +import java.util.List; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JSONUtils { + + public static boolean isValidJSON(String json) { + if (json == null) { + return false; + } + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(json); + return true; + } catch (IOException e) { + return false; + } + } + + public static String objectToJson(Object object) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + String json = ""; + json = mapper.writeValueAsString(object); + return json; + } + + @SuppressWarnings("rawtypes") + public static T jsonToListObject(String json, Class clazz) throws JsonMappingException, JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, clazz); + return mapper.readValue(json, type); + } + +} diff --git a/src/main/java/com/ljunggren/storm/util/ParameterUtils.java b/src/main/java/com/ljunggren/storm/util/ParameterUtils.java new file mode 100644 index 0000000..016756c --- /dev/null +++ b/src/main/java/com/ljunggren/storm/util/ParameterUtils.java @@ -0,0 +1,56 @@ +package com.ljunggren.storm.util; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Parameter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.IntStream; + +import com.ljunggren.storm.annotation.Param; + +public class ParameterUtils { + + private final static String parameterRegex = "#\\{[a-zA-Z0-9_]+\\}"; + + public static Map mapArgumentsToParameterNames(Parameter[] parameters, Object[] arguments) { + String[] parameterNames = getParameterNames(parameters); + return IntStream.range(0, parameterNames.length) + .collect(HashMap::new, (m, i) -> m.put(parameterNames[i], arguments[i]), Map::putAll); + } + + public static String[] getParameterNames(Parameter[] parameters) { + return Arrays.stream(parameters) + .map(parameter -> getParameterName(parameter)) + .filter(name -> null != name) + .toArray(String[]::new); + } + + public static String getParameterName(Parameter parameter) { + Annotation[] annotations = parameter.getAnnotations(); + return Arrays.stream(annotations) + .filter(annotation -> annotation.annotationType() == Param.class) + .map(annotation -> ((Param) annotation).value()) + .findFirst() + .orElse(null); + } + + public static List findParameterIds(String sql) { + List parameterIds = new ArrayList<>(); + Pattern pattern = Pattern.compile(parameterRegex); + Matcher matcher = pattern.matcher(sql); + while (matcher.find()) { + parameterIds.add(matcher.group(0).replace("#{", "").replace("}", "")); + } + return parameterIds; + } + + public static String replaceParamaterIdsWithQuestionMarks(String sql) { + return sql.replaceAll(parameterRegex, "?"); + } + +} diff --git a/src/main/java/com/ljunggren/storm/utils/AnnotationUtils.java b/src/main/java/com/ljunggren/storm/utils/AnnotationUtils.java deleted file mode 100644 index d9c0e05..0000000 --- a/src/main/java/com/ljunggren/storm/utils/AnnotationUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.ljunggren.storm.utils; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.List; - -import com.ljunggren.storm.annotation.entity.Id; -import com.ljunggren.storm.annotation.entity.Transient; -import com.ljunggren.storm.entity.Generated; - -public class AnnotationUtils { - - @SuppressWarnings("unchecked") - public static T findFieldByAnnotation(Class annotationClazz, List fields) { - return (T) fields.stream() - .filter(field -> AnnotationUtils.getAnnotationFromField(Id.class, field) != null) - .findFirst() - .orElse(null); - } - - @SuppressWarnings("unchecked") - public static T getAnnotationFromField(Class annotationClazz, Field field) { - return (T) Arrays.stream(field.getAnnotations()) - .filter(annotation -> annotation.annotationType() == annotationClazz) - .findFirst() - .orElse(null); - } - - @SuppressWarnings("unchecked") - public static T getAnnotationFromClass(Class annotationClazz, Class clazz) { - return (T) Arrays.stream(clazz.getAnnotations()) - .filter(annotation -> annotation.annotationType() == annotationClazz) - .findFirst() - .orElse(null); - } - - public static boolean isAutoGeneratedId(Field field) { - if (field == null) { - return false; - } - Id id = getAnnotationFromField(Id.class, field); - if (id == null) { - return false; - } - return id.generated() == Generated.AUTO; - } - - public static boolean isTransient(Field field) { - return getAnnotationFromField(Transient.class, field) != null; - } - -} diff --git a/src/main/java/com/ljunggren/storm/utils/ExceptionUtils.java b/src/main/java/com/ljunggren/storm/utils/ExceptionUtils.java deleted file mode 100644 index 31ab2f9..0000000 --- a/src/main/java/com/ljunggren/storm/utils/ExceptionUtils.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ljunggren.storm.utils; - -import java.util.function.Function; - -public class ExceptionUtils { - - @FunctionalInterface - public interface FunctionWithException { - R apply(T t) throws E; - } - - public static Function rethrowFunction(FunctionWithException fe) { - return arg -> { - try { - return fe.apply(arg); - } catch (Exception e) { - throw new RuntimeException(e); - } - }; - } - -} diff --git a/src/main/java/com/ljunggren/storm/utils/JSONUtils.java b/src/main/java/com/ljunggren/storm/utils/JSONUtils.java deleted file mode 100644 index 068ae1a..0000000 --- a/src/main/java/com/ljunggren/storm/utils/JSONUtils.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ljunggren.storm.utils; - -import java.io.IOException; -import java.util.List; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JSONUtils { - - public static boolean isValidJSON(String json) { - if (json == null) { - return false; - } - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(json); - return true; - } catch (IOException e) { - return false; - } - } - - public static String objectToJson(Object object) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - String json = ""; - json = mapper.writeValueAsString(object); - return json; - } - - @SuppressWarnings("rawtypes") - public static T jsonToListObject(String json, Class clazz) throws JsonMappingException, JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, clazz); - return mapper.readValue(json, type); - } - -} diff --git a/src/test/java/com/ljunggren/storm/context/ContextFactoryTest.java b/src/test/java/com/ljunggren/storm/context/ContextFactoryTest.java index e017572..9ee6f0c 100644 --- a/src/test/java/com/ljunggren/storm/context/ContextFactoryTest.java +++ b/src/test/java/com/ljunggren/storm/context/ContextFactoryTest.java @@ -4,7 +4,7 @@ import org.junit.Test; -import com.ljunggren.storm.exceptions.ContextException; +import com.ljunggren.storm.exception.ContextException; public class ContextFactoryTest { diff --git a/src/test/java/com/ljunggren/storm/context/ContextTest.java b/src/test/java/com/ljunggren/storm/context/ContextTest.java index 597cb29..4457457 100644 --- a/src/test/java/com/ljunggren/storm/context/ContextTest.java +++ b/src/test/java/com/ljunggren/storm/context/ContextTest.java @@ -7,7 +7,7 @@ import org.junit.Test; -import com.ljunggren.storm.exceptions.ContextException; +import com.ljunggren.storm.exception.ContextException; public class ContextTest { diff --git a/src/test/java/com/ljunggren/storm/crud/DeleteQueryTest.java b/src/test/java/com/ljunggren/storm/crud/DeleteQueryTest.java index 8632e19..f21cdb8 100644 --- a/src/test/java/com/ljunggren/storm/crud/DeleteQueryTest.java +++ b/src/test/java/com/ljunggren/storm/crud/DeleteQueryTest.java @@ -14,18 +14,19 @@ import com.ljunggren.storm.StormRepository; import com.ljunggren.storm.TestUser; import com.ljunggren.storm.annotation.Database; +import com.ljunggren.storm.annotation.Param; import com.ljunggren.storm.annotation.crud.Delete; import com.ljunggren.storm.annotation.crud.Select; import com.ljunggren.storm.context.Context; import com.ljunggren.storm.context.ContextFactory; -import com.ljunggren.storm.exceptions.StormException; +import com.ljunggren.storm.exception.StormException; public class DeleteQueryTest { @Database("H2") private interface UserRepository extends Peek { - @Delete(sql = "delete from users where id = ?") + @Delete(sql = "delete from users where id = #{id}") public int deleteById(int id); @Delete @@ -40,8 +41,8 @@ @Select(sql = "select count(*) from users") public long count(); - @Select(sql = "select * from users where id = ?") - public TestUser findById(int id); + @Select(sql = "select * from users where id = #{id}") + public TestUser findById(@Param("id") int id); } diff --git a/src/test/java/com/ljunggren/storm/crud/InsertQueryTest.java b/src/test/java/com/ljunggren/storm/crud/InsertQueryTest.java index 8fa0036..de9a9d0 100644 --- a/src/test/java/com/ljunggren/storm/crud/InsertQueryTest.java +++ b/src/test/java/com/ljunggren/storm/crud/InsertQueryTest.java @@ -14,19 +14,20 @@ import com.ljunggren.storm.StormRepository; import com.ljunggren.storm.TestUser; import com.ljunggren.storm.annotation.Database; +import com.ljunggren.storm.annotation.Param; import com.ljunggren.storm.annotation.crud.Insert; import com.ljunggren.storm.annotation.crud.Select; import com.ljunggren.storm.context.Context; import com.ljunggren.storm.context.ContextFactory; -import com.ljunggren.storm.exceptions.StormException; +import com.ljunggren.storm.exception.StormException; public class InsertQueryTest { @Database("H2") private interface UserRepository extends Peek { - @Insert(sql = "insert into users (firstname, lastname, employee_id) values (?, ?, ?)") - public int insert(String firstName, String lastName, int employeeID); + @Insert(sql = "insert into users (firstname, lastname, employee_id) values (#{firstname}, #{lastname}, #{employeeID})") + public int insert(@Param("firstname") String firstname, @Param("lastname") String lastname, @Param("employeeID") int employeeID); @Insert public int insert(TestUser user); diff --git a/src/test/java/com/ljunggren/storm/crud/SelectQueryTest.java b/src/test/java/com/ljunggren/storm/crud/SelectQueryTest.java index bf4f31f..6e000f7 100644 --- a/src/test/java/com/ljunggren/storm/crud/SelectQueryTest.java +++ b/src/test/java/com/ljunggren/storm/crud/SelectQueryTest.java @@ -18,10 +18,11 @@ import com.ljunggren.storm.StormRepository; import com.ljunggren.storm.TestUser; import com.ljunggren.storm.annotation.Database; +import com.ljunggren.storm.annotation.Param; import com.ljunggren.storm.annotation.crud.Select; import com.ljunggren.storm.context.Context; import com.ljunggren.storm.context.ContextFactory; -import com.ljunggren.storm.exceptions.StormException; +import com.ljunggren.storm.exception.StormException; public class SelectQueryTest { @@ -34,17 +35,17 @@ @Select(sql = "select * from users order by id") public TestUser[] fetchAllOrdered(Paging paging); - @Select(sql = "select * from users where lastname = ?") - public List findByLastName(String lastName, Paging paging); + @Select(sql = "select * from users where lastname = #{lastname}") + public List findByLastName(@Param("lastname") String lastname, Paging paging); - @Select(sql = "select * from users where lastname = ?") - public List findByLastName(Paging paging, String lastName); + @Select(sql = "select * from users where lastname = #{lastname}") + public List findByLastName(Paging paging, @Param("lastname") String lastname); - @Select(sql = "select * from users where id = ?") + @Select(sql = "select * from users where id = #{id}") public TestUser findById(int id); - @Select(sql = "select * from users where firstname = ? and lastname = ?") - public TestUser findByFirstAndLastName(String firstName, String lastName); + @Select(sql = "select * from users where firstname = #{firstname} and lastname = #{lastname}") + public TestUser findByFirstAndLastName(@Param("firstname") String firstname, @Param("lastname") String lastname); @Select(sql = "select count(*) from users") public long count(); diff --git a/src/test/java/com/ljunggren/storm/crud/UpdateQueryTest.java b/src/test/java/com/ljunggren/storm/crud/UpdateQueryTest.java index 16fbdef..237918a 100644 --- a/src/test/java/com/ljunggren/storm/crud/UpdateQueryTest.java +++ b/src/test/java/com/ljunggren/storm/crud/UpdateQueryTest.java @@ -14,19 +14,20 @@ import com.ljunggren.storm.StormRepository; import com.ljunggren.storm.TestUser; import com.ljunggren.storm.annotation.Database; +import com.ljunggren.storm.annotation.Param; import com.ljunggren.storm.annotation.crud.Select; import com.ljunggren.storm.annotation.crud.Update; import com.ljunggren.storm.context.Context; import com.ljunggren.storm.context.ContextFactory; -import com.ljunggren.storm.exceptions.StormException; +import com.ljunggren.storm.exception.StormException; public class UpdateQueryTest { @Database("H2") private interface UserRepository extends Peek { - @Update(sql = "update users set firstname = ? where id = ?") - public int updateFirstName(String name, int id); + @Update(sql = "update users set firstname = #{firstname} where id = #{id}") + public int updateFirstName(@Param("firstname") String firstname, @Param("id") int id); @Update public int update(TestUser user); @@ -37,7 +38,7 @@ @Update(sql = "nonsense") public int nonsense(); - @Select(sql = "select * from users where id = ?") + @Select(sql = "select * from users where id = #{id}") public TestUser findById(int id); } diff --git a/src/test/java/com/ljunggren/storm/util/AnnotationUtilsTest.java b/src/test/java/com/ljunggren/storm/util/AnnotationUtilsTest.java new file mode 100644 index 0000000..374223d --- /dev/null +++ b/src/test/java/com/ljunggren/storm/util/AnnotationUtilsTest.java @@ -0,0 +1,103 @@ +package com.ljunggren.storm.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.List; + +import org.junit.Test; + +import com.ljunggren.reflectionUtils.ReflectionUtils; +import com.ljunggren.storm.TestUser; +import com.ljunggren.storm.annotation.Database; +import com.ljunggren.storm.annotation.entity.Id; +import com.ljunggren.storm.annotation.entity.Table; +import com.ljunggren.storm.annotation.entity.Transient; +import com.ljunggren.storm.context.Context; +import com.ljunggren.storm.entity.Generated; + +import lombok.Data; + +public class AnnotationUtilsTest { + + @Data + private class TestId { + + @Id(generated = Generated.NONE) + private int id; + + } + + @Test + public void instantiationTest() { + AnnotationUtils annotationUtils = new AnnotationUtils(); + assertTrue(annotationUtils instanceof AnnotationUtils); + } + + @Test + public void findFieldByAnnotationTest() { + List fields = ReflectionUtils.getObjectFields(TestUser.class); + Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); + assertTrue(field != null); + } + + @Test + public void findFieldByAnnotationNoFieldTest() { + List fields = ReflectionUtils.getObjectFields(Context.class); + Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); + assertTrue(field == null); + } + + @Test + public void getAnnotationFromFieldTest() { + List fields = ReflectionUtils.getObjectFields(TestUser.class); + Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); + Annotation annotation = AnnotationUtils.getAnnotationFromField(Id.class, field); + assertTrue(annotation instanceof Id); + } + + @Test + public void getAnnotationFromFieldNoAnnotationTest() { + List fields = ReflectionUtils.getObjectFields(TestUser.class); + Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); + Annotation annotation = AnnotationUtils.getAnnotationFromField(Database.class, field); + assertTrue(annotation == null); + } + + @Test + public void getAnnotationFromClassTest() { + Annotation annotation = AnnotationUtils.getAnnotationFromClass(Table.class, TestUser.class); + assertTrue(annotation instanceof Table); + } + + @Test + public void getAnnotationFromClassNoAnnotationTest() { + Annotation annotation = AnnotationUtils.getAnnotationFromClass(Transient.class, TestUser.class); + assertTrue(annotation == null); + } + + @Test + public void isAutoGeneratedIdTest() { + List fields = ReflectionUtils.getObjectFields(TestUser.class); + Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); + boolean isAutogenerated = AnnotationUtils.isAutoGeneratedId(field); + assertTrue(isAutogenerated); + } + + @Test + public void isAutoGeneratedIdNotGeneratedTest() { + List fields = ReflectionUtils.getObjectFields(TestId.class); + Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); + boolean isAutogenerated = AnnotationUtils.isAutoGeneratedId(field); + assertFalse(isAutogenerated); + } + + @Test + public void isAutoGeneratedIdNullTest() { + boolean isAutogenerated = AnnotationUtils.isAutoGeneratedId(null); + assertFalse(isAutogenerated); + } + +} diff --git a/src/test/java/com/ljunggren/storm/util/ExceptionUtilsTest.java b/src/test/java/com/ljunggren/storm/util/ExceptionUtilsTest.java new file mode 100644 index 0000000..85ade48 --- /dev/null +++ b/src/test/java/com/ljunggren/storm/util/ExceptionUtilsTest.java @@ -0,0 +1,34 @@ +package com.ljunggren.storm.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class ExceptionUtilsTest { + + @Test + public void instantiationTest() { + ExceptionUtils exceptionUtils = new ExceptionUtils(); + assertTrue(exceptionUtils instanceof ExceptionUtils); + } + + @Test + public void rethrowFunctionTest() { + int sum = Arrays.stream(new Integer[] {1, 1}) + .map(ExceptionUtils.rethrowFunction(value -> 1/value)) + .collect(Collectors.summingInt(Integer::intValue)); + assertEquals(2, sum); + } + + @Test(expected = Exception.class) + public void rethrowFunctionThrowTest() { + Arrays.stream(new Integer[] {0, 1}) + .map(ExceptionUtils.rethrowFunction(value -> 1/value)) + .collect(Collectors.summingInt(Integer::intValue)); + } + +} diff --git a/src/test/java/com/ljunggren/storm/util/JSONUtilsTest.java b/src/test/java/com/ljunggren/storm/util/JSONUtilsTest.java new file mode 100644 index 0000000..bac8796 --- /dev/null +++ b/src/test/java/com/ljunggren/storm/util/JSONUtilsTest.java @@ -0,0 +1,78 @@ +package com.ljunggren.storm.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.ljunggren.storm.TestUser; + +public class JSONUtilsTest { + + private TestUser getUser() { + TestUser user = new TestUser(); + user.setFirstName("Alex"); + user.setEmployeeID(100); + return user; + } + + @Test + public void instantiationTest() { + JSONUtils jsonUtils = new JSONUtils(); + assertTrue(jsonUtils instanceof JSONUtils); + } + + @Test + public void isValidJsonTest() throws JsonGenerationException, JsonMappingException, IOException { + String json = JSONUtils.objectToJson(getUser()); + boolean actual = JSONUtils.isValidJSON(json); + assertTrue(actual); + } + + @Test + public void isValidJsonFailTest() throws JsonGenerationException, JsonMappingException, IOException { + String json = JSONUtils.objectToJson(getUser()); + String brokenJson = json.substring(0, json.length()/2); + boolean actual = JSONUtils.isValidJSON(brokenJson); + assertFalse(actual); + } + + @Test + public void isValidJsonNullValueTest() throws JsonParseException, IOException { + boolean actual = JSONUtils.isValidJSON(null); + assertFalse(actual); + } + + @Test + public void objectToJsonTest() throws JsonGenerationException, JsonMappingException, IOException { + String json = JSONUtils.objectToJson(getUser()); + Boolean valid = JSONUtils.isValidJSON(json); + assertTrue(valid); + } + + @Test + public void objectToJsonNullTest() throws JsonGenerationException, JsonMappingException, IOException { + String json = JSONUtils.objectToJson(null); + Boolean valid = JSONUtils.isValidJSON(json); + assertTrue(valid); + } + + @Test + public void jsonToListObjectTest() throws JsonMappingException, JsonProcessingException { + List expected = Arrays.asList(new String[] {"Alex", "Christie", "Gage"}); + String json = JSONUtils.objectToJson(expected); + List actual = JSONUtils.jsonToListObject(json, String.class); + assertEquals(expected, actual); + } + + +} diff --git a/src/test/java/com/ljunggren/storm/util/ParameterUtilsTest.java b/src/test/java/com/ljunggren/storm/util/ParameterUtilsTest.java new file mode 100644 index 0000000..0361327 --- /dev/null +++ b/src/test/java/com/ljunggren/storm/util/ParameterUtilsTest.java @@ -0,0 +1,70 @@ +package com.ljunggren.storm.util; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import com.ljunggren.storm.annotation.Param; + +public class ParameterUtilsTest { + + private class DummyClass { + @SuppressWarnings("unused") + public void find(@Param("id") int id, @Param("asc") boolean asc) {} + } + + + @Test + public void mapArgumentsToParameterNamesTest() throws NoSuchMethodException, SecurityException { + Object[] arguments = new Object[] { 1, true}; + Method method = DummyClass.class.getMethod("find", int.class, boolean.class); + Parameter[] parameters = method.getParameters(); + String[] parameterNames = ParameterUtils.getParameterNames(parameters); + Map map = ParameterUtils.mapArgumentsToParameterNames(parameters, arguments); + assertEquals(2, map.size()); + assertEquals(arguments[0], map.get(parameterNames[0])); + assertEquals(arguments[1], map.get(parameterNames[1])); + } + + @Test + public void findParameterIdsTest() { + String sql = "select * from users whesre id = #{id} and active = #{active}"; + List parameterIds = ParameterUtils.findParameterIds(sql); + assertEquals(2, parameterIds.size()); + assertEquals("id", parameterIds.get(0)); + assertEquals("active", parameterIds.get(1)); + } + + @Test + public void getParameterNamesTest() throws NoSuchMethodException, SecurityException { + Method method = DummyClass.class.getMethod("find", int.class, boolean.class); + Parameter[] parameters = method.getParameters(); + String[] parameterNames = ParameterUtils.getParameterNames(parameters); + assertEquals(2, parameterNames.length); + assertEquals("id", parameterNames[0]); + assertEquals("asc", parameterNames[1]); + } + + @Test + public void findParameterIdsWithOutSpacesTest() { + String sql = "select * from users where id in (#{id1},#{id2})"; + List parameterIds = ParameterUtils.findParameterIds(sql); + assertEquals(2, parameterIds.size()); + assertEquals("id1", parameterIds.get(0)); + assertEquals("id2", parameterIds.get(1)); + } + + @Test + public void replaceParamaterIdsWithQuestionMarksTest() { + String sql = "select * from users where id = #{id} and active = #{active}"; + String actual = ParameterUtils.replaceParamaterIdsWithQuestionMarks(sql); + String expected = "select * from users where id = ? and active = ?"; + assertEquals(expected, actual); + } + +} diff --git a/src/test/java/com/ljunggren/storm/utils/AnnotationUtilsTest.java b/src/test/java/com/ljunggren/storm/utils/AnnotationUtilsTest.java deleted file mode 100644 index fe933df..0000000 --- a/src/test/java/com/ljunggren/storm/utils/AnnotationUtilsTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.ljunggren.storm.utils; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.util.List; - -import org.junit.Test; - -import com.ljunggren.reflectionUtils.ReflectionUtils; -import com.ljunggren.storm.TestUser; -import com.ljunggren.storm.annotation.Database; -import com.ljunggren.storm.annotation.entity.Id; -import com.ljunggren.storm.annotation.entity.Table; -import com.ljunggren.storm.annotation.entity.Transient; -import com.ljunggren.storm.context.Context; -import com.ljunggren.storm.entity.Generated; - -import lombok.Data; - -public class AnnotationUtilsTest { - - @Data - private class TestId { - - @Id(generated = Generated.NONE) - private int id; - - } - - @Test - public void instantiationTest() { - AnnotationUtils annotationUtils = new AnnotationUtils(); - assertTrue(annotationUtils instanceof AnnotationUtils); - } - - @Test - public void findFieldByAnnotationTest() { - List fields = ReflectionUtils.getObjectFields(TestUser.class); - Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); - assertTrue(field != null); - } - - @Test - public void findFieldByAnnotationNoFieldTest() { - List fields = ReflectionUtils.getObjectFields(Context.class); - Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); - assertTrue(field == null); - } - - @Test - public void getAnnotationFromFieldTest() { - List fields = ReflectionUtils.getObjectFields(TestUser.class); - Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); - Annotation annotation = AnnotationUtils.getAnnotationFromField(Id.class, field); - assertTrue(annotation instanceof Id); - } - - @Test - public void getAnnotationFromFieldNoAnnotationTest() { - List fields = ReflectionUtils.getObjectFields(TestUser.class); - Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); - Annotation annotation = AnnotationUtils.getAnnotationFromField(Database.class, field); - assertTrue(annotation == null); - } - - @Test - public void getAnnotationFromClassTest() { - Annotation annotation = AnnotationUtils.getAnnotationFromClass(Table.class, TestUser.class); - assertTrue(annotation instanceof Table); - } - - @Test - public void getAnnotationFromClassNoAnnotationTest() { - Annotation annotation = AnnotationUtils.getAnnotationFromClass(Transient.class, TestUser.class); - assertTrue(annotation == null); - } - - @Test - public void isAutoGeneratedIdTest() { - List fields = ReflectionUtils.getObjectFields(TestUser.class); - Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); - boolean isAutogenerated = AnnotationUtils.isAutoGeneratedId(field); - assertTrue(isAutogenerated); - } - - @Test - public void isAutoGeneratedIdNotGeneratedTest() { - List fields = ReflectionUtils.getObjectFields(TestId.class); - Field field = AnnotationUtils.findFieldByAnnotation(Id.class, fields); - boolean isAutogenerated = AnnotationUtils.isAutoGeneratedId(field); - assertFalse(isAutogenerated); - } - - @Test - public void isAutoGeneratedIdNullTest() { - boolean isAutogenerated = AnnotationUtils.isAutoGeneratedId(null); - assertFalse(isAutogenerated); - } - -} diff --git a/src/test/java/com/ljunggren/storm/utils/ExceptionUtilsTest.java b/src/test/java/com/ljunggren/storm/utils/ExceptionUtilsTest.java deleted file mode 100644 index 273cb5f..0000000 --- a/src/test/java/com/ljunggren/storm/utils/ExceptionUtilsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ljunggren.storm.utils; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.stream.Collectors; - -import org.junit.Test; - -public class ExceptionUtilsTest { - - @Test - public void instantiationTest() { - ExceptionUtils exceptionUtils = new ExceptionUtils(); - assertTrue(exceptionUtils instanceof ExceptionUtils); - } - - @Test - public void rethrowFunctionTest() { - int sum = Arrays.stream(new Integer[] {1, 1}) - .map(ExceptionUtils.rethrowFunction(value -> 1/value)) - .collect(Collectors.summingInt(Integer::intValue)); - assertEquals(2, sum); - } - - @Test(expected = Exception.class) - public void rethrowFunctionThrowTest() { - Arrays.stream(new Integer[] {0, 1}) - .map(ExceptionUtils.rethrowFunction(value -> 1/value)) - .collect(Collectors.summingInt(Integer::intValue)); - } - -} diff --git a/src/test/java/com/ljunggren/storm/utils/JSONUtilsTest.java b/src/test/java/com/ljunggren/storm/utils/JSONUtilsTest.java deleted file mode 100644 index 7b85826..0000000 --- a/src/test/java/com/ljunggren/storm/utils/JSONUtilsTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.ljunggren.storm.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.ljunggren.storm.TestUser; - -public class JSONUtilsTest { - - private TestUser getUser() { - TestUser user = new TestUser(); - user.setFirstName("Alex"); - user.setEmployeeID(100); - return user; - } - - @Test - public void instantiationTest() { - JSONUtils jsonUtils = new JSONUtils(); - assertTrue(jsonUtils instanceof JSONUtils); - } - - @Test - public void isValidJsonTest() throws JsonGenerationException, JsonMappingException, IOException { - String json = JSONUtils.objectToJson(getUser()); - boolean actual = JSONUtils.isValidJSON(json); - assertTrue(actual); - } - - @Test - public void isValidJsonFailTest() throws JsonGenerationException, JsonMappingException, IOException { - String json = JSONUtils.objectToJson(getUser()); - String brokenJson = json.substring(0, json.length()/2); - boolean actual = JSONUtils.isValidJSON(brokenJson); - assertFalse(actual); - } - - @Test - public void isValidJsonNullValueTest() throws JsonParseException, IOException { - boolean actual = JSONUtils.isValidJSON(null); - assertFalse(actual); - } - - @Test - public void objectToJsonTest() throws JsonGenerationException, JsonMappingException, IOException { - String json = JSONUtils.objectToJson(getUser()); - Boolean valid = JSONUtils.isValidJSON(json); - assertTrue(valid); - } - - @Test - public void objectToJsonNullTest() throws JsonGenerationException, JsonMappingException, IOException { - String json = JSONUtils.objectToJson(null); - Boolean valid = JSONUtils.isValidJSON(json); - assertTrue(valid); - } - - @Test - public void jsonToListObjectTest() throws JsonMappingException, JsonProcessingException { - List expected = Arrays.asList(new String[] {"Alex", "Christie", "Gage"}); - String json = JSONUtils.objectToJson(expected); - List actual = JSONUtils.jsonToListObject(json, String.class); - assertEquals(expected, actual); - } - - -}