How to ignore #class type during deserialize by jackson - jackson

I have two project A and B,
project A serialized a dto, and cached into redis, String like :
{"#class":"com.mike.xxxx.DtoDemo","id":88888,"name":"xxxxx"}
this cache was used by A and B too.
so, project A has no question.
But project B has question:
InvalidTypeIdException:Could not resolve type id 'com.mike.xxxx.DtoDemo' as a subtype of xxx
then I disable FAIL_ON_INVALID_SUBTYPE
ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
.featuresToDisable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)
...
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
but, in project B, always get null result.
How to resolve this?

in project A, keep this code, don't need change,
and project B, comment this code:
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
and it works now.

Related

How to make new mono with DTO from mono and flux in spring reactive webflux

Here I try to make call from database and combine into new mono from different mono and flux.
public Mono<ListMovieWithKomenDTO> fetchMovieAndKomen(Integer movieId){
Mono<Movie> movie = findById(movieId).subscribeOn(Schedulers.elastic());
Flux<MovieKomen> movieKomen = getKomenByMovieId(movieId).subscribeOn(Schedulers.elastic());
return Mono.zip(movie, movieKomen.collectList(), movieMovieKomenDTOBiFunction);
}
private BiFunction<Movie, List<MovieKomen>, ListMovieWithKomenDTO> movieMovieKomenDTOBiFunction = (x1, x2) -> ListMovieWithKomenDTO.builder()
// .age(x1.getAge())
.id(x1.getId())
.name(x1.getName())
.status(x1.getStatus())
.detail(x1.getDetail())
.url(x1.getUrl())
.movieKomen(x2).build();
In here I make db call twice for header ( like movie ) and detail ( like movie comment ) to separate them. After I make retrieve two different data, I want to join into new mono data based on flux data and mono. to make them into one data, I make DTO to put together from movie table and comment table but it failed. I assume that errors from mono.zip to get data into one new mono.
Here the error from debug console
java.lang.IllegalArgumentException: Cannot encode parameter of type org.springframework.r2dbc.core.Parameter
at io.r2dbc.postgresql.ExtendedQueryPostgresqlStatement.bind(ExtendedQueryPostgresqlStatement.java:89) ~[r2dbc-postgresql-0.8.10.RELEASE.jar:0.8.10.RELEASE]
Thank you
Problem is in my repository I used
public interface MovieKomenRepository extends ReactiveCrudRepository<MovieKomen,Integer> {
#Query("select * from m_movie_komen where m_movie_id = $1")
Flux<MovieKomen> findByMovieId(int movie_id);
}
in above example, I used $1 for the param in query. But when I change my code like bottom. It works like a charm.
public interface MovieKomenRepository extends ReactiveCrudRepository<MovieKomen,Integer> {
#Query("select * from m_movie_komen where m_movie_id = :movie")
Flux<MovieKomen> findByMovieId(#Param("movie") int movie_id);
}
so if someone want to use my service code is fine but careful in repository. we should not used '$1' instead ':movie'. so the problem not in service or mono/flux. but in my repository
Thank you.

org.apache.avro.SchemaParseException: Can't redefine: org.apache.avro.reflect.Pair620b9c15f622a7

I have a class as given below
class A
{
private Map<Long ,Set<Long>> x;
private Map<Long ,Set<Long>> y;}
When avro tries to create schema using reflection it creates the schema having the name of the map as Pair620b9c15f622a7 for both the fields. ANd hence I get the exception
Schema s = ReflectData.get().getSchema(A.class);
I am not sure as of why I am getting this error , though the field names are completely different.
1 solution for this might be to explicitly define the name of x and y in the schema using #AvroSchema annotation, but that is very manual task and I have to do it for all such mappings in my code
pretty similar to what I just answered here Generate Avro file based on java file. TRy using kite sdk util class

Spring Data Rest ignoring #JsonInclude annotation

With or without this annotation, there is a property on my JPA #Entity
#Entity
public class Myentity extends ResourceSupport implements Serializable {
...
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="idrepository")
#JsonInclude(JsonInclude.Include.ALWAYS)
private MyentitySource entitysource;
...
}
that is not being mapped when I return:
#RequestMapping("/myentity/{uuid}")
public ResponseEntity<Myentity> getResourceById(#PathVariable("uuid") UUID uuid) {
Myentity result = myentityRepository.findOne(uuid);
return ResponseEntity.ok(myentityAssembler.toResource(result));
}
myentityAssembler.toResource(result) does contain this MyentitySource entitysource, but the JSON output does not.
The weirdest thing is I have another spring boot hateoas project where I am using the exact same entity, repository, controller, and assembler implementations, with the exact same dependencies and versions on my pom, and a very similar configuration (I am not defining any special jackson mappers or anything, just using the default rest/hateoas configuration), and it does work there: The MyentitySource entitysource property, which is another JPA entity extending ResourceSupport, gets serialized and included into the JSON output.
I have been a couple of hours at it already, but I am quite lost. I have verified this behavior is happening all through the application in both applications: #ManyToOne relations defined on any #Entity are being mapped and present in the JSON output on one application, but not in the other.
How can I get these fields to show up on the JSON output?
entitysource will be included if MyentitySource is not an exported entity. If it is one - what seems to be the case here - then it would be wrong to include it. Including associations could lead to sending the whole database to the client. Moreover it is a separate resource with its own URI. Consequently a link to that URI is included in the response.
CascadeType.ALL implies that Myentity is an aggregate, therefore MyentitySource should not be exported in the first place. That would solve your problem. If my assumption is wrong, then you can still use Projections to get entitysource included. I can refer you to this answer from Spring's Oliver Gierke and the relevant chapter of the documentation.

