2009-04-23

Ibator's deleteByExample() and MySQL.

If you use 'alias' when generating Ibator artifacts and your database is MySQL, you cannot use deleteByExample() because of MySQL bug #12811.
To workaround the issue, you can use the following plugin.

import java.util.List;

import org.apache.ibatis.ibator.api.FullyQualifiedTable;
import org.apache.ibatis.ibator.api.IbatorPluginAdapter;
import org.apache.ibatis.ibator.api.IntrospectedTable;
import org.apache.ibatis.ibator.api.dom.xml.Element;
import org.apache.ibatis.ibator.api.dom.xml.TextElement;
import org.apache.ibatis.ibator.api.dom.xml.XmlElement;

public class MySqlDeleteByExamplePlugin extends IbatorPluginAdapter
{

 public boolean validate(List<String> warnings)
 {
  return true;
 }

 @Override
 public boolean sqlMapDeleteByExampleElementGenerated(XmlElement element,
  IntrospectedTable introspectedTable)
 {
  FullyQualifiedTable table = introspectedTable.getFullyQualifiedTable();
  for (int i = 0; i < element.getElements().size(); i++)
  {
   Element elem = element.getElements().get(i);
   if (elem instanceof TextElement
    && elem.getFormattedContent(0).contains("delete from "))
    replaceDeleteStatement(element, table, i);
  }
  return true;
 }

 private void replaceDeleteStatement(XmlElement element, FullyQualifiedTable table, int index)
 {
  StringBuilder sb = new StringBuilder();
  sb.append("delete from ");
  String alias = table.getAlias();
  if (alias != null && alias.length() > 0)
  {
   sb.append(alias);
   sb.append(" using ");
  }
  sb.append(table.getAliasedFullyQualifiedTableNameAtRuntime());

  element.getElements().set(index, new TextElement(sb.toString()));
 }
}

No comments:

Post a Comment