Question

I found the below code in an example and it works. But I don't know why.

My questions are:

  • How does the mapping from getDrugsWithAlert(int count) get assigned to #{maxrowcount} (I can put anything inside: #{maxrowcount}, #{mcount} and it does not seem to matter);

  • how/why the if test="_parameter != null and _parameter > 0 works?

My DAO interface looks like this:

@Repository
public interface DrugMasterDao {
    public List<Drug_Master> getDrugsWithAlert(int count);
}

My mapper file looks like this:

<mapper namespace="org.mydb.formulary.drugmaster.dao.DrugMasterDao">

    <select id="getDrugsWithAlert" parameterType="int"  
            resultType="org.mydb.formulary.drug_master.model.Drug_Master">

        Select drug_id , drug_name , drug_alert_date, drug_alert_source
          from (select drug_id,drug_name,to_char(drug_alert_datetime,'MM/DD/YYYY') as
                       drug_alert_date ,drug_alert_source
                  from drug_master
                  where drug_status ='A' and length(drug_alert) > 0
                  order by drug_alert_datetime DESC )

       <if test="_parameter != null and _parameter > 0">
          where rownum &lt;= #{maxrowcount}
       </if>
    </select>
 </mapper>
Was it helpful?

Solution

Your queries have declared parameters that will be replaced with their corresponding values upon execution. The parameter names are properties on the object that you send to the query.

But your mapping has parameterType="int" which is a simple value. The value will replace the parameter entirely. If your parameter type is a Map or object of some sort then the names become important because they name the keys or properties of the object, respectively.

Because you have an int the name is unimportant and can be #{maxrowcount}, #{mcount}, #{whatever}. That's why the first part works.

For the second part it's trickier because _parameter is undocumented. MyBatis is a nice framework but, sadly, lacks on the documentation part. The input parameter is stored under the key _parameter in the mapping context. In this case it's your int parameter. That's how the second part works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top