Search in sources :

Example 6 with JdbcColumnKey

use of org.simpleflatmapper.jdbc.JdbcColumnKey in project SimpleFlatMapper by arnaudroger.

the class JdbcColumnKeyTest method testEquals.

@Test
public void testEquals() throws Exception {
    assertEquals(new JdbcColumnKey("col", 1, Types.ARRAY), new JdbcColumnKey("col", 1, Types.ARRAY));
    assertNotEquals(new JdbcColumnKey("col", 1, Types.ARRAY), new JdbcColumnKey("col", 1, Types.VARCHAR));
    assertNotEquals(new JdbcColumnKey("col", 1, Types.ARRAY), new JdbcColumnKey("col", 2, Types.ARRAY));
    assertNotEquals(new JdbcColumnKey("col", 1, Types.ARRAY), new JdbcColumnKey("col1", 1, Types.ARRAY));
}
Also used : JdbcColumnKey(org.simpleflatmapper.jdbc.JdbcColumnKey) Test(org.junit.Test)

Example 7 with JdbcColumnKey

use of org.simpleflatmapper.jdbc.JdbcColumnKey in project SimpleFlatMapper by arnaudroger.

the class JdbcConverterFactoryProducer method produce.

@Override
public void produce(Consumer<? super ConverterFactory<?, ?>> consumer) {
    // IFJAVA8_START
    constantConverter(consumer, Time.class, LocalTime.class, new TimeToLocalTimeConverter());
    constantConverter(consumer, Date.class, LocalDate.class, new DateToLocalDateConverter());
    factoryConverter(consumer, new AbstractConverterFactory<Time, OffsetTime>(Time.class, OffsetTime.class) {

        @Override
        public Converter<Time, OffsetTime> newConverter(ConvertingTypes targetedTypes, Object... params) {
            ZoneOffset zoneOffset = getZoneOffset(params);
            return new TimeToOffsetTimeConverter(zoneOffset);
        }

        @SuppressWarnings("unchecked")
        private ZoneOffset getZoneOffset(Object[] params) {
            for (Object prop : params) {
                if (prop instanceof ZoneOffset) {
                    return (ZoneOffset) prop;
                } else if (SupplierHelper.isSupplierOf(prop, ZoneOffset.class)) {
                    return ((Supplier<ZoneOffset>) prop).get();
                }
            }
            return ZoneOffset.UTC;
        }
    });
    // IFJAVA8_END
    factoryConverter(consumer, new AbstractConverterFactory<Array, Object>(Array.class, java.lang.reflect.Array.class) {

        @Override
        public Converter<? super Array, ? extends Object> newConverter(ConvertingTypes targetedTypes, Object... params) {
            Type elementType = TypeHelper.getComponentTypeOfListOrArray(targetedTypes.getTo());
            Getter<? super ResultSet, ?> getter = ResultSetGetterFactory.INSTANCE.newGetter(elementType, new JdbcColumnKey("elt", 2), params);
            return new SqlArrayToJavaArrayConverter<Object>(TypeHelper.<Object>toClass(elementType), getter);
        }

        @Override
        public ConvertingScore score(ConvertingTypes targetedTypes) {
            return new ConvertingScore(super.score(targetedTypes).getFromScore(), TypeHelper.isArray(targetedTypes.getTo()) ? 1 : -1);
        }
    });
    factoryConverter(consumer, new AbstractConverterFactory<Array, List>(Array.class, List.class) {

        @Override
        public Converter<? super Array, ? extends List> newConverter(ConvertingTypes targetedTypes, Object... params) {
            Type elementType = TypeHelper.getComponentTypeOfListOrArray(targetedTypes.getTo());
            Getter<? super ResultSet, ?> getter = ResultSetGetterFactory.INSTANCE.newGetter(elementType, new JdbcColumnKey("elt", 2), params);
            return new SqlArrayToListConverter<Object>(getter);
        }
    });
    constantConverter(consumer, Calendar.class, Timestamp.class, new CalendarToTimestampConverter());
    constantConverter(consumer, java.util.Date.class, Timestamp.class, new UtilDateToTimestampConverter());
    constantConverter(consumer, java.util.Date.class, Time.class, new UtilDateToTimeConverter());
    constantConverter(consumer, java.util.Date.class, Date.class, new UtilDateToDateConverter());
}
Also used : Getter(org.simpleflatmapper.reflect.Getter) Time(java.sql.Time) LocalTime(java.time.LocalTime) OffsetTime(java.time.OffsetTime) ZoneOffset(java.time.ZoneOffset) TimeToLocalTimeConverter(org.simpleflatmapper.jdbc.converter.time.TimeToLocalTimeConverter) ConvertingTypes(org.simpleflatmapper.converter.ConvertingTypes) OffsetTime(java.time.OffsetTime) ResultSet(java.sql.ResultSet) TimeToLocalTimeConverter(org.simpleflatmapper.jdbc.converter.time.TimeToLocalTimeConverter) Converter(org.simpleflatmapper.converter.Converter) TimeToOffsetTimeConverter(org.simpleflatmapper.jdbc.converter.time.TimeToOffsetTimeConverter) DateToLocalDateConverter(org.simpleflatmapper.jdbc.converter.time.DateToLocalDateConverter) TimeToOffsetTimeConverter(org.simpleflatmapper.jdbc.converter.time.TimeToOffsetTimeConverter) Supplier(org.simpleflatmapper.util.Supplier) List(java.util.List) ConvertingScore(org.simpleflatmapper.converter.ConvertingScore) Array(java.sql.Array) JdbcColumnKey(org.simpleflatmapper.jdbc.JdbcColumnKey) Type(java.lang.reflect.Type) DateToLocalDateConverter(org.simpleflatmapper.jdbc.converter.time.DateToLocalDateConverter)

