Search code examples
gwtsmartgwt

What is prefered to use record.getAttribute or record.getAttributeAsTYPE?


I'm using MySQL for dev environment but my app could be on SQLServer on staging environment.

In my database, booleans (boolean) are record as VARCHAR, integers (int) are record as VARCHAR too.

Are the methods record.getAttributeAsTYPE like getAttributeAsBoolean(java.lang.String) appropriate / sure to use ? Or is it better to use something like type myvar = new TYPE(record.getAttribute("COLUNM_NAME")) ?

What is better to use between solution 1 and 2 ?

Example 1 :

boolean mybool = record.getAttributeAsBoolean("COLUNM_NAME"); // Solution 1

boolean mybool = new Boolean(record.getAttribute("COLUNM_NAME")); // Solution 2

Example 2 :

int myint = record.getAttributeAsInt("COLUNM_NAME"); // Solution 1

int myint = new Interger(record.getAttribute("COLUNM_NAME")); // Solution 2

For me, VARCHAR may be closer to java.lang.String than java.lang.Boolean or java.lang.Integer. So I think "Solution 2", in these examples, are more sure.


Solution

  • It depends. If you are absolutely certain that the value of the attribute is of the type you require, you should use getAttributeAsTYPE(). How is your data source (if you're using ds.xml) defining that field? It just might be converted implicitly by smartGWT.

    Looks like your value is stored as String (ex: record.setAttribute("COLUMN_NAME", "12345"), calling record.getAttributeAsInt("COLUMN_NAME") will likely fail with the type exception. In that case, the only thing you can do is instantiate Integer or convert it statically: Integer.parseInt(recrod.getAttribute()).

    getAttributeAsTYPE is convenient and I use it as much as I can but you have to be sure that the value is of the right type when being set.