MyBatis SELECT基本查詢實(shí)現(xiàn)方法詳解
1、返回一個(gè)LIST
<!-- public List<Employee> getEmpsByLastNameLike(String lastName); --> <!--resultType:如果返回的是一個(gè)集合,要寫集合中元素的類型 --> <select resultType='com.atguigu.mybatis.bean.Employee'> select * from tbl_employee where last_name like #{lastName} </select>
2、將查詢記錄封裝為一個(gè)Map
<!--public Map<String, Object> getEmpByIdReturnMap(Integer id); --> <select resultType='map'> select * from tbl_employee where id=#{id} </select>
返回一條記錄的map;key就是列名,值就是對應(yīng)的值。
3、多條記錄封裝為一個(gè)map
@MapKey('id')public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);
<select resultType='com.atguigu.mybatis.bean.Employee'> select * from tbl_employee where last_name like #{lastName} </select>
Map<Integer,Employee>:鍵是這條記錄的主鍵,值是記錄封裝后的javaBean。
@MapKey:告訴mybatis封裝這個(gè)map的時(shí)候使用哪個(gè)屬性作為map的key。
4、多條件查詢
public Employee getEmpByIdAndLastName(@Param('id')Integer id,@Param('lastName')String lastName);
<select resultType='com.atguigu.mybatis.bean.Employee'> select * from tbl_employee where id = #{id} and last_name=#{lastName} </select>
@Param('id')標(biāo)注查詢條件的key,查詢條件都會封裝為map。id為key,value為參數(shù)所對應(yīng)的值。
5、插入操作(自增主鍵mysql)
<insert parameterType='com.atguigu.mybatis.bean.Employee' useGeneratedKeys='true' keyProperty='id' databaseId='mysql'> insert into tbl_employee(last_name,email,gender) values(#{lastName},#{email},#{gender})</insert>
獲取自增主鍵的值:
mysql支持自增主鍵,自增主鍵值的獲取,mybatis也是利用statement.getGenreatedKeys();
useGeneratedKeys='true';使用自增主鍵獲取主鍵值策略
keyProperty;指定對應(yīng)的主鍵屬性,也就是mybatis獲取到主鍵值以后,將這個(gè)值封裝給javaBean的哪個(gè)屬性。
6、插入操作(非自增主鍵oracle)
①非自增主鍵oracle BEFORE格式推薦
<!-- public void addEmp(Employee employee); --><insert databaseId='oracle'> <selectKey keyProperty='id' order='BEFORE' resultType='Integer'> select EMPLOYEES_SEQ.nextval from dual </selectKey> insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) values(#{id},#{lastName},#{email) </insert>
②非自增主鍵oracle AFTER存在并發(fā)有可能不準(zhǔn)確,不推薦
<!-- public void addEmp(Employee employee); --><insert databaseId='oracle'> <selectKey keyProperty='id' order='AFTER' resultType='Integer'> select EMPLOYEES_SEQ.currval from dual </selectKey> insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) values(#{id},#{lastName},#{email}) </insert>
Oracle不支持自增;Oracle使用序列來模擬自增;每次插入的數(shù)據(jù)的主鍵是從序列中拿到的值;如何獲取到這個(gè)值;
使用selectKey:
keyProperty:查出的主鍵值封裝給javaBean的哪個(gè)屬性
order='BEFORE':當(dāng)前sql在插入sql之前運(yùn)行AFTER:當(dāng)前sql在插入sql之后運(yùn)行resultType:查出的數(shù)據(jù)的返回值類型
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. MySQL存儲過程例子(包含事務(wù)、參數(shù)、嵌套調(diào)用、游標(biāo)循環(huán)等)2. navicat for mysql導(dǎo)出sql文件的方法3. 如何實(shí)現(xiàn)MySQL數(shù)據(jù)庫的備份與恢復(fù)4. mybatis plus代碼生成工具的實(shí)現(xiàn)代碼5. Mysql入門系列:MYSQL創(chuàng)建、刪除和選擇數(shù)據(jù)庫6. navicat for mysql導(dǎo)出數(shù)據(jù)庫的方法7. Oracle一家的幸福生活8. 破解Oracle中國高層頻繁變動之謎9. SQL Server下7種“數(shù)據(jù)分頁”方案全網(wǎng)最新最全10. Navicat Premium操作MySQL數(shù)據(jù)庫(執(zhí)行sql語句)
