Saturday, October 11, 2025

tmux and expected clipboard behavior with ctrl-v and middle click

Surpisingly, this took me a while to tweak (with the help of AI prompts.) I wanted, what in my opinion, was a more consistant approach inside of tmux so that mouse wheel scroll and select with vi visual mode, both copied to both clipboards (the primary - mouse wheel selects) and the secondary ( keyboard copy paste.) I'll probably just end up using autocutsel so that it sync system wide (since I've yet to find a case where I did *not* want them in sync.) But until, then here is my tmux .. I also crated a wl-copy-both file that I put in /.local/bin that I describe below.

set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-yank'
set -g mouse on
set -s set-clipboard off
#wl-copy-both is a script I put in ./local.bin
        #!/bin/sh
        # Read from stdin, copy to primary, then pass through to system clipboard
        #input=$(cat)
        #echo "$input" | wl-copy --primary
        #echo "$input" | wl-copy
set -s copy-command 'wl-copy-both'
set-window-option -g mode-keys vi
set -g @yank_action 'copy-pipe-and-cancel'
set -g @override_copy_command 'wl-copy-both'
bind-key -T copy-mode-vi v send -X begin-selection
bind-key -T copy-mode-vi y send -X copy-pipe-and-cancel 'wl-copy-both'
bind-key -T copy-mode-vi MouseDragEnd1Pane send -X copy-pipe-and-cancel 'wl-copy-both'
bind -n MouseDown2Pane run "tmux set-buffer \"$(wl-paste --primary)\"; tmux paste-buffer"
bind-key h select-pane -L
bind-key j select-pane -D
bind-key k select-pane -U
bind-key l select-pane -R
run '~/.tmux/plugins/tpm/tpm'

Saturday, February 27, 2016

Set global properties for your MyBatis mappers using Spring-MyBatis

If you need to define some global properties in MyBatis, but using spring-mybatis

In your spring config file:



In application.properties:

fooTableName=FOO_T

In your spring config file: (note sorry about the odd xml declaration, this blogger pre xml doesn't let me define the xml in one line using "/"?)


 
  
 
  
   ${fooTableName}
  
 



Now in your mapper:




Thanks to post at http://stackoverflow.com/questions/8392741/mybatis-defining-a-global-parameter/8422082#8422082

Thursday, February 18, 2016

Spring look up property dynamically

You need to look up a property from your properties file dynamically in a Spring class. If you google for this you'll find different approaches. Here is what I'm doing, which seems to work nicely.

My Spring class implements EmbeddedValueResolverAware

You then need to implement the setEmbeddedValueResolver method, so you create a field in your class:

private StringValueResolver stringValueResolver;

public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
    this.stringValueResolver = stringValueResolver;
}

Now let's say have a props file:

something.1.foo=something2
something.2.foo=something1

In my Spring class above I can look it up dynamically...

int dynamicVal = getSomeDyanmicVal();
String foo = stringValueResolver.resolveStringValue("${something."+dynamicVal+".foo}");

Thursday, October 8, 2015

ZK: multi-select listboxes with dynamic right click menu

http://learntechnology.net/2015/10/07/listbox-rightclick.html

ZK: setting menuitem style programmtically

ZK's menuitem inherits setStyle but I couldn't get it work eg...
Menuitem menuItem = new Menuitem("Foo"));
menuItem.setStyle("font-weight:bold");

However, on the forums someone pointed out setting sclass works and then defining that class style in your zul.

eg..
Menuitem menuItem = new Menuitem("Foo"));
menuItem.setSclass("itembold");

in your zul:

<style>
.itembold .z-menuitem-text {font-weight: bold}
</style>

Wednesday, June 10, 2015

https://github.com/rickcr/mybatis-generic-crud

Many times your application consists of doing common CRUD type operations (Create, Read, Update, Delete.)

I'm a big fan of MyBatis and a few solutions have been proposed to handle some of the basic CRUD in a generic fashion. This is just one 'partially generic' way to handle these common things. I say 'partially' since I've seen other approaches, such as having a single mapper and you pass in the table name and a list of columns etc. That approach is decent as well, but I've found that many times you start out generic but you'll often have to tweak a few things such that your CRUD becomes a bit more complicated. Following the approach below you have the flexibility to override whatever you want. The drawback (minor) is that, yes, you still need to create a place-holder mapper interface and you still need to create your mapper xml file and the corresponding CRUD sql in it.

