I am trying to get date value from JsonNode. I have a car object which has car name and released LocalDate.
public class Car {
String carName;
LocalDate released;
}
I need to convert it into JsonNode, so I am doing this way.
ObjectMapper obj = new ObjectMapper();
JsonNode node = obj.valueToTree(car);
Until here I am good. Once I have JsonNode I need to read it from it.
String carName = node.at("/carName").textValue();
LocalDate date = node.at("/released").textValue();
How can I get LocalDate value in LocalDate format or String format from JsonNode?
it worked. I used objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); I am able to get string value from JsonNode now.
Related
Here my problem, I have to store serialized website's cookie information in DB, and I tried to write a simple PesistentConverter to it can be convert Map to String and vice-versa. But the IDE show a warning about this:
'Basic' attribute type should not be a map
Here my Entity:
#Entity
#Table(name = "website")
public class Website implements Serializable {
#Id
#Column(name = "name", length = 16, nullable = false)
#NotNull
private String name;
#Column(name = "serialized_cookie_map", nullable = false, length = 2048)
#Convert(converter = CookieMapPersistenceConverter.class)
#NotNull
private Map<String,String> serializedCookieMap;
...
}
CookieMapPersistenceConverter:
public class CookieMapPersistenceConverter implements AttributeConverter<Map<String, String>, String> {
#Override
public String convertToDatabaseColumn(Map<String, String> stringStringMap) {
return stringStringMap.toString();
}
#Override
public Map<String, String> convertToEntityAttribute(String s) {
ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, String.class);
HashMap<String,String> convertedMap = null;
try {
convertedMap = mapper.readValue(s, mapType);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return convertedMap;
}
}
I'm using the 2.6.3 version of Spring Boot.
Many thanks your time!
According to this:
Any attributes that have no other annotations and do not reference
other entities will be automatically mapped as basic.
and according to the table from the above link map is not a basic type. so IDE is right about
'Basic' attribute type should not be a map
I suggest try the following approach to see it satisfies your requirements or not.
#Id
#Column(name = "id", length = 16, nullable = false)
#NotNull
private String id;
#ElementCollection
#MapKeyColumn(name="property")
#Column(name="value")
#CollectionTable(name="cookies", joinColumns=#JoinColumn(name="id"))
#NotNull
private Map<String,String> serializedCookieMap;
//setter and getter
and the code for repositry:
#Repository
public interface WebsiteRepository extends CrudRepository<Website, String> {}
code I did for test:
Website w = new Website();
w.setId("id");
Map<String, String> m = new HashMap<>();
m.put("key1", "value1");
m.put("key2", "value2");
m.put("key3", "value3");
w.setSerializedCookieMap(m);
repo.save(w);
which creates two table named WEBSITE and COOKIES and the content of each is like this:
WEBSITES:
ID
id
and:
COOKIES:
ID VALUE PROPERTY
id value1 key1
id value2 key2
id value3 key3
if you insist to store Serialized version of map take a look at this
I have tried same thing in my project (with same version of spring boot). I did not notice any warning.
But here are some suggestions...
The field you have annotated #convert not meant to be persisted in DB. So instead of #column try using #Transient.
You can also try using #Type( type = "json" ) instead of #convert.
Also this can be possibly issue with IDE, so just to ignore it as a
warning you can use #SuppressWarnings("JpaAttributeTypeInspection") annotation.
Folks..!!
Have a requirement to work on reading specific column data by using Spring batch. Well i am creating a spring batch application which has a requirement to read specific column.
In my csv file i have a column "msisdn", that field is mapped to an POJO. I want to read the values of "msisdn" no which is of Long data type.
well i am taking reference of below link.
read only selective columns from csv file using spring batch
Customer POJO
public class Customer {
private String id_type;
private String id_number;
private String customer_name;
private String email_address;
private LocalDate birthday;
private String citizenship;
private String address;
private Long msisdn;
private LocalDateTime kyc_date;
private String kyc_level;
private String goalscore;
private String mobile_network;
}
I am using a CustomMapper class to implement this feature. As you can see CustomMapper class implements FieldSetMapper type. fieldSet method returns String[] Array and msisdn is of Long type.Not able to understand how to get all values in msisdn column as fieldSet is only giving String[] type of data.
CustomMapper
============
public class CustomMapper implements FieldSetMapper<Customer> {
#Override
public Customer mapFieldSet(FieldSet fieldSet) throws BindException {
String[] custArray = null;
Customer customer = new Customer();
customer.setMsisdn(fieldSet.get);
return null;
}
}
please help me on this?
You can use fieldSet.readLong(int index) or fieldSet.readLong(String name) to select a field by name or index from the field set. Obviously this field should have been selected when parsing the file in your item reader.
I have a set of data that I return in a method, how can I sort this data by createDate, I can do it using a stream, but the method returns a list, so I don’t want to use a stream, but if I can use a stream and return data in view list, can you show how?
public List<Mark> getMarksByUser(){
List<Mark> marks = markService.getMarksByUser(AuthenticationController.selfUserName());
}
sorting should be in this method
my mark entity with createDate
public class Mark extends BaseEntity<Integer> {
private String mark;
private String text;
private String sku;
private Date dateCreated;
private Date dateUpdated;
private Boolean deleted;
private String username;
I am using Chrome postman client for rest calls, here I am sending 15 form parameters like fname, last name.. so on, and also two files as file type.
I am submitting my request POST method, body type is form data selected and content type header is empty.
In the server side, I am consume this as method
#RequestMapping(value = "/create"
method = RequestMethod.POST,
consumes = {"multipart/form-data"},
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<ResponseTO> create( #ModelAttribute RequestTO updateTripRequestTO, HttpServletRequest request);
public class RequestTO implements Serializable {
private UUID id private Date createdate;
private String createdby;
private String updatedby;
private Date updateddate;
private String visibility;
private String name;
private MultipartFile tripimage;
public class RequestTO implements Serializable {
private UUID id private Date createdate;
private String createdby;
private String updatedby;
private Date updateddate;
private String visibility;
private String name;
private MultipartFile tripimage;
( and Set and get Methods)
When I debug the TO, its giving comma separated values in TO.
If I give fname is "Test", lname "Ltest" in the postman, when I debug the TO its coming fname as "Test,Test" and lname as "Ltest,Ltest " for all form fields. Can some suggest me why like this and any solution please.
I have two such Java object:
public class PSubject
{
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("name")
private String name;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("type")
private String type;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("uri")
private String uri;
#OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
#IndexedEmbedded
#org.apache.solr.client.solrj.beans.Field("attributes")
private Set<PAttribute> attributes = new HashSet<PAttribute>();
.....
}
#Entity
#Indexed
#Table(name="PAttribute")
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class PAttribute extends PEntity
{
private static final long serialVersionUID = 1L;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES)
#org.apache.solr.client.solrj.beans.Field("attr_name")
private String name;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES)
#org.apache.solr.client.solrj.beans.Field("attr_value")
private String value;
.....
}
And my Spring Data Solr query interface:
public interface DerivedSubjectRepository extends SolrCrudRepository<PSubject, String> {
Page<PSubject> findByName(String name, Pageable page);
List<PSubject> findByNameStartingWith(String name);
Page<PSubject> findBy(Pageable page);
#Query("name:*?0* or description:*?0* or type:*?0* or mac_address:*?0* or uri:*?0* or attributes:*?0*")
Page<PSubject> find(String keyword,Pageable page);
#Query("name:*?0* or description:*?0* or type:*?0* or mac_address:*?0* or uri:*?0* or attributes:*?0*")
List<PSubject> find(String keyword);
}
I can search any by name, description, type and mac_address, but can't search any result by attribute.
Update:
For example,when user search "ipod", it's probably means the type of subject or name of subject, or the name of attribute or the value of attribute. And I want get all the matched subject in one request. I know I can search the attribute object in a separate query. But that makes the code in the backend complex.
So, how can I search this nested object?
Update:
I flattened my data:
#Transient
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("attrs")
private String attrs;
public String getAttrs() {
return attrs;
}
public void setAttrs(Set<PAttribute> attributes) {
StringBuffer attrs = new StringBuffer();
if(attributes==null) {
attributes = this.getAttributes();
}
for(PAttribute attr:attributes){
attrs.append(attr.getName()+" " + attr.getValue()).append(" ");
}
this.attrs =attrs.toString();
}
The issue is resolved.
IIRC it is not possible to store nested data structures in solr - it depends how you flatten your data to fit into an eg. multivalue field - a little hard not knowing your schema.
see: http://lucene.472066.n3.nabble.com/Possible-to-have-Solr-documents-with-deeply-nested-data-structures-i-e-hashes-within-hashes-td4004285.html
How does the data look like in you index, and did you have a look at the http request sent by spring-data-solr?