1

I am using myBatis to write some SQL queries, the problem is that I have tables that have several columns ( around 50 column). So writing the insert query like this :

<insert id="insert" parameterType="com.atos.tables.Table1>
  insert into ot ( id, c1, c2, ....,c50) values (#{id}, #{c1},#{c2},... #{c50})
</insert>

is very tedious.

I can create a method in java that generate the String of the queries automatically, but how can I call this method from the mapper.xml ?

And if I use myBatis annotations I cannot call a method in an interface. I don't know if I am missing something, is there a way to do this??

Thanks for helping.

2 Answers 2

1

There isn't any way I'm aware of for doing this directly.

What you could try is to generate the columns at compile or deploy time in a separate file as <sql> elements and then include them in your mapper files as needed.

There is also this statement-builders feature added to MyBatis that alows you to build SQL from code so maybe have a look at that also.

Sign up to request clarification or add additional context in comments.

Comments

1

The main problem is not in query string generation: this can be done easily using scripting support for example with mybatis-velocity.

The main problem is to set parameters dynamically. This can done in mybatis-velocity by defining custom directive which will dynamically create org.apache.ibatis.mapping.ParameterMapping.

It may be used in mapper like this:

<insert id="insert">
   insert into ot (
     #field_names('com.atos.tables.Table1')
   ) values ( @{id},
     #params_for_fields('com.atos.tables.Table1')
   )
</insert>

Here #field_names adn #params_for_fields is a custom directives which you need to implement. field_names should iterate over fields of class which is passed as argument and generate comma separated list of field.

params_for_fields should create new parameters mapping and add them to list of parameters mappings maintained by velocity language driver.

You may look to built-in repeat directive and ParameterMappingCollector to see how parameter mappings can be created and accessed.

2 Comments

The problem with this solution is that my fields have complex name (is not c1 , c2.. I used these names only to simplify), In the method of generation of the query I get the fields from the class and I generate the query.
This is not a problem. You can shape custom directives so you can create directives which iterates over the fields of a class. I've updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.