The benefit is that if you follow the convention of naming the mapper methods to match the GenericCrudMapper, you typically are only writing the SQL, and the Java side becomes simple.

Note, I also created a GenericCrudService class. If you follow any of my other tutorials you'll realize that I do prefer to have my Mappers used within a service class. This is just my preference and not required. I've found in the 'real world' that I often need to do more stuff around my basic CRUD operations so that using the Mapper within a Service class gives me an extra layer to shield the client - typically the UI - from having to handle the other needed business logic around the CRUD operations.

Friday, April 10, 2015

MyBatis-Spring-ZK Maven Multimodule Project

I know have a sample project that uses MyBatis, Spring, and ZK, broken out into separate Maven modules. It's a more realistic setup for how you'd typically organize your 'real life' projects, especially in a corporate environment.   Domain module (pojos), Services module (MyBatis), Web project (ZK)

Monday, February 23, 2015

MyBatis CDI Zk Sample App (BETA)

Had the worst time trying to figure out how to get this set up working. (The Spring Mybatis setup was much easier.) The examples out there are few and far between and absolutely nothing using the above combination.

https://github.com/rickcr/mybatis-cdi-zk

I'm calling it a BETA though because I have a few questions as you can see in the README Reposting here, in case anyone can help

1) You're supposed to be able to add a weld:scan section in beans.xml but when I do, I get start up errors? It works without it, but I'd like it to only scan what it needs so I'd prefer to add the weld:scan section if I could.

2) I don't understand why/how to upgrade to weld-servlet 2.9? (see note in my pom.xml) I posted about it here posted about it here on stackoverflow

3) Why do some examples also have a beans.xml in resources/META-INF/ along with WEB-INF/ ?

4) Can not get an Integration test (DepartmentIntegrationIT) working with Arquillian. Any help much appreciated. Posted for some help here https://developer.jboss.org/message/919605

Tuesday, February 17, 2015

Ran into an interesting JAXB issue. We have several classes that all extends a Base class. At one point I introduced an object property into the base class, that also happened to be a property defined in just ONE of the subclasses. This caused any setter of this property from ANY subclasses (outside the one with that property overridden) to have this property completely ignored in the XML output. Example
@XmlRootElement(name = "animal")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Dog.class, Fish.class})
public class Animal {
    protected String movement;
     ....
}

@XmlRootElement(name = "dog")
@XmlSeeAlso({Animal.class})
@XmlAccessorType(XmlAccessType.FIELD)
public class Dog extends Animal {
   private String breed;
   protected String movement;
   ....
}

@XmlRootElement(name = "fish")
@XmlSeeAlso({Animal.class})
@XmlAccessorType(XmlAccessType.FIELD)
public class Fish extends Animal {
    private String scaleType;
    ....
}

