今天MyBatis连接MySQL时,出现一个问题,让在下着实恼火,特此记录。
问题如下:就是在Dao中我取出数据的时候,会报SQL语句错误,具体错误如下:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''desc' limit 0, 20' at line 5
具体代码如下:
Dao层代码:
public interface CampaignDAO extends SqlMapper{ /** * 查看所有Campaign信息 */ public List<Campaign> list(@Param(value = "orderBy") String orderBy, @Param(value = "order") String order, @Param(value = "fromIndex") int fromIndex, @Param(value = "lines") int lines); }
Mapper对应代码:<!-- 查看所有活动 --> <select id="list" parameterType="Map"resultType="com.miaozhen.cms.business.model.Campaign"> <![CDATA[ select mc.MCampaignId, mc.MCampaignName, mp.StartTime, mp.EndTime, mc.AgencyId, mc.AdvertiserId, mc.BrandInfoId from st_monitor_campaign mc left join st_media_plan mp on mc.MediaPlanId = mp.MediaPlanId where mc.IsDeleted = 0 order by #{orderBy} #{order} limit #{fromIndex}, #{lines} ]]> </select>
后来经过多方调试发现,可以将xml中的文件改为如下:问题就解决了。<!-- 查看所有活动 --> <select id="list" parameterType="Map" statementType="STATEMENT" resultType="com.miaozhen.cms.business.model.Campaign"> <![CDATA[ select mc.MCampaignId, mc.MCampaignName, mp.StartTime, mp.EndTime, mc.AgencyId, mc.AdvertiserId, mc.BrandInfoId from st_monitor_campaign mc left join st_media_plan mp on mc.MediaPlanId = mp.MediaPlanId where mc.IsDeleted = 0 order by ${orderBy} ${order} limit ${fromIndex}, ${lines} ]]> </select>具体原因是,如果加上如下代码(当然别忘了#相应换成$),就会是在执行到Dao层时,直接将参数插入查询语句,而不是以预编译语句的形式,然后再将参数传入。 statementType="STATEMENT"