Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map a List<string> in iBatis?

I have a class like this

public SomeClass
{
   private List<string> _strings = new List<string>();

   public IEnumerable<string> Strings
   {
      {  get return _strings; }
   }
}

How would I do the mapping for _strings?

I tried this, but it complains about the List typehandler not being found, which it doesn't complain about if I mapped it as an object.

<result property="_strings" column="value" />

So I searched Google and found this workaround (originally for a Java issue, no idea if it's suppose to work in C#)

<result property="_strings" resultMapping="someMapping.StringList"/>

<resultMap id="StringList" class="System.String">
  <result property="" column="Value"/>
</resultMap>

This at least lets the test run, and it returns the rest of my object fine, and my list has the right number of entries, except they're all blank.

I think the problem is that the property attribute is blank, but I'm not sure whats suppose to go there. (I also tried using 'value', but that didn't work either). This seems like it should be a lot simpler and I'm just overlooking something obvious.

Thanks.

like image 446
Brandon Avatar asked Jul 14 '09 20:07

Brandon


2 Answers

Use auto result-mapping of IBatis. This is the solution in Java which you can easily map to C#. This is your sql map:

<sqlMap namespace="Users">
<select id="names" resultClass="java.lang.String">
        select first_name as firstName from user
</select>
<sqlMap>

And then you can call it like this:

List<String> userNames = (List<String>)sqlMap.queryForList("Users.names");

So you don't have to create a custom type with one property to do that.

like image 84
user18943 Avatar answered Nov 14 '22 22:11

user18943


My experience is the with Java version of iBATIS, but the solution should still work for the C# peeps out there.

Given a class

class MyClass {
  int id;
  List<String> firstName;
}

You can populate the list of strings or other simple types (classes without attributes, such as Integer, String, etc.) with the following two resultMaps

<sqlMap namespace="ns">
  <resultMap id="ListMap" class="string">
    <result property="firstName" column="firstName" 
            javaType="java.util.List" jdbcType="VARCHAR"/>
  </resultMap>

  <resultMap id="PrimaryMap" class="MyClass" groupBy="id">
    <result property="id" columnName="id"/>
    <result property="firstname" resultMap="ns.ListMap" javaType="java.util.List"/>
  </resultMap>

  <select id="MySuperQuery" resultMap="PrimaryMap">
    select id, firstName from user
  </select>
</sqlMap>

Hope this helps.

like image 36
inanutshellus Avatar answered Nov 14 '22 21:11

inanutshellus