Mapstruct transform obect to list - mapstruct

I have to map an object to list of another objects like below
public List map(ClassA A){
List<ClassB> list = new ArrayList<ClassB>();
ClassB C1 = new ClassB();
ClassB C2= new ClassB();
.... Logic to populate C1 and C2 from ClassA
add C1 and C2 to list
return list;
}
In the generated Impl class, I am getting a complilation error "Cannot find the symbol ClassB". The class "ClassB" is not imported to the generated impl class. Please help me in solving this.

MapStruct cannot generate mapping methods between iterable types (List<ClassB>) and non-iterable types (ClassA).
Can you share the definitions of ClassA and ClassB in more detail? Then we can try and find a good solution. Probably it's simplest though to just implement this one from hand (esp. if ClassA contains a list of ClassB, in which case no mapping for the list elements is required).

Related

Jackson scala object mapper not properly serializing nested case class

I have a schema which is defined like this
#JsonDeserialize(using = classOf[ProductDeserializer])
trait GenericProduct{
#JsonUnwrapped
def commonAttributes: CommonAttributes
}
There are different kinds of products. For example, Product A given below extends base trait Product. Similarly, there are other products B, C, D.
case class ProductA(commonAttributes: CommonAttributes,
extraField1: String,
extraField2: String) extends GenericProduct
My serializer method is like this
#Component
class ProductSerializer #Autowired()
(val mapper: ScalaObjectMapper = ObjectMapperSingleton.getMapper) {
def serialize[T<:GenericProduct](product: T)(implicit m: Manifest[T]): String = {
mapper
.writerWithType[T]
.writeValueAsString(product)
}
}
If i pass objects of type A, B, C, D, it works just fine. Serialized JSON string has common attributes and product specific attributes.
But if i wrap the product objects inside a case class. For example, from one method i'm returning something like this
case class ConsolidatedProducts(newProducts: List[GenericProduct],
oldProducts: List[GenericProduct])
It doesn't complain during compile time but during runtime the output have only the common attributes.
Question: Is this because of type erasure?
If I pass the manifest implicitly to all the places where the consolidatedProducts is called and used, then i can see the expected JSON with all the attributes which makes me believe this is because of type erasure.
Found two ways to solve this
Use manifest implicitly everywhere to retain type information
Just update writerWithType[T] to writerWithType[T.type]
Is there any other workaround? I'm still not sure why the second solution works. If someone can explain, that would be great.

Scala Nested Object Serialization

