MyBatis實(shí)現(xiàn)萬(wàn)能Map和模糊查詢
我們?cè)谏弦还?jié)博文里面將到利用Mybatis實(shí)現(xiàn)CRUD操作的時(shí)候,我們?cè)跀?shù)據(jù)庫(kù)表中新增一條數(shù)據(jù)是這樣操作的:
實(shí)體類(lèi)對(duì)象的字段有:
package com.hpf.bean;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;//編寫(xiě)實(shí)體類(lèi)User@Data@AllArgsConstructor@NoArgsConstructorpublic class User { private Long id; private String username; private String password;}
新增一條記錄的xml文件配置內(nèi)容為:
<insert parameterType='com.hpf.bean.User'>insert into userinfo (id,username,password) values (#{id},#{username},#{password})</insert>
其中,#后帶的字段名都是我們實(shí)體類(lèi)用戶類(lèi)里面一模一樣的字段名。
接著我們?cè)賮?lái)試試用Map的方式實(shí)現(xiàn)用戶記錄的新增:
<insert parameterType='Map'>insert into userinfo (id,username,password) values (#{id},#{user},#{pwd})</insert>
測(cè)試部分:
@Test public void testAddUserByMap(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserDao mapper = sqlSession.getMapper(UserDao.class);Map<String,Object> map = new HashMap<>();map.put('id', 6L);map.put('user', '張三');map.put('pwd', '666');int res = mapper.addUserByMap(map);sqlSession.commit();sqlSession.close(); }
說(shuō)明:我們業(yè)務(wù)相關(guān)的參數(shù)需要哪些字段內(nèi)容,我們就往map里面?zhèn)髂男┳侄蝺?nèi)容就行。
模糊查詢要求查詢下表內(nèi)為李性的用戶信息:
package com.hpf.dao;import com.hpf.bean.User;import java.util.List;import java.util.Map;//這個(gè)接口實(shí)現(xiàn)的是對(duì)于用戶的相關(guān)操作public interface UserDao { //模糊查詢用戶信息 List<User> getUserByLike(Map map);}
<select parameterType='Map' resultType='com.hpf.bean.User'>select * from userinfo where username like #{value} </select>
@Test public void testGetUserByLike(){SqlSession sqlSession = MyBatisUtils.getSqlSession();UserDao mapper = sqlSession.getMapper(UserDao.class);Map<String,Object> map = new HashMap<>();map.put('value', '李%');List<User> userByLike = mapper.getUserByLike(map);for(User user:userByLike) System.out.println(user); }
結(jié)果如圖所示:
說(shuō)明:模糊查詢?cè)谶@種方式下其實(shí)還有一種寫(xiě)法也可以得出結(jié)果,但是為了防止sql注入問(wèn)題,我們不建議如下的寫(xiě)法:
<select parameterType='Map' resultType='com.hpf.bean.User'>select * from userinfo where username like #{value}'%'</select>
到此這篇關(guān)于MyBatis實(shí)現(xiàn)萬(wàn)能Map和模糊查詢的文章就介紹到這了,更多相關(guān)MyBatis 萬(wàn)能Map和模糊查詢內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 用腳本和查詢主動(dòng)監(jiān)視Oracle 9i性能2. ORACLE創(chuàng)建DBlink的過(guò)程及使用方法3. Oracle 數(shù)據(jù)庫(kù)集中復(fù)制方法逐步精細(xì)4. 關(guān)鍵字:oracle_sid,server_name,網(wǎng)絡(luò)連接,數(shù)據(jù)庫(kù)啟動(dòng)5. MySQL Community Server 5.1.496. Oracle和MySQL的一些簡(jiǎn)單命令對(duì)比7. MySql導(dǎo)出后再導(dǎo)入數(shù)據(jù)時(shí)出錯(cuò)問(wèn)題8. MySQL主備操作以及原理詳解9. oracle定時(shí)分析用戶下的所有表10. Oracle數(shù)據(jù)庫(kù)9i DataGuard的安裝與維護(hù)
