Grails data binding - data-binding

I need to bind request parameters to an instance of the following Java class (getters and setters omitted):
public class ShippingHouse {
private String name;
private String description;
private List<ShippingRule> shippingRules = new ArrayList<ShippingRule>();
}
public class ShippingRule {
private ShippingHouse shippingHouse;
private String name
}
Notice that there is a 1:N relationship between ShippingHouse and ShippingRule, but each ShippingRule also has a reference to the ShippingHouse thaat owns it.
If these were Grails command/domain classes, I would bind them with request parameters
name=foo&description=bar&shippingRules[0].name=sr0&shippingRules[1].name=sr1
But it doesn't seem like this will set the reference to the owning ShippingHouse within each ShippingRule. Is there a way I can bind this automatically, or must I write the code myself?

Don,
You will need to write code to do it yourself using BindUsing or some other approach. The binder doesn't (and shouldn't) assume anything about back references from a parent to a child. If these were GORM entities and the relationship was explicit, that is different, but in your case the binder should not assume that shippingHouse property in the ShippingRule class has anything to do with the shippingRules property in the ShippingHouse class.
Also note that lucke84 said that your "private" is implicit. Make sure you understand what that means if you are going to remove them. If you remove them the compiler is going to generate public getter and setter methods for those properties, which may or may not be what you want.

If you want to implement a 1:N relationship between the two classes, you should use the right grails approach. Something like this:
class ShippingHouse {
String name
String description
static hasMany = [shippingRules: ShippingRule]
}
class ShippingRule {
String name
static belongsTo = [shippingHouse: ShippingHouse]
}
Please note that semicolons are useless and the "private" declaration on class fields is implicit.

Related

Entity Framework Class Manipulation

I'm using Entity Framework (DB First) on a new project and wanted to add some customisation to the classes generated. However, my changes are obviously lost every time that the edmx is refreshed. I was just wondering if there is a design pattern for handling this sort of thing?
As an example, suppose I have a class with a integer property; StatusID - and I'd like to extend the entity class so that the status value can also be accessed/set via the related enum and finally a property that gets a text representation of that Enum from the description attribute. This all works, but those customisations are lost when the model is refreshed. I appreciate that the property can be converted to an enum, so the latter property that gets the description of the enum is perhaps a better example for this question.
I think I know the answer but I just wanted to put this out there in case there were some magic tricks that would allow this to work and prevent those customisations from being lost.
public int StatusID { get; set; }
public Enumerations.ValidationStatus StatusEnum
{
get
{
return (Enumerations.ValidationStatus)StatusID;
}
set
{
StatusID = (int)value;
}
}
public string StatusText
{
get
{
return MyMethodThatGetsTheEnumDescription(StatusEnum);
}
}
Two Solutions to work around the problem:
User Data Transfer Object(DTO) nd put the enum there. then use Automapper or manually map between the DB Model and the DTO Model (best practice)
Instead of enum you can use extension functions on the model and define your getter, setters and any extra properties you want as extension functions to the class
(will add some complexity to your models)

modify groovy trait private field

In my unit tests I usually use reflection to manually inject a mock to the tested class' private field:
static void setFieldValue(Object instance, String fieldName, Object fieldValue, Class instanceClass) {
def field = instanceClass.getDeclaredField(fieldName)
field.accessible = true
field.set(instance, fieldValue)
}
Where instanceClass is the class/superclass, where the class is actually declared. How can I make it work or achieve same result for a private field being declared on a groovy trait?
My IDE helped me - just use the # attribute access notation, where the fieldname is package_dots_replaced_with_underscore_TraitName__fieldName, e.g.
testee.#pl_kamilroman_DeleteEntityBean__messages

Jackson custom deserializer module to abstract class