Auto generated linq class is empty?

This is a continuation of my previous question: Could not find an implementation of the query pattern
I'm trying to insert a new 'Inschrijving' into my database. I try this with the following code:
[OperationContract]
public void insertInschrijving(Inschrijvingen inschrijving)
{
var context = new DataClassesDataContext();
context.Inschrijvingens.InsertOnSubmit(inschrijving);
dc.SubmitChanges();
}
But the context.Inschrijvingens.InsertOnSubmit(inschrijving); gives me the following error:
cannot convert from 'OndernemersAward.Web.Service.Inschrijvingen' to 'OndernemersAward.Web.Inschrijvingen'
I call the method in my main page:
Inschrijvingen1Client client = new Inschrijvingen1Client();
Inschrijvingen i = new Inschrijvingen();
client.insertInschrijvingCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_insertInschrijvingCompleted);
client.insertInschrijvingAsync(i);
But as you can see there appears to be something wrong with my Inschrijvingen class, which is auto generated by LINQ. (Auto generated class can be found here: http://pastebin.com/QKuAAKgV)
I'm not entirely sure what is causing this, but I assume it has something to do with the auto generated class not being correct?
Thank you for your time,
Thomas
The problem is that you've got two Inschrijvingen classes - one in the OndernemersAward.Web.Service namespace, and one in the OndernemersAward.Web namespace.
You either need to change the codebase so that you've only got one class, or you need to convert from one type to the other.

JPA & Ebean ORM: Empty collection is not empty

I've started switching over a project from hand-written JDBC ORM code to Ebeans. So far it's been great; Ebeans is light and easy to use.
However, I have run into a crippling issue: when retrieving a one-to-many list which should be empty there is actually one element in it. This element looks to be some kind of proxy object which has all null fields, so it breaks code which loops through the collection.
I've included abbreviated definitions here:
#Entity
class Store {
...
#OneToMany(mappedBy="store",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
List<StoreAlbum> storeAlbums = new LinkedList<StoreAlbum>();
}
#Entity
class StoreAlbum {
...
#ManyToOne(optional=false,fetch=FetchType.EAGER)
#JoinColumn(name="store_id",nullable=false)
Store store;
}
The ... are where all the standard getters and setters are. The retrieval code looks like this:
Store s = server.find(Store.class)
.where()
.eq("store_id",4)
.findUnique();
Assert.assertEquals("Sprint",s.getStoreName());
Assert.assertEquals(0, s.getStoreAlbums().size());
The database is known to contain a 'store' row for "Sprint", and the 'store_album' table does not contain any rows for that store.
The JUnit test fails on the second assertion. It finds a list with 1 element in it, which is some kind of broken StoreAlbum object. The debugger shows the object as being of the type "com.lwm.catalogfeed.domain.StoreAlbum$$EntityBean$test#1a5e68a" with null values for all the fields which are declared as nullable=false (and optional=false).
Am I missing something here?
Thought I'd post an update on this... I ended up giving up on EBeans and instead switched the implementation over to use MyBatis. MyBatis is fantastic; the manual is easy to read and thorough. MyBatis does what you expect it to do. I got it up and running in no time.
EBeans didn't appear to detect that the join for the associated collection resulted in a bunch of null ids, but MyBatis handled this scenario cleanly.
I ran into the same issue and was able to solve it by adding an identity column to the secondary table (StoreAlbum). I did not investigate the cause but I suppose Ebean needs a primary key on the table in these kind of situations.