Example 8 with JdbcColumnKey

use of org.simpleflatmapper.jdbc.JdbcColumnKey in project SimpleFlatMapper by arnaudroger.

the class SqlParameterSourceBuilder method add.

public SqlParameterSourceBuilder<T> add(JdbcColumnKey key, FieldMapperColumnDefinition<JdbcColumnKey> columnDefinition) {
    final FieldMapperColumnDefinition<JdbcColumnKey> composedDefinition = columnDefinition.compose(mapperConfig.columnDefinitions().getColumnDefinition(key));
    final JdbcColumnKey mappedColumnKey = composedDefinition.rename(key);
    if (composedDefinition.has(ConstantValueProperty.class)) {
        ConstantValueProperty staticValueProperty = composedDefinition.lookFor(ConstantValueProperty.class);
        PropertyMeta<T, Object> meta = new ObjectPropertyMeta<T, Object>(key.getName(), builder.getClassMeta().getType(), reflectionService, staticValueProperty.getType(), ScoredGetter.of(new ConstantGetter<T, Object>(staticValueProperty.getValue()), 1), null, null);
        builder.addProperty(key, columnDefinition, meta);
    } else {
        builder.addProperty(mappedColumnKey, composedDefinition);
    }
    return this;
}
Also used : JdbcColumnKey(org.simpleflatmapper.jdbc.JdbcColumnKey) ConstantGetter(org.simpleflatmapper.reflect.getter.ConstantGetter) ConstantValueProperty(org.simpleflatmapper.map.property.ConstantValueProperty) ObjectPropertyMeta(org.simpleflatmapper.reflect.meta.ObjectPropertyMeta)

Example 9 with JdbcColumnKey

use of org.simpleflatmapper.jdbc.JdbcColumnKey in project SimpleFlatMapper by arnaudroger.

the class JoinSample method stackOverFlowJoin.

/**
 * Test for https://arnaudroger.github.io/blog/2017/02/24/jooq-one-to-many.html
 *
 * To avoid having to mock the result set metadata I used a static mapper here. In production code
 * you can just call
 *  newMapper(Location.class)
 * instead of newBuilder()...mapper()
 *
 * @throws SQLException
 */
@Test
public void stackOverFlowJoin() throws SQLException {
    JdbcMapper<Location> mapper = JdbcMapperFactory.newInstance().addKeys("player").newBuilder(Location.class).addMapping(new JdbcColumnKey("name", 1, Types.VARCHAR)).addMapping(new JdbcColumnKey("player", 2, Types.VARCHAR)).addMapping(new JdbcColumnKey("invited_players_player", 3, Types.VARCHAR)).mapper();
    UUID[] players = new UUID[] { UUID.randomUUID(), UUID.randomUUID() };
    UUID[] invitedPlayers = new UUID[] { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID() };
    String[] name = new String[] { "location1", "location2" };
    ResultSet rs = mock(ResultSet.class);
    when(rs.next()).thenReturn(true, true, true, false);
    when(rs.getString(1)).thenReturn(name[0], name[1]);
    when(rs.getString(2)).thenReturn(players[0].toString(), players[1].toString());
    when(rs.getObject(2)).thenReturn(players[0].toString(), players[0].toString(), players[0].toString(), players[0].toString(), players[1].toString(), players[1].toString());
    when(rs.getString(3)).thenReturn(invitedPlayers[0].toString(), invitedPlayers[1].toString(), invitedPlayers[2].toString());
    List<Location> list = mapper.forEach(rs, new ListCollector<Location>()).getList();
    assertEquals(2, list.size());
    assertEquals("location1", list.get(0).getName());
    assertEquals(players[0], list.get(0).getPlayer());
    assertEquals(Arrays.asList(invitedPlayers[0], invitedPlayers[1]), list.get(0).getInvitedPlayers());
    assertEquals("location2", list.get(1).getName());
    assertEquals(players[1], list.get(1).getPlayer());
    assertEquals(Arrays.asList(invitedPlayers[2]), list.get(1).getInvitedPlayers());
}
Also used : JdbcColumnKey(org.simpleflatmapper.jdbc.JdbcColumnKey) ListCollector(org.simpleflatmapper.util.ListCollector) ResultSet(java.sql.ResultSet) UUID(java.util.UUID) Test(org.junit.Test)

