1 |
48362
|
claudio.at
|
package eu.dnetlib.openaire.exporter.model;
|
2 |
|
|
|
3 |
|
|
import java.sql.Array;
|
4 |
|
|
import java.sql.Connection;
|
5 |
|
|
import java.sql.SQLException;
|
6 |
|
|
import java.util.Arrays;
|
7 |
|
|
import java.util.List;
|
8 |
|
|
import java.util.Map;
|
9 |
|
|
import java.util.stream.Collectors;
|
10 |
|
|
import javax.persistence.AttributeConverter;
|
11 |
|
|
import javax.persistence.Converter;
|
12 |
|
|
import javax.sql.DataSource;
|
13 |
|
|
|
14 |
|
|
import org.springframework.beans.BeansException;
|
15 |
|
|
import org.springframework.context.ApplicationContext;
|
16 |
|
|
import org.springframework.context.ApplicationContextAware;
|
17 |
|
|
|
18 |
|
|
/**
|
19 |
|
|
* Created by claudio on 05/07/2017.
|
20 |
|
|
*/
|
21 |
|
|
@Converter
|
22 |
|
|
public class ConverterTextArray implements AttributeConverter<List<String>, Array>, ApplicationContextAware {
|
23 |
|
|
|
24 |
|
|
private ApplicationContext applicationContext;
|
25 |
|
|
|
26 |
|
|
@Override
|
27 |
|
|
public Array convertToDatabaseColumn(List<String> attribute) {
|
28 |
|
|
|
29 |
|
|
final Map<String, DataSource> datasources = applicationContext.getBeansOfType(DataSource.class);
|
30 |
|
|
DataSource source = datasources.values().stream().findFirst().get();
|
31 |
|
|
|
32 |
|
|
try {
|
33 |
|
|
Connection conn = source.getConnection();
|
34 |
|
|
Array array = conn.createArrayOf("text", attribute.toArray());
|
35 |
|
|
return array;
|
36 |
|
|
|
37 |
|
|
} catch (SQLException e) {
|
38 |
|
|
e.printStackTrace();
|
39 |
|
|
}
|
40 |
|
|
|
41 |
|
|
return null;
|
42 |
|
|
|
43 |
|
|
}
|
44 |
|
|
|
45 |
|
|
@Override
|
46 |
|
|
public List<String> convertToEntityAttribute(Array dbData) {
|
47 |
|
|
try {
|
48 |
|
|
return Arrays.stream((Object[]) dbData.getArray()).map(d -> (String) d).collect(Collectors.toList());
|
49 |
|
|
} catch (SQLException e) {
|
50 |
|
|
e.printStackTrace();
|
51 |
|
|
return null;
|
52 |
|
|
}
|
53 |
|
|
}
|
54 |
|
|
|
55 |
|
|
@Override
|
56 |
|
|
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
|
57 |
|
|
this.applicationContext = applicationContext;
|
58 |
|
|
}
|
59 |
|
|
}
|