I have a big set of classes (like more that 100) and they are all extend from some abstract class, let's call it ParentClass. Let's call child classes ChildA,ChildB, etc. How can I register custom deserializer for all children and get class type inside my Deserializer?
I tried:
module.addDeserializer(ParentClass.class, new MyObjectDeserializer());
but it does not work.
I want to skip doing (what is working):
module.addDeserializer(ChildA.class, new MyObjectDeserializer(ChildA.class));
module.addDeserializer(ChildB.class, new MyObjectDeserializer(ChildB.class));
module.addDeserializer(ChildC.class, new MyObjectDeserializer(ChildC.class));
//etc......
Class type should be known, as I am use Jackson for spring #RequestBody method, what have defined class name there.
Any ideas how this can be done?
As far as I know, I don't think there is a mechanism in jackson that will address your exact needs.
However, there are a couple alternatives you can try.
Deserializing polymorphic types with Jackson describes one such alternative, however, you would still need to explicitly define all of the supported subtypes.
Another alternative that would not require you to explicitly define deserialization relationships would be to change your class hierarchy from one of inheritance to that of a container.
For example, converting your abstract parent class to a container like so:
public class DataContainer<T> {
String commonString;
Integer commonInteger;
T subData;
}
Would allow you to simply define in your controller input function as
public String controllerFunction(DataContainer<ClassA> classA);
without a need to define all these subclass deserializations.
Late to the party but I had a similar problem which I solved by registering a custom Deserializers to my SimpleModule. The code is in Kotlin but it should be easy to port it to Java.
The class itself:
class UseBaseClassSimpleDeserializers(
private val baseClass: Class<*>,
private val baseClassDeserializer: JsonDeserializer<*>
) : SimpleDeserializers() {
#Throws(JsonMappingException::class)
override fun findBeanDeserializer(
type: JavaType?,
config: DeserializationConfig?,
beanDesc: BeanDescription?
): JsonDeserializer<*>? {
val beanDeserializer = super.findBeanDeserializer(type, config, beanDesc)
return if (beanDeserializer == null && baseClass.isAssignableFrom(type!!.rawClass)) {
baseClassDeserializer
} else {
beanDeserializer
}
}
}
How to register the custom Deserializers class to a SimpleModule:
val simpleModule = SimpleModule()
simpleModule.setDeserializers(UseBaseClassSimpleDeserializers(ParentClass::class.java, ParentClassDeserializer()))

Simplest way to use composed object as RequestParam in Spring

To following is something like... pseudo code... To illustrate what I am looking for:
// Setters and Getters ommitted to keep the example short here:
class Address
{
private String street;
private String city;
}
class AddressBookEntry
{
private String name;
private Address address;
}
class MyController
{
public void render(#RenderParam AddressBookEntry entry)
{
...
}
}
As you can see there are two POJOs (Address and AddressBookEntry). Now I would like to pass an AddressBookEntry to my Controller as http request parameter. I imagine that the URL looks like this: /target?entry.name=Random-Guy&entry.address.street=Random-Street&entry.address.city=Random-City.
As far as I understand #RenderParam doesn't work this way. I would have to create a PropertyEditor that takes a single string and construct my target Object from it, which means that I can't have an individual URL-param for each (sub-)property.
#ModelAttribute comes closer, but I could not find any hint if and how nesting of objects might work with this annotation. Additionally this annotation works without the "entry." prefix in my URL above which means that I need to make sure that I don't have multiple ModelAttributes that share a property name, correct? That sounds stressful.
How can I solve this?
It's the situation when you should use #ModelAttribute. It supports nested objects as you want.
If you need multiple #ModelAttributes, you can compose them into special class (for example, it you case that class can contain a field named entry of type AddressBookEntry, so that parameter names will be the same).

why and when to use properties

I am very confused with properties in asp.net.
I just don't understand why we use properties and when I should use them. Could anybody elaborate a little on this.
public class Customer
{
private int m_id = -1;
public int ID
{
set
{
m_id = value;
}
}
private string m_name = string.Empty;
public string Name
{
set
{
m_name = value;
}
}
public void DisplayCustomerData()
{
Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name);
}
}
Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code. Now, lets see how to use properties.
Taken From CSharp-Station
There are a couple of good reasons for it. The first is that you might need to add validation logic in your setter, or actually calculate the value in the getter.
Another reason is something to do with the IL code generated. If you are working on a large project that is spread over multiple assemblies then you can change the code behind your property without the application that uses your assembly having to recompile. This is because the "access point" of the property stays the same while allowing the implementation code behind it to be altered. I first read about this when I was looking into the point of automatic properties as I didnt see the point between those and a normal public variable.
It's easy.
All fields in class MUST be private (or protected). To show fields to another class yyou can use properties or get/set methods. Properties a shorter.
P.S. Don't declare write-only properties. It is worst practices.
Properties are a convenient way to encapsulate your classes' data.
Quoting from MSDN:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods.
Let's consider two common scenarios:
1) You want to expose the Name property without making it changeable from outside the class:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
}
2) You want to perform some checks, or run some code every time the data is accessed or set:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = (String.IsNullOrEmpty(value)) ? "DefaultName" : value;
}
}
see:
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
The most important reason is for validation purpose in setter and manipulation part can be implemented in get part.
For Ex.
Storing weekdays, which should be from 1-7, if we take normal variable and declare it as public, anyone can assign any value.
But in Properties setter you can control and validate.
The next one you can use it for tracking. That means, you can know how many times set and get functions has been called by clients (statistical purpose, may be not useful frequently).
Finally, you can control read only, write only and read/write for the properties according to your requirements.

Resources