public static void main(String[] args) {
    Dog dog = new Dog();
    dog.setBreed("lab");
    dog.setMovement("walks"); 
    String xml = AnimalJaxb.toXml(dog);
    System.out.println("dog = "+xml);

    Fish fish = new Fish();
    fish.setMovement("swims"); //WILL NOT SHOW UP IN XML!
    fish.setScaleType("normal"); 
    String xml = AnimalJaxb.toXml(fish);
    System.out.println("fish = "+xml); 
When the above runs. The "movement" property on Fish will NOT be in the XML. To fix this, I needed to remove the overridden movement property in the Dog class. What's frustrating is JAXB doesn't throw any errors or complain. The only way it will complain is if I make the base class (Animal) abstract and mark it @XmlTransient, afterwhich JAXB will complain about having "two properties with the same name."

Friday, May 31, 2013

ZK - Paginating Large Results sets in ZK with MyBatis

Benefit of this type of paging is that it doesn't load all the results up front. Useful for very large result sets. I'm a fan of MyBatis, so this example below demonstrates the use with MyBatis.



ZUL


 
 <paging id="executionsPaging"
  onCreate="executionsList.setPaginal(self)"
  totalSize="@bind(vm.executionsTotalSize)"
  pageSize="@bind(vm.executionsPageSize)"
  activePage="@bind(vm.currentPageNumber)"
  onPaging="@command('pageExecutions', pageNum=event.activePage)"
  /> 


 <listbox id="executionsList" model="@load(vm.executions)"
       selectedItem="@bind(vm.selectedExecution)".... />


Executions ViewModel


public class ExecutionsVM {
 private final static Logger logger = LoggerFactory.getLogger(ExecutionsVM.class);

 private List executions = new ArrayList();
 private ExecutionSearchFilter searchFilter = new ExecutionSearchFilter();
 private long executionsTotalSize = 0l;
 private int executionsPageSize = 25;
 private int currentPageNumber = 0;

 @WireVariable
 private ExecutionService executionService;

 @NotifyChange({"executions","executionsTotalSize"})
 @Command
 public void pageExecutions(@BindingParam("pageNum") int pageNum) {
  logger.debug("pageExecutions for pagNum {}", pageNum);
  this.currentPageNumber = pageNum;
  populateSearchFilter();
  executions = executionService.getExecutions(searchFilter);
  executionsTotalSize = executionService.getExecutionsSize(searchFilter);
 }

 private void populateSearchFilter() {
  int base = this.currentPageNumber * executionsPageSize;
  int firstRow = base + 1;
  int lastRow = base + executionsPageSize;
  searchFilter.setLowerRowLimit(firstRow);
  searchFilter.setUpperRowLimit(lastRow);
 }

}

Executions Service (wraps Mapper)


@Service
public class ExecutionService {

 @Resource
 private ExecutionMapper executionMapper;

 public List featchExecutions(ExecutionSearchFilter searchFilter) {
  return executionMapper.getExecutions(searchFilter);
 }
}

Executions Mapper


public interface ExecutionMapper {
 List featchExecutions(ExecutionSearchFilter searchFilter) 
}

Search Filter POJO


public class ExecutionSearchFilter {
 private int upperRowLimit;
 private int lowerRowLimit;
    //setters/getters
}

Executions Mapper MXL


<select id="getExecutions" resultMap="executionResultMap" parameterType="ExecutionSearchFilter">
  select
   EXECUTION_ID,
   EXECUTION_NM,
   ROW_NUM
  FROM
   (
    SELECT
     tempRow.EXECUTION_ID,
     tempRow.EXECUTION_NM,
     rownum ROW_NUM
    from
    (
     SELECT
      e.EXECUTION_ID,
      e.EXECUTION_NM
     FROM
      EXECUTION_T e
    ) tempRow
    WHERE
     rownum <![CDATA[ <= ]]> #{upperRowLimit}
   )
  WHERE
   ROW_NUM >= #{lowerRowLimit}
</select>

Friday, May 24, 2013

ZK Tips

Figured I'd list some of the tips here as I work with ZK. A lot of things aren't immediately apparent even using the online docs.

NotifyChange from your Base ViewModels


In annoying thing in ZK is that if your ViewModel extends another ViewModel and your base ViewModel decides that it needs to delegate a call to its subclass, the subclass @NotifyChange({"props}") will not automatically be triggered. As an example take:
public abstract class BaseVM {

 public void doSomething() {
  //do Stuff
  //delegate to implementing class
  doSomeStuff();
 }
 public abstract void doSomeStuff();
}

public ChildVM extends BaseVM {
 private String someProperty;

 @NotifyChange("someProperty")
 public void doSomeStuff() {
  someProperty = "blah";
 }

 public String getSomeProperty() {
  return someProperty;
    }
}
It would be nice if when "doSomeStuff" is called that "someProperty" would be able to be notified so it could display properly in your zul. Matze2 on the forums helped provide the work around http://forum.zkoss.org/question/86637/notifychange-in-subclass-methods-called-from-parent-will-not-fire/ Solution is to use the "Binder" object. Illustrated as so...
public abstract class BaseVM {
 
 protected Binder binder;

 @Init
 public final void init(@ContextParam(ContextType.BINDER) Binder _binder) {
  binder = _binder;
 }

 public void doSomething() {
  //do Stuff
  //delegate to implementing class
  doSomeStuff();
  binder.notifyChange(this, "someProperty");
 }
 public abstract void doSomeStuff();
}

public ChildVM extends BaseVM {
 private String someProperty;

 @Init(superclass=true)
 public void init() {
 }

 @NotifyChange("someProperty")
 public void doSomeStuff() {
  someProperty = "blah";
 }

 public String getSomeProperty() {
  return someProperty;
    }
}
Don't forget the @Init(superclass=true) in your subclass (I think you can add it to the Class annotation if you aren't providing an init method in your subclass.) The above is clunky but it works.

Use Constants for your GlobalCommands


Most of the documentation and examples demonstrate declaring GlobalCommmand annotations like:
@GlobalCommand
public void someMethod() { ... }
and calling it from some other ViewModel like so:
BindUtils.postGlobalCommand(null, null, "someMethod", null);
The problem with this is it's extremely fragile. If you decide to refactor your method name, you end up then having to do a search and replace for everywhere you've called your Global command with "someMethod." Possibly more annoying is you do not get any IDE help when you want to post to this GlobalCommand from another ViewModel... you need to recall the exact name of the method and if you can't recall the name you have to remember where that GlobalCommand was defined which could take time in a large project. Instead, I recommend always getting in the habit of using a GlobalCommandValues class that declares the GlobalCommand as String constant and then using it in your annotation and of course in your postGlobalCommand calls. This seems obvious, but I wasn't even aware it was an option.
//GlobalCommandValues class
public static final String SOME_METHOD = "someMethod";

//ViewModel
@GlobalCommand(GlobalCommandValues.SOME_METHOD)
public void someMethodDoesntHaveToMatchYourConstant() { ... }

//Usage
BindUtils.postGlobalCommand(null, null, GlobalCommandValues.SOME_METHOD, null);

Tuesday, June 26, 2012

EL in ZK 6 I had some issues trying to figure out some basic stuff since I didn't see it documented anywhere.

For concatenation I seemed to have to use el2's concat function...



 

For equals you can't use == , need to use el's 'eq' or 'ne'
visible="@load(productGroup.owner.id eq user.id)" 

Monday, April 2, 2012

Groovy - using a writer with FileIO

Groovy - using a writer with FileIO


public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}

