I initially had my #NodeEntity class having a #GraphProperty of java.util.Date type. The graph repository APIs automatically convert that to long / string value and stores it based on my property type.
As I wanted to import huge chunk of data from csv, I wanted this date field in my custom or pre-defined string format, say "yyyyMMdd". So I wrote my spring converter factories for both String -> Date and DAte -> String and registered them in the spring xml for conversion service. But unfortunately my converter was never called. Only the standard converter was called.
Later, when I wrap the date object inside MyDate class and changed the converter to String -> MyDAte and vice versa instead of java.util.Date, converter was called and the required serialization was done.
I dont want this MyDate wrapper around Date just for the sake of converter. Now, my question is, how to override the default date converter with my converters?
try this:
#Configuration
#EnableNeo4jRepositories
static class TestConfig extends Neo4jConfiguration {
#Bean
GraphDatabaseService graphDatabaseService() {
return new ImpermanentGraphDatabase();
}
#Bean
protected ConversionService neo4jConversionService() throws Exception {
ConversionService conversionService = super.neo4jConversionService();
ConverterRegistry registry = (ConverterRegistry) conversionService;
registry.removeConvertible(Date.class, String.class);
registry.removeConvertible(String.class, Date.class);
//add your own converters like this
registry.addConverter(new MyDateToStringConverter());
registry.addConverter(new MyStringToDateConverter());
return conversionService;
}
}
Related
I have the following mapping
#Document(indexName = "some-index")
#Data
public class ElasticDocument {
#Id
#Field(type = FieldType.Text)
private String id;
#Field(type = FieldType.Date, format = DateFormat.custom)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "uuuu-MM-dd'T'HH:mm:ss.SSS")
private LocalDateTime issuedTimestamp;
}
The following repository
#Repository
public interface DocumentRepository extends ElasticsearchRepository<ElasticDocument, String> {
}
But the following query from spring data elastic search 4.0.3.RELEASE throws a conversion error:
Page<ElasticDocument> elasticDocuments = documentRepository.findAll(PageRequest.of(0, 10));
[MappingElasticsearchConverter.java:290] [Type LocalDateTime of
property ElasticDocument.issuedTimestamp is a TemporalAccessor
class but has neither a #Field annotation defining the date type nor a
registered converter for reading! It cannot be mapped from a complex
object in Elasticsearch!
[No converter found capable of converting from type [java.lang.Long]
to type [java.time.LocalDateTime]]
[org.springframework.core.convert.ConverterNotFoundException: No
converter found capable of converting from type [java.lang.Long] to
type [java.time.LocalDateTime]
I'm using elasticsearch 7.9.1 and spring data elasticsearch 4.0.3.RELEASE and from what i understood starting with spring data elasticsearch 4.x we don't need to create a custom conversion as long as i added the Field annotation at mapping
You need to add the pattern for your custom format in the #Field annotation
#Field(type = FieldType.Date, format = DateFormat.custom, pattern = "uuuu-MM-dd'T'HH:mm:ss.SSS")
Since spring-data-elastic version 4.2, dateformat.custom is deprecated. You can use any of the enum date_hour_minute_second_xxx in org.springframework.data.elasticsearch.annotations.DateFormat. E.g
#Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second_millis)
private LocalDateTime createdDate;
I have an Aqueduct project using the ORM, with a data model as follows:
class _Thing {
#primaryKey
int id;
String first;
String second;
}
class Thing extends ManagedObject<_Thing> implements _Thing {
#Serialize()
OtherThing get firstAndSecond() {
// return some value computed from first and second
}
#Serialize()
set firstAndSecond(OtherThing firstAndSecond) {
// set first and second based on some computation
}
}
According to the docs for transient properties, annotating with #Serialize() should enable this model to be serialized/deserialized. It also says that properties in ManagedObjects are not persisted, but when I run the server, I get the error:
Data Model Error: Property 'firstAndSecond' on 'Thing' has an unsupported type.
If I remove the #Serialize(), it doesn't try to persist it, but I can't serialize/deserialize this object.
Any suggestions as to why this is happening or how I can control this behaviour?
This should be in the docs -
A Serializable property must be a primitive type (e.g. String, int, double, bool or a Map or List containing these types). Serializable values are passed directly to the codec that is reading from a request body or writing to a response body (by default, this codec is JSON). In the case of a custom type like OtherThing, the codec doesn't know how to encode or decode that type.
For complex types, you might use a map:
#Serialize()
Map<String, dynanic> get firstAndSecond() {
return {"first": first, "second": second};
}
You might also use CSV-like data:
#Serialize()
String get firstAndSecond() {
return "$first,$second";
}
In grails 3 is there a way to bind time of format "11:00 AM" to java.sql.Time?
import java.sql.Time
Time startTime
There are several ways to do it. One is to supply an appopriate ValueConverter as described in the Custom Data Converters section at http://docs.grails.org/3.3.8/guide/theWebLayer.html#dataBinding.
That could look something like this...
package com.myapp.converters
import grails.databinding.converters.ValueConverter
import java.sql.Time
/**
* A custom converter which will convert String into a Time object.
*/
class TimeValueConverter implements ValueConverter {
boolean canConvert(value) {
value instanceof String
}
def convert(value) {
// return a new Time instance initialized with the `value` parameter
}
Class<?> getTargetType() {
java.sql.Time
}
}
Then add an instance of that class the Spring application context:
beans = {
timeConverter com.myapp.converters.TimeValueConverter
// ...
}
I am trying to create nodes of a specific type with properties which can be dynamic .
For Example : I can create a Person node with name,age,address properties. But these need not be the only properties when I create another Person node. This node can have name,age,address and an additional property salary. Using spring data or query DSL needs me to create Java POJO class Person with fixed number of instance variables name,age and address .
#NodeEntity
public class Person {
#GraphId private Long id;
private String name;
private String age;
private String address;
}
I cannot add a dynamic property for salary for another Person node. Is there a way I can achieve this ?
Dynamic properties are not supported in Neo4j-OGM at the moment (see https://jira.spring.io/browse/DATAGRAPH-555)
If you only interact with your graph via the OGM and do not have to query on individual dynamic properties, you could try a Map of properties with a custom Converter, that converts this Map to a String (like json). The OGM will then use this converter to serialize the map to and from the graph.
Note that because the values are squashed into a String, it is now not trivial to query on an individual dynamic property.
To create a custom converter you need to implement org.neo4j.ogm.typeconversion.AttributeConverter and provide the implementation to convert from a Map to String.
Then, annotate your map property in your domain entity like this:
#Convert(MoneyConverter.class)
Edit:
As pointed out by Michael, if the salary is the only extra optional property, then it makes sense to have this property but set it only when it has a value. Dynamic properties are overkill in this case. You may want to use dynamic properties when you have an unknown and arbitrary set of properties to be persisted with the node
You can workaround the limitations by creating a CompositeAttributeConverter saving each dynamic property in the graph (not only as JSON-String wich cannot be queried well - as mentioned by luanne in the accepted answer)
import java.lang.reflect.Field;
import java.util.*;
import org.neo4j.ogm.typeconversion.CompositeAttributeConverter;
public abstract class DynamicPropertiesConverter implements CompositeAttributeConverter<Map<String, ?>> {
private Set<String> blacklist;
public DynamicPropertiesConverter(Class<?> clazz) {
blacklist = new HashSet<>();
addAllFields(clazz);
}
public DynamicPropertiesConverter(Set<String> blacklist) {
this.blacklist = blacklist;
}
public void addAllFields(Class<?> type) {
for (Field field : type.getDeclaredFields()) {
blacklist.add(field.getName());
}
if (type.getSuperclass() != null) {
addAllFields(type.getSuperclass());
}
}
#Override
public Map<String, ?> toGraphProperties(Map<String, ?> value) {
Map<String, ?> result = new HashMap<>(value);
result.keySet().removeAll(blacklist);
return result;
}
#Override
public Map<String, ?> toEntityAttribute(Map<String, ?> value) {
return toGraphProperties(value);
}
}
Now you can create a special version of this converter:
public class DynamicNodePropertiesConverter extends DynamicPropertiesConverter {
public DynamicNodePropertiesConverter() {
super(Node.class);
}
}
And use it like this:
import java.util.Map;
import DynamicNodePropertiesConverter;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.typeconversion.Convert;
#NodeEntity
public class Node {
#Convert(DynamicNodePropertiesConverter.class)
private Map<String, Object> data;
/* getter and setter */
}
I'm new to Guice and here is a naive question. I learned that we could bind String to a particular value through:
bind(String.class)
.annotatedWith(Names.named("JDBC URL"))
.toInstance("jdbc:mysql://localhost/pizza");
But what if I want to bind String to any possible characters?
Or I think it could be described this way:
How can I replace "new SomeClass(String strParameter)" with Guice?
You first need to annotate the constructor for SomeClass:
class SomeClass {
#Inject
SomeClass(#Named("JDBC URL") String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
}
I prefer to use custom annotations, like this:
class SomeClass {
#Inject
SomeClass(#JdbcUrl String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD, ElementType.PARAMETER})
#BindingAnnotation
public #interface JdbcUrl {}
}
Then you need to provide a binding in your Module:
public class SomeModule extends AbstractModule {
private final String jdbcUrl; // set in constructor
protected void configure() {
bindConstant().annotatedWith(SomeClass.JdbcUrl.class).to(jdbcUrl);
}
}
Then an time Guice creates SomeClass, it will inject the parameter. For instance, if SomeOtherClass depends on SomeClass:
class SomeOtherClass {
#Inject
SomeOtherClass(SomeClass someClass) {
this.someClass = someClass;
}
Often, when you think you want to inject a String, you want to inject an object. For instance, if the String is a URL, I often inject a URI with a binding annotation.
This all assumes there is some constant value you can define at module creation time for the String. If the value isn't available at module creation time, you can use AssistedInject.
This might be off-topic, but Guice makes configuration much easier than writing an explicit binding for every String you need. You can just have a config file for them:
Properties configProps = Properties.load(getClass().getClassLoader().getResourceAsStream("myconfig.properties");
Names.bindProperties(binder(), configProps);
and voilĂ all your config is ready for injection:
#Provides // use this to have nice creation methods in modules
public Connection getDBConnection(#Named("dbConnection") String connectionStr,
#Named("dbUser") String user,
#Named("dbPw") String pw,) {
return DriverManager.getConnection(connectionStr, user, pw);
}
Now just create your Java properties file myconfig.properties at the root of your classpath with
dbConnection = jdbc:mysql://localhost/test
dbUser = username
dbPw = password
or merge authorization information from some other source into the properties and you're set.
I was able to inject a string through Named annotation.
#Provides
#Named("stage")
String stage() {
return domain;
}
class SomeClass {
#Inject
#Named("stage")
String stageName;
}
I find a solution in the FAQ of Guice:
http://code.google.com/docreader/#p=google-guice&s=google-guice&t=FrequentlyAskedQuestions
In addition to define an annotation and a String attribute in MyModule, I need to write below line to get a instance of SomeClass:
SomeClass instance = Guice.createInjector(new MyModule("any string i like to use")).getInstance(SomeClass.class);
But I remembered that Injector.getInstance() should not be used except for the root object, so is there any better way to do this?