MyBatis SQL statement for Mysql and mybatismysql
This document describes some statements that are used to operate databases using Mybatis for future reference.
I. Multi-condition Query
Schematic SQL statement: SELECT t_field1, t_field2 FROM table_name WHERE t_field3 (BETWEEN startTime AND endTime) AND t_field4 IN (xxx, xxx, xxx)
Mapper Interface Configuration:
public List<Chat> query(@Param("startTime") long startTime, @Param("endTime") long endTime, @Param("sids") List<Long> sidList);
Mapper. xml configuration:
<select id="query" resultMap="chat"> SELECT uid,content from tableName WHERE ( UNIX_TIMESTAMP(data_time) >= #{startTime} ) AND ( UNIX_TIMESTAMP(data_time) <= #{endTime} ) AND sid IN <foreach collection="sids" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach> </select>
ResultMap maps the column names in the database to the JavaBean attribute names to form Java objects. Chat is a JavaBean class with two fields (uid and content.
<ResultMap id = "chat" type = "Chat"> <! -- Chat is in mybatisConfig. alias defined in xml (the fully qualified package name is in mybatisConfig. configured in xml) --> <id property = "id" column = "id"/> <result property = "uid" column = "uid"/> <result property = "content" column =" content "/> </resultMap>
Explanation: ① The method name in the Mapper interface corresponds to the <select id in Mapper. xml.
② The Mapper interface implements multiple parameter passing through @ Param. For details, refer to "using parameter annotations to pass multiple parameters" in MyBatis simple usage and getting started ". The parameter name specified in @ Param corresponds to the name in the select query statement. For example, @ param ("startTime") corresponds to # {startTime }. @ Param ("endTime") corresponds to # {endTime }.
@ Param ("sids") corresponds to foreach collection = "sids"
③ Use the foreach statement to implement multi-condition matching for the sid field. Equivalent to sid IN {xxx1, xxx2, xxx3 ....}
④ For the String-type data_time field in the database, it is first converted into a UNIX Timestamp and then compared with startTime and endTime.Note that <= is expressed with <. Otherwise, the following error is reported:
tag name are expected