目錄
- 第一節 MyBatis簡介
-
- 1.1 MyBatis概述
- 1.2 以前的jdbc程式代碼
- 1.3 MyBatis架構的核心
- 第二節 Mybatis入門
-
- 2.1 環境搭建
-
- 1. 下載下傳Mybatis
- 2. 建立資料庫表
- 3. 建立項目導包
- 4. 添加log4j.properties
- 2.2 開發步驟
-
- 1. 根據需求建立PO(model)類
- 2. 建立全局配置檔案SqlMapConfig.xml
- 3. 編寫映射檔案
- 4. 加載映射檔案(在SqlMapConfig.xml中配置)
- 5. 編寫測試程式,連接配接并操作資料庫
- 2.3 更多操作
-
- 1. 模糊查詢
- 2. 抽取重複代碼(簡化書寫)
- 3. 插入
- 4. 删除
- 5. 更新
- 6. 插入後自動傳回主鍵(id)
- 7. 插入後自動傳回主鍵(uuid)
- 小結
第一節 MyBatis簡介
1.1 MyBatis概述
- MyBatis 原本是apache的一個開源項目iBatis,2010年這個項目由apache software foundation 遷移到了google code,并且改名為MyBatis,實質上Mybatis對ibatis進行了一些改進。
- MyBatis是一個優秀的持久層架構,它對jdbc的操作資料庫的過程進行封裝,使開發者隻需要關注 SQL 本身,而不需要花費精力去處理例如注冊驅動、建立connection、建立statement、手動設定參數、結果集檢索等jdbc繁雜的過程代碼。
- 對jdbc的封裝架構有:Hibernate、dbutils、jdbcTemplate[spring]、mybatis
- 原理:Mybatis通過xml或注解的方式将要執行的各種statement(statement、preparedStatemnt、CallableStatement)配置起來,并通過java對象和statement中的sql進行映射生成最終執行的sql語句,最後由mybatis架構執行sql并将結果映射成java對象并傳回。
1.2 以前的jdbc程式代碼
package com.it.test;
import org.junit.Test;
import java.sql.*;
/**
* @ClassName Demo02
* @Author shuyy
* @Date 2020/9/18
**/
public class Demo02 {
@Test
public void test1() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1.加載資料庫驅動
Class.forName("com.mysql.cj.jdbc.Driver");
//2.通過驅動管理類擷取資料庫連結
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/web-ssh", "root", "root");
//3.定義sql語句?表示占位符
String sql = "select * from t_user where username = ?";
//4.擷取預處理statement
preparedStatement = connection.prepareStatement(sql);
//5.設定參數,第一個參數為sql語句中參數的序号(從1開始),第二個參數為設定的參數值
preparedStatement.setString(1, "shu");
//6.向資料庫發出sql執行查詢,查詢出結果集
resultSet = preparedStatement.executeQuery();
//7.周遊查詢結果集
while (resultSet.next()) {
System.out.println("id:"+resultSet.getString("id") + " 使用者名:" + resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//8.釋放資源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

資料庫連接配接頻繁開啟和關閉,會嚴重影響資料庫的性能。
代碼中存在寫死,分别是資料庫部分的寫死和SQL執行部分的寫死。
1.3 MyBatis架構的核心
- mybatis配置檔案,包括Mybatis全局配置檔案和Mybatis映射檔案,其中全局配置檔案配置了資料源、事務等資訊;映射檔案配置了SQL執行相關的資訊。
- mybatis通過讀取配置檔案資訊(全局配置檔案和映射檔案),構造出SqlSessionFactory,即會話工廠。
- 通過SqlSessionFactory,可以建立SqlSession即會話。Mybatis是通過SqlSession來操作資料庫的。
- SqlSession本身不能直接操作資料庫,它是通過底層的Executor執行器接口來操作資料庫的。Executor接口有兩個實作類,一個是普通執行器,一個是緩存執行器(預設)。
- Executor執行器将要處理的SQL資訊封裝到一個底層對象MappedStatement中。該對象包括:SQL語句、輸入參數映射資訊、輸出結果集映射資訊。其中輸入參數和輸出結果的映射類型包括HashMap集合對象、POJO對象類型。
第二節 Mybatis入門
2.1 環境搭建
1. 下載下傳Mybatis
- mybaits由github.com管理,下載下傳位址:https://github.com/mybatis/mybatis-3/releases.
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門 MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門 - 這裡使用MyBatis3.2.7
2. 建立資料庫表
- 在Navicat中建立資料庫mybatis_day01,選中該資料庫,按F6進入指令行,複制以下sql,enter執行
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 80013
Source Host : localhost:3306
Source Database : mybatis_day01
Target Server Type : MYSQL
Target Server Version : 80013
File Encoding : 65001
Date: 2020-09-18 18:14:13
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '商品名稱',
`price` float(10,1) NOT NULL COMMENT '商品定價',
`detail` text COMMENT '商品描述',
`pic` varchar(64) DEFAULT NULL COMMENT '商品圖檔',
`createtime` datetime NOT NULL COMMENT '生産日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '桌上型電腦', '10000.0', '電腦品質非常好!', null, '2020-09-18 13:22:53');
INSERT INTO `items` VALUES ('2', '筆記本', '7000.0', '筆記本性能好,品質好!', null, '2020-09-18 13:22:57');
INSERT INTO `items` VALUES ('3', '背包', '500.0', '名牌背包,容量大品質好!', null, '2020-09-18 13:23:02');
-- ----------------------------
-- Table structure for orderdetail
-- ----------------------------
DROP TABLE IF EXISTS `orderdetail`;
CREATE TABLE `orderdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`orders_id` int(11) NOT NULL COMMENT '訂單id',
`items_id` int(11) NOT NULL COMMENT '商品id',
`items_num` int(11) DEFAULT NULL COMMENT '商品購買數量',
PRIMARY KEY (`id`),
KEY `FK_orderdetail_1` (`orders_id`),
KEY `FK_orderdetail_2` (`items_id`),
CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`),
CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orderdetail
-- ----------------------------
INSERT INTO `orderdetail` VALUES ('1', '3', '1', '1');
INSERT INTO `orderdetail` VALUES ('2', '3', '2', '3');
INSERT INTO `orderdetail` VALUES ('3', '4', '3', '4');
INSERT INTO `orderdetail` VALUES ('4', '4', '2', '3');
-- ----------------------------
-- Table structure for orders
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '下單使用者id',
`number` varchar(32) NOT NULL COMMENT '訂單号',
`createtime` datetime NOT NULL COMMENT '建立訂單時間',
`note` varchar(100) DEFAULT NULL COMMENT '備注',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orders
-- ----------------------------
INSERT INTO `orders` VALUES ('3', '1', '1000010', '2020-09-18 13:22:35', null);
INSERT INTO `orders` VALUES ('4', '1', '1000011', '2020-09-18 13:22:41', null);
INSERT INTO `orders` VALUES ('5', '10', '1000012', '2020-09-18 13:22:50', null);
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '使用者名稱',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '位址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', '2020-09-18', '2', '南京市');
INSERT INTO `user` VALUES ('10', '張三', '2020-09-18', '1', '北京市');
INSERT INTO `user` VALUES ('27', '張大', '2020-09-18', '1', '上海市');
3. 建立項目導包
- 建立一個普通的java項目即可(示範一些mybatis的功能)
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門 - 導入下載下傳好的MyBatis的jar包
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
- 其中的pdf是mybatis自帶的使用教程,從中可以擷取一些檔案配置。
- 導入資料庫驅動包
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
- 發現mybatis裡有很多log4j的包
4. 添加log4j.properties
-
Mybatis使用的日志包是log4j的,是以添加log4j.properties。
在classpath下建立log4j.properties内容如下:【檔案内容可以從mybatis-3.2.7.pdf中拷貝】
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
- 日志級别在開發階段設定成DEBUG,在生産階段設定成INFO或者ERROR。
- 這裡暫不配置寫入檔案中
2.2 開發步驟
1. 根據需求建立PO(model)類
- User.java
package com.it.model;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName User
* @Author shuyy
* @Date 2020/9/19
**/
public class User implements Serializable {
private int id;
private String username;//使用者姓名
private String sex;//性别,1女2男
private Date birthday;//生日
private String address;//位址
public User() {
}
//id自增無需添加
public User(String username, String sex, Date birthday, String address) {
this.username = username;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
}
}
2. 建立全局配置檔案SqlMapConfig.xml
- 名字可以自定義,這裡使用SqlMapConfig.xml
- 在classpath(src)下,建立SqlMapConfig.xml檔案【SqlMapConfig.xml(檔案頭可以從mybatis-3.2.7.pdf文檔的2.1.2小節中拷貝)】
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置mybatis的環境資訊(可配置多個環境,配置多個資料源)-->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事務控制,由mybatis進行管理,如果不配置會報錯 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置資料源,采用dbcp連接配接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis_day01"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
3. 編寫映射檔案
-
在classpath下,建立sqlmap檔案夾。在sqlmap目錄下,建立User.xml映射檔案。(與hibernate的使用類似)
【Mybatis的映射檔案頭(也可以從mybatis-3.2.7.pdf檔案中拷貝)】
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace:命名空間,它的作用就是對SQL進行分類化管理,可以了解為SQL隔離
注意:使用mapper代理開發時,namespace有特殊且重要的作用
-->
<mapper namespace="test">
<!--
id:statement的id,要求在命名空間内唯一
parameterType:參數的java類型
resultType:查詢出的單條結果集對應的java類型
#{}:表示一個占位符 ?
#{id}:表示該占位符待接收參數的名稱為id。注意:如果參數為簡單類型時,#{}裡面的參數名稱可以是任意定義
-->
<select id="findUserById" parameterType="int" resultType="com.it.model.User">
SELECT * FROM USER WHERE id = #{id}
</select>
</mapper>
4. 加載映射檔案(在SqlMapConfig.xml中配置)
<!--加載映射檔案-->
<mappers>
<mapper resource="com/it/sqlmap/User.xml"></mapper>
</mappers>
5. 編寫測試程式,連接配接并操作資料庫
package com.it.test;
import com.it.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @ClassName Demo01
* @Author shuyy
* @Date 2020/9/19
**/
public class Demo01 {
@Test
public void test1() throws IOException {
//1.讀取配置檔案
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.通過SqlSessionFactoryBuilder建立SqlSessionFactory會話工廠
SqlSessionFactoryBuilder sessionFactory = new SqlSessionFactoryBuilder();
//3.通過SqlSessionFactory建立SqlSession
SqlSession sqlSession = sessionFactory.build(inputStream).openSession();
//4.調用SqlSession的操作資料庫方法
//selectOne查詢一條記錄
User user = sqlSession.selectOne("findUserById",1);
System.out.println(user);//查詢結果傳回的就是一個User對象
//5.關閉SqlSession
sqlSession.close();
}
}
2.3 更多操作
1. 模糊查詢
<!--
${}:表示拼接SQL字元串
${value}:表示要拼接的是簡單類型參數。
注意:
簡單類型:int、byte、...String
1.如果參數為簡單類型時,${}裡面的參數名稱必須為value
2.${}會引起SQL注入,一般情況下不推薦使用。但是有些場景必須使用${},比如(排序)order by ${name}
-->
<select id="findUserByName" parameterType="String" resultType="com.it.model.User">
SELECT * FROM USER WHERE username like '%${value}%'
</select>
- selectList查詢多條記錄
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
2. 抽取重複代碼(簡化書寫)
- 發現每次都要寫前面的固定代碼,下面來抽取一下,簡化書寫
package com.it.test;
import com.it.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @ClassName Demo02
* @Author shuyy
* @Date 2020/9/19
**/
public class Demo02 {
SqlSession sqlSession;
@Before
public void before() throws IOException {
System.out.println("before...擷取session");
//1.讀取配置檔案
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.通過SqlSessionFactoryBuilder建立SqlSessionFactory會話工廠
SqlSessionFactoryBuilder sessionFactory = new SqlSessionFactoryBuilder();
//3.通過SqlSessionFactory建立SqlSession
sqlSession = sessionFactory.build(inputStream).openSession();
}
@After
public void after(){
System.out.println("after...關閉session");
//5.關閉SqlSession
sqlSession.close();
}
@Test
public void test1(){
//4.調用SqlSession的操作資料庫方法
//selectList查詢多條記錄(如果符合結果的記錄有多條還使用selectOne會報錯哦)
List<User> list = sqlSession.selectList("findUserByName","張");
System.out.println(list);//查詢結果傳回的是一個list集合
}
}
- 簡化了很多
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
3. 插入
<!--插入使用者資訊
這裡的占位寫的是模型的屬性,對應一下即可
-->
<insert id="insertUser" parameterType="com.it.model.User">
insert into user (username,sex,birthday,address)
values (#{username},#{sex},#{birthday},#{address})
</insert>
- 運作成功了,但是資料沒有插入,是因為涉及增删改要送出事務(查詢不用)
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
@Test
public void test2(){
//插入
//4.調用SqlSession的操作資料庫方法
User user = new User("shu", "男", new Date(), "北京市");
sqlSession.insert("insertUser",user);
sqlSession.commit();//增删改要送出事務,否則不影響資料庫
}
- sqlSession調用傳回的是一個int類型的影響行數
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門 MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
4. 删除
<!--删除使用者-->
<delete id="deleteUserById" parameterType="int">
delete from user where id = #{id}
</delete>
@Test
public void test3(){
//删除使用者
//4.調用SqlSession的操作資料庫方法
int affectRow = sqlSession.delete("deleteUserById", 32);//傳回的是一個int類型,受影響的行數
System.out.println("受影響的行數:"+affectRow);
sqlSession.commit();//增删改要送出事務,否則不影響資料庫
}
5. 更新
<!--更新使用者-->
<update id="updateUser" parameterType="com.it.model.User">
update user set username = #{username},birthday = #{birthday},sex = #{sex},address = #{address}
where id = #{id}
</update>
@Test
public void test4(){
//更新
User user = new User();
user.setId(29);
user.setUsername("shu03");
user.setBirthday(new Date());
user.setSex("男");
user.setAddress("上海市");
//4.調用SqlSession的操作資料庫方法
int affectRow = sqlSession.update("updateUser", user);//傳回的是一個int類型,受影響的行數
System.out.println("受影響的行數:"+affectRow);
sqlSession.commit();//增删改要送出事務,否則不影響資料庫
}
6. 插入後自動傳回主鍵(id)
- MySQL自增主鍵,是指在insert之前MySQL會自動生成一個自增的主鍵。
- 我們可以通過MySQL的函數擷取到剛插入的自增主鍵:LAST_INSERT_ID()
- 這個函數是在insert語句之後去調用。
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門 - 這裡如果使用BEFORE(before)會報錯
<!--插入後自動傳回主鍵id-->
<insert id="insertUser2" parameterType="com.it.model.User">
<!--
selectKey标簽:通過select查詢來生成主鍵
keyProperty:指定存放生成主鍵的屬性
resultType:生成主鍵所對應的Java類型
order:指定該查詢主鍵SQL語句的執行順序,相對于insert語句
last_insert_id:MySQL的函數,要配合insert語句一起使用
-->
<selectKey keyProperty="id" resultType="int" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
insert into user (username,sex,birthday,address)
values (#{username},#{sex},#{birthday},#{address})
</insert>
@Test
public void test5(){
//插入後傳回主鍵id
User user = new User("shu04","男",new Date(),"南京市");
//4.調用SqlSession的操作資料庫方法
int affectRow = sqlSession.insert("insertUser2", user);//傳回的是一個int類型,受影響的行數
System.out.println("受影響的行數:"+affectRow);
sqlSession.commit();//增删改要送出事務,否則不影響資料庫
System.out.println("使用者的id:"+user.getId());
}
7. 插入後自動傳回主鍵(uuid)
- 首先要生成一張主鍵id為uuid類型的表
- 然後修改id的類型為string,重新提供一下get/set
- 上面的id是mysql自增機制生成的,無需給id指派,這裡的uuid不同,需要給它指派,否則報錯
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門 - 這裡使用的是BEFORE(before使用after會報錯)
<!--插入後自動傳回主鍵uuid-->
<insert id="insertUser3" parameterType="com.it.model.User">
<!--
selectKey标簽:通過select查詢來生成主鍵
keyProperty:指定存放生成主鍵的屬性
resultType:生成主鍵所對應的Java類型
order:指定該查詢主鍵SQL語句的執行順序,相對于insert語句
-->
<selectKey keyProperty="id" resultType="String" order="BEFORE">
select uuid()
</selectKey>
insert into user (id,username)
values (#{id},#{username})
</insert>
@Test
public void test6(){
//插入後傳回主鍵uuid
User user = new User();
user.setUsername("shu06");
//4.調用SqlSession的操作資料庫方法
int affectRow = sqlSession.insert("insertUser3", user);//傳回的是一個int類型,受影響的行數
System.out.println("受影響的行數:"+affectRow);
sqlSession.commit();//增删改要送出事務,否則不影響資料庫
System.out.println("使用者的id:"+user.getId());
}
- 注意它插入的位置,是在上一條記錄前(shu05是先插入的)
MyBatis簡介、MyBatis入門、MyBatis簡單的增删改查操作-day01上第一節 MyBatis簡介第二節 Mybatis入門
小結
parameterType和resultType
- parameterType指定輸入參數的java類型,可以寫别名或Java類的全限定名。
- resultType指定輸出結果的java類型,可以寫别名或Java類的全限定名。
#{}和${}
- #{}:相當于預進行中的占位符?。
- #{}裡面的參數表示接收java輸入參數的名稱。
- #{}可以接受HashMap、POJO類型的參數。
- 當接受簡單類型的參數時,#{}裡面可以是value,也可以是其它。
- #{}可以防止SQL注入
- ${}:相當于拼接SQL串,對傳入的值不做任何解釋的原樣輸出。
- ${}會引起SQL注入,是以要謹慎使用。
- ${}可以接受HashMap、POJO類型的參數。
- 當接受簡單類型的參數時,${}裡面隻能是value。
selectOne和selectList
- selectOne:隻能查詢0或1條記錄,大于1條記錄的話,會報錯
- selectList:可以查詢0或N條記錄