Wednesday, May 4, 2011

Note Taking on the Mac/IPhone/etc

In another post I commented about Notaional Velocity and SimpleNote. I still use that as my primary note taking combination for simple things that I'll often want to look up quickly - eg Last oil changes, printer cartridge type, size of the AC filter, list of names of people I meet, list of movies to check out, etc Basically I'm using Simplenote (Notaional Velocity on Mac that syncs to Simplenote) for anything I'd want quickly on my iPhone as well.

For work stuff - tasks, project notes, developer code snippets etc. I'm using MacJournal. I toyed around with using Evernote but I didn't like it for work notes. The main reasons I didn't like Evernote is

1) You can't reorganize your notes in a predefined order. They're argument is 'use the search feature.' And I agree for simple notes that's fine. But for work I often keep a list of notes that I have neatly organized with a few things at the top such as "server names" "common commands" etc. With MacJournalI can always keep them at the top. With Evernote you can't.

2) They don't have the nice split vertical pane that MacJournal has. They have it - but it defaults to a view that has icons in it and it's just a waste of space. They do have a flat list view but it splits it horizontally which still isn't what I want.

3) Evernote now does support nested folders, but it's still sort of goofy (if you drag a folder onto another you'd expect it to immediately just become a subfolder - but that's not what happens.) MacJournal makes it intuitive with nested journals.

Thursday, March 4, 2010

National Velocity plus Simplenote

I’m really digging this combo for note taking on my Mac and iPhone. I was using Evernote, but it’s a bit heavy and I only seem to be keeping text notes.

National Velocity (I know goofy name and the website is lacking) is a nice light weight note taking app for the Mac. I was using Mori, which I liked but they currently have no way to sync to my iPhone. National Velocity will synch with Simplenote which is a really nice note taking application for the iPhone (free.) Simplenote has a nice web client as well (which is what National Velocity syncs with behind the scenes.)

Thursday, January 28, 2010

Dropbox - Simply Awesome


  1. Easy to use. Looks just like any other drive on your system. ~/Dropbox (by default.)
    Files are always there, even when not connected to the internet. Only syncs when connected to the internet, and the growl notifications are really slick.
  2. Drop something in your public folder and make it available easily with right click "copy public link" - send the link out in an email. Really nice for sharing large files or maybe posting an file or image that you want to link to in a forum post or email list where you can't add an attachment. Can even act as a mini static webserver for quick previews of an html/flash site - just give someone the link to a folder in your public dir.
  3. Works as a mini-time machine/backup. Keeps backups of versions of your files.
  4. Easily create a shared private directory. This is really great for work or collaboration between people (probably great for contractor communication with a client on screen shots etc.) No need to use sharepoint (blah) just throw in your uml diagrams or project notes into the dir and everyone it's shared with gets notified and gets a copy whenever their online. (It actually has some versioning as well, so acts like mini vcs.) This one guy at work has created some nice unix scripts that he updates frequently... now I just share a directory with him on dropbox, so as he makes changes to the scripts, I have them (I just added the shared dir to my system path.)
  5. Great for keeping files in sync between different computers. I put my 1Password file out there and now my wife's 1Password app and mine all share the same file (encrptyped of course.) Can be great for sharing any files that you want across systems.
  6. ***iPhone app*** awesome. GREAT PDF solution. A lot of iphone people complain about not being able to keep PDFs on the iphone - their solutions are all pretty lame (email storage.) Well, with Dropbox you have access to ANY file in there. Great place to store pdf books you want to read using the iphone.
  7. Cross-platform. Nice to have a client for Mac/Windows/Linux
  8. 2GB free storage is pretty nice.

