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入門系列:建立MYSQL客戶機(jī)程序的一般過程2. MySql導(dǎo)出后再導(dǎo)入數(shù)據(jù)時(shí)出錯(cuò)問題3. MySQL Innodb 存儲結(jié)構(gòu) 和 存儲Null值 用法詳解4. mysql命令行客戶端結(jié)果分頁瀏覽5. MYSQL技巧:為現(xiàn)有字段添加自增屬性6. centos7下安裝mysql6初始化安裝密碼的方法7. MySql使用mysqldump 導(dǎo)入與導(dǎo)出方法總結(jié)8. mysql-bin.000001文件的來源及處理方法9. mybatis-plus如何使用sql的date_format()函數(shù)查詢數(shù)據(jù)10. DB2 9(Viper)快速入門