Hi I have a case class A which contains variables pointing to another class B (with companion object, which has variables pointing to yet another class C which also has companion object). class B and C are from other libraries. What is the easier way that I could serialize my case class A?
case class A() {
val b = B
}
//B & C are defined in a library that I have no control of
object B {
val c = C
}
class B{
...
}
object C{
...
}
class C{
...
}
If these classes are already Serializable, you don't need to do anything special, so the rest of the answer assumes they aren't.
If these fields can be reconstructed from others, mark them as #transient and implement readObject (as described in http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html) to restore them. Unfortunately, you can't initialize vals in readObject and will have to write something like
case class A() {
private var _b = B
def b = _b
}
If they can't, you need to store something they can be restored from in writeObject as well.
Finally, you can use one of the third-party serialization libraries like Kryo or Scala Pickling, because basically all of them allow to add support for types not under your control (otherwise they couldn't work with the types in standard Java library!)

Writing a Python method to reference the Class attribute in the derived class, rather than base class

As someone who worked more in Java, I am having a bit of difficulty wrapping my head around polymorphic references to class attributes in Python.
What I would like to do is have a method in the base class which modifies a "static" variable (aka class attribute) of the base class, but when calling the method from the derived class, for the method to modify the class attribute of the derived class, not the base class. Note, I am NOT overriding the method in the derived class.
For example, I have something like:
class BaseClass:
itemList = []
def addItem(thing):
BaseClass.itemList.append(thing)
class Child1(BaseClass):
pass
class Child2(BaseClass):
pass
...
Child1.addItem("foo")
Child2.addItem("bar")
print(str(Child1.itemList))
I'd like: "foo"
I get: "foo, bar"
Now, I understand that because of "BaseClass.itemList.append(thing)", it will reference the class attribute of the base class.
Put another way, is there a way to avoid saying "BaseClass.itemList", but keep it static, or do I need to instead override the method in each of the child classes?
You can have a "static" class variable that can be changed by every instance of the class:
class BaseClass:
itemList = []
def addItem(self, thing):
self.itemList.append(thing)
class Child1(BaseClass):
itemList = []
class Child2(BaseClass):
itemList = []
# each class has its own "itemList"
# now we can instantiate each class and use the different itemLists:
c1 = Child1()
c1.addItem("foo")
c2 = Child2()
c2.addItem("bar")
c3 = Child1()
c3.addItem("foo2")
print(str(Child1.itemList)) # prints: ['foo', 'foo2']
print(str(Child2.itemList)) # prints: ['bar']

Difference in Scala class, trait and object memory allocation

In Scala, there's many way to create object:
For example, creating through class with new keyword
class Car {
def startEngine() = println("run....")
}
val car = new Car
car.startEngine() // run....
where car object should act like "newed" object in Java seating in heap and waiting to be garbage collected as it is de-referenced.
So, how about creating though trait?
trait Car {
def startEngine() = println("run...")
}
val car = new Car {}
car.startEngine() //run....
This is a valid syntax that creating object with using class myCar extends Car.
Instead, it just creating object from Trait.
Does it object seats in heap? (I guess it is not)
So, does it live in stack and will be de-referenced as local variable once out of scoop?
At last, how about via Object?
object Car {
def startEngine() = println("run...")
}
Car.startEngine() //run....
Is this the same case as via Trait? I believe object is more likely living in the stack.
Could someone please shed some light about the difference among this 3 syntax, in terms of memory allocation?
They all live in the heap. (Also, your second example didn't work as written.)
The difference is in code reuse.
With a class, each new object of that class runs the same code:
class Car { }
val c1 = new Car
val c2 = new Car // Same code as c1
c1.getClass == c2.getClass // true
c1 eq c2 // false--different objects on the heap
With a trait, each time you make a class from it, it copies the code (at least a forwarder). So it's less efficient but more flexible (because you can mix it into other classes when you need it). And you can make a new anonymous class for each object just by adding {}, so it's easy to do a lot of work for nothing:
trait Car { }
val t1 = new Car {} // Anon class #1
val t2 = new Car {} // Anon class #2--duplicate of #1
t1.getClass == t2.getClass // false
With an object, you explicitly say there's going to be only one. You can't (without low-level trickery) get another.
object Car { }
val o1 = Car
val o2 = Car
o1 eq o2 // true -- there is only one Car
Using a class (case 1) or an anonymous class implementing a trait (case 2) should be the same in terms of memory. Note that you can never directly instantiate a trait. E.g., new Car will not work but only new Car {} which instantiates an anonymous class that extends that trait.
Using a singleton object obviously only uses one instance of that "class". I don't think a top-level object will ever be garbage collected, so you should not store tremendous amounts of data within singleton objects.

JPA entities and equals method on abstract entity

I have a abstract entity class that 3 slightly different entities implements. In my 3 sub classes I have overriden the equals and has methods but the question is, should I also do this in the abstract entity? If I dont I will not be able to compare entities that are only defined by abstract entity unless i cast them. If i do a equals will I risk to compare to different sub entities and get that they are alike?
Example:
abstract class Log{}
SystemLog extends Log{}
UserLog extends Log{}
public void test(Log log){
Log myInner = new SystemLog();
if(log.equals(myInner)){
//do random stuff
}
}
I cannot see problem with casting. Type of argument to equals is Object, so you have to cast anyway to have access to attributes.
If you define equals method in each subclasses, when comes the situation where equals in abstract superclass is called?
If i do a equals will I risk to compare to different sub entities and
get that they are alike
You are in the risk of comparing different subentities to each others anyway. Just imagine Set with superclass as type populated with objects that are two instances of two different subclasses. It has not too much to do with do you override equals in superclass or not.
In your example equals method possibly implemented in abstract class Log will not be called, if we have implementation already in actual subclass:
Assuming:
UserLog extends Log{
public boolean equals(Object o) {
//I do override equals method so I am one who is called.
//and here you go and check type with something like
if (this == o) return true;
if (!(o instanceof UserLog)) return false;//accepts subclasses of UserLog
....
}
...
}
//And then somewhere else
Log ul = new UserLog();
test(ul);