Monday, January 18, 2010

@Scott [Organization and some MINOR Mac complaints]

@Scott In reference to some comments Scott and I were having on a blog post found here: http://osxhelp.com/mastering-safaris-bookmarks-bar/

Excellent points Scott. In fact your comments on the bookmark folder setup is exactly what I'm starting over with on a fresh mac OS install (clean up time:). Once I get it just right and clean out all the dead stuff I'll start a new sync with xmarks.

Regarding the wiki idea, I was doing that for my code snippets just like you are, and I'll probably go back to it (since I like that it's not tied to an OS), although in the meantime I switched over to using Mori for all that kind of stuff. I just found it easier using a native app - speedy and fast. A wiki takes more thought on things - especially with markup and organization, etc. Overall though the wiki is a great approach though, but with mori it's easier to reorganize things (folders) as my needs progress.

I should point out that I'm trying to replace Mori with now using Evernote for what I used Mori for - mainly code snippets of things ('What was that unix are command again to recursively grep through files?') The benefits of Evernote was that I also have my notes on the iphone, and it had nice safari integration for clipping things. The drawback (and this is somewhat large) is that the organization seems sort of lame. I didn't find a way to have subdirectories for content - you can create new parent content directories and I think you have tags as well (I just haven't used it enough yet to have a complete verdict on how much I'll like evernote to replace Mori.) Right now Mori is the speediest solution I've found, and it has some nice export options - but I'd love to see a hyperlinked export option then you could just export and have it as a make-shift wiki. Lack of an iphone version/sync is sort of depressing to me so that's why I'm looking more towards evernote as a longer-term solution.

I'll be interested in solutions you've tried to 'get organized.' I know the wiki idea is one - which I do like, but I don't know if I'd be diligent enough to keep up with it. For example, maybe your researching 'design patterns for event handling in flex' - some of the articles are too long to just copy snippets out of into a wiki, so I suppose I should then copy and paste the links of what I find into a wiki? A good idea, just not sure if I'd realistically do it since I could be lazy during my research and wouldn't want to be updating a wiki entry while reearching links at the same time.

