Skip to main content

Posts

Showing posts with the label MyBatis

MyBatis: Insert multiple rows if doesn’t exist otherwise update the existing rows

The following is only content for XML file in MyBatis <insert id="insertOrUpdateMultipleRecords" parameterType="HashMap">     INSERT INTO table1  ( field1, field2, created )     VALUES     <foreach collection="inputList" item="inputListItem" separator=",">        (#{inputListItem.itemfield1}, #{inputListItem.itemfield2} , NOW())     </foreach>     ON DUPLICATE KEY UPDATE field2 = VALUES(field2)   </insert>

Insert/update into multiple rows (collections) in table MyBatis

Method 1 (only for insert) :  To add multiple record into "product" table The XML file is as follows <insert id="insertList" parameterType="HashMap" useGeneratedKeys="true"> INSERT INTO product (vendor_id, name ,description) VALUES <foreach collection="paramList" item="param" separator=","> (#{param.vendorId}, #{param.name}, #{param.description}) </foreach> </insert> The invoking Java code is as follows List products = new ArrayList(); HashMap<String, Object>  para = new HashMap<String, Object>(); Product product1 = new Product("vendor_id1,"pen","good pen"); Proudct product2 = new Product("vendor_id1,"book","good book"); products.add(product1); products.add(product2); para.put ("paramList",products); Integer status = mapper.insertList(para); Method 2: (work both for insert and update) You also...

SQL IN operator in MyBatis

"student" table with two columns "id" and "name". The following is an example query in XML file. <select id="select" parametertype="HashMap" resulttype="String"> SELECT name FROM student WHERE id IN <foreach item="item" index="index" collection="studentIds" open="(" separator="," close=")"> #{item} </foreach> </select> "studentIds" is the name of input list