Example 10 with JdbcColumnKey

use of org.simpleflatmapper.jdbc.JdbcColumnKey in project SimpleFlatMapper by arnaudroger.

the class CrudMeta method of.

public static CrudMeta of(Connection connection, String table, ColumnDefinitionProvider<FieldMapperColumnDefinition<JdbcColumnKey>, JdbcColumnKey> columnDefinitionProvider) throws SQLException {
    Statement statement = connection.createStatement();
    try {
        ResultSet resultSet = statement.executeQuery("SELECT * FROM " + table + " WHERE 1 = 2");
        try {
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            DatabaseMetaData metaData = connection.getMetaData();
            DatabaseMeta databaseMeta = new DatabaseMeta(metaData.getDatabaseProductName(), metaData.getDatabaseMajorVersion(), metaData.getDatabaseMinorVersion());
            ColumnMeta[] columnMetas = new ColumnMeta[resultSetMetaData.getColumnCount()];
            List<String> primaryKeys = getPrimaryKeys(connection, resultSetMetaData, columnDefinitionProvider);
            for (int i = 0; i < columnMetas.length; i++) {
                String columnName = resultSetMetaData.getColumnName(i + 1);
                FieldMapperColumnDefinition<JdbcColumnKey> columnDefinition = columnDefinitionProvider.getColumnDefinition(JdbcColumnKey.of(resultSetMetaData, i + 1));
                AutoGeneratedProperty autoGeneratedProperty = columnDefinition.lookFor(AutoGeneratedProperty.class);
                if (autoGeneratedProperty == null && resultSetMetaData.isAutoIncrement(i + 1) && !columnDefinition.has(IgnoreAutoGeneratedProperty.class)) {
                    autoGeneratedProperty = AutoGeneratedProperty.DEFAULT;
                }
                columnMetas[i] = new ColumnMeta(columnName, resultSetMetaData.getColumnType(i + 1), primaryKeys.contains(columnName), autoGeneratedProperty);
            }
            return new CrudMeta(databaseMeta, table, columnMetas);
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
Also used : Statement(java.sql.Statement) DatabaseMetaData(java.sql.DatabaseMetaData) AutoGeneratedProperty(org.simpleflatmapper.map.property.AutoGeneratedProperty) IgnoreAutoGeneratedProperty(org.simpleflatmapper.map.property.IgnoreAutoGeneratedProperty) ResultSetMetaData(java.sql.ResultSetMetaData) JdbcColumnKey(org.simpleflatmapper.jdbc.JdbcColumnKey) ResultSet(java.sql.ResultSet)

Aggregations

JdbcColumnKey (org.simpleflatmapper.jdbc.JdbcColumnKey)14 Test (org.junit.Test)8 ResultSet (java.sql.ResultSet)7 DbObject (org.simpleflatmapper.test.beans.DbObject)4 ListCollector (org.simpleflatmapper.util.ListCollector)4 Type (java.lang.reflect.Type)2 ParseException (java.text.ParseException)2 ArrayList (java.util.ArrayList)2 PropertyMapping (org.simpleflatmapper.map.mapper.PropertyMapping)2 Getter (org.simpleflatmapper.reflect.Getter)2 PropertyMeta (org.simpleflatmapper.reflect.meta.PropertyMeta)2 Array (java.sql.Array)1 DatabaseMetaData (java.sql.DatabaseMetaData)1 ResultSetMetaData (java.sql.ResultSetMetaData)1 Statement (java.sql.Statement)1 Time (java.sql.Time)1 LocalTime (java.time.LocalTime)1 OffsetTime (java.time.OffsetTime)1 ZoneOffset (java.time.ZoneOffset)1 List (java.util.List)1