Back to the Mac itself... I know I'm being overly critical because I certainly like it better than Windows and even though I keep playing around with Linux distros - I end up getting the best of everything by just sticking with the MacOS so I dabble with them just for fun. I suppose I'd still disagree with you on just those small points above (like maximize and the add bookmmark dialog) and they really are small so it isn't a big deal. Just some other comments I'll throw on some small Mac-ish things that I don't like very much (again - reiteration - I find the Mac OSX to be the best OS out there :)

  • Maximize comment again. It's not that big a deal to me either since once I have the window sized I rarely change it, but I still prefer maximize acting like 'full screen (well not true full screen but you get the idea.) The reasoning mac proponents often give (copied from a post) is: " In most cases, maximizing a window serves no practical purpose, and actually just ends up wasting screen space by filling it with blank whitespace. " I'd disagree with that since web layouts often aren't fixed. In fact the very forum I copied that quote from http://forums.macrumors.com/archive/index.php/t...%3C/index.php/t-155116.html is a perfect good example. On my mbp my res is set at 1650x1050. The content on that forum is flowing so by maximizing horizontally I get to read a lot more posts without scrolling. That's efficient to me. I know everyone has their own ideas of 'what's best' so I won't belabor the point much more.
  • .DS_Store files. I hate them. I understand their purpose but there has to be a better way to store metadata (possibly a mini db like Pathfinder uses.) Nothing's more embarrassing than sending out a zip where you forgot to remove them. (That's like getting those thumbnail files from a windows user in an image dir)
  • Finder. Not a fan of it. No right click on a file to cut (only copy). Can't easily always organize by folders first than files. Have to go to settings tweaks to show hidden files. No split view. No tab view. No nice preview panel (yes there is 'quick view' but not really the same thing.) Fortunately there is Pathfinder as a replacement. Great app.
  • Default way search results are displayed. In Pathfinder or on windows/linux when you search within a gui filebrowser you get results that show you the file path without having to actually click on each search result line and look at some goofy folder icon bread crumb trail in the bottom of the finder window. That's horrible inefficient. Many times my search results return multiple folders/files with the same name, and it's a pain on the default Mac search quickly determining which is which. Maybe there is a way to get the Mac to show the file path in the search results, if so someone tell me because I haven't found it. In the meantime there is EasyFind (free.)
  • I wish there was a better way Safari handled its downloads window. At least show a status in a bottom bar or something that is easy to see. It doesn't confuse me much since I know to cmd-~ to get to my downloads window, but I've watched my parents get super confused over this. They end downloading things multiple times because they don't see anything happening so they keep re-clicking the download link:)
  • iTunes music library and iPhoto libraries. Maybe for the average user, their structure and operation is great so I'm not going to say Apple took a bad approach. Personally I find itunes for music confusing and opt just to use VLC and pathfinder for most everything media related (itunes store is cool though.) iPhoto gets confusing also with its modified versions of files. What if I'm not in iPhoto and I want to use gmail to send the image that I just modified? Just seems easier to be more old-skool when it comes to photo managment, but I get their intent and for many users it probably works just fine.
  • Not Mac related, but before the Mac had Spaces, what did you think of MDI apps like Photoshop? My brother is a graphic artist and has always used a Mac so I guess they got used to Photoshop without having multiple desktops, but if I couldn't have all those photoshop menus on a clean workspace I'd go nuts. Why would I want to see a paintbrush menu and four other other menu windows with safari or terminal in the background? Just seems to messy. With spaces it's not a big deal, but multiple workspaces is relatively new to the Mac (I think Windows photoshop wasn't an MDI interface but I could be wrong there.)

Like you mentioned though, Scott, there are always some good 3rd party apps to overcome any of these things, so the above comments are quite trivial. Fun discussion though.

Thursday, December 3, 2009

vim plugins

I need these to be efficient:

NERDTree http://www.vim.org/scripts/script.php?script_id=1658
bufmru http://www.vim.org/scripts/script.php?script_id=2346
bufkill http://www.vim.org/scripts/script.php?script_id=1147
LargeFile http://www.vim.org/scripts/script.php?script_id=1506

Friday, July 10, 2009

Cigars I Really Enjoy

My tastes often change over time, so this list could easily change (not listing real Cubans.) For the most part, I'm not listing sizes here either.


  1. My Father Limited Edition 2011

  2. Arturo Fuente Anejo (Shark)

  3. Tatujae Verite 2009

  4. My Father Limited Edition 2010

  5. Paul Garmirian Symphony 20 Ltd

  6. Padron 1926

  7. Padron 1964 Anniversary (Natural & Maduro)

  8. God of Fire

  9. Tatujae (Cabinet Selection/aka Brown Label)

  10. La Riqueza

  11. Illusione Epernay

  12. Esteban Carreras 10 Anos

  13. Liga Privada (#9 and T52)

  14. Don Pepin Garcia - Blue Label (and White Series JJ)

  15. Cabaiguan

  16. Viaje Oro (the Platino is great also, which is more medium)

  17. Cruzado

  18. San Cristobal

Sunday, May 3, 2009

Set pojo properties with groovy sql row results

This is probably documented somewhere that you can do this with a Map and a regular typed Object, I just hadn't run across it and tried it to see what happens.

You can just pass in a Map of properties to an Object and as long as you don't have any properties in your Map that are not defined in the class, it'll work fine. As an example:


class Person {
String name
Integer age
String address
}

def map = [ name: "Joe", age: 4, address: "Somewhere"]

Person p = new Person(map)

println "Peson name: $p.name, address: $p.address"


This comes in real handy when want you want to populate some groovy sql results into a collection of typed objects. As an example:


def getPersons() {
def persons = []
sql.eachRow("Select * from Person") {
persons << new Person( it.toRowResult() )
}
return persons
}

Blogger Syntax Highliter