在建設(shè)政府門(mén)戶(hù)網(wǎng)站時(shí)要充分考慮到引流推廣是什么意思
動(dòng)態(tài)SQL
什么是MyBatis的動(dòng)態(tài)SQL?
**定義:**根據(jù)不同的條件拼接SQL語(yǔ)句,實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)更準(zhǔn)確的操作;
**實(shí)現(xiàn):**映射器配置文件或者注解
常用的動(dòng)態(tài)SQL元素
- if 元素:判斷語(yǔ)句,單條件分 支判斷.
- choose 元素 (when,otherwise):?多條件分支判斷,等同于java 的 switch.
- trim (where,set): 輔助元素,用于處理一些 SQL 拼接的問(wèn)題.
- foreach 元素 :循環(huán)語(yǔ)句,在in 語(yǔ) 句等列舉條件常用
- bind 元素 :自定義上下文變量, 傳遞參數(shù).
if元素
語(yǔ)法:
語(yǔ)法
< if test =”條件”> 滿(mǎn)足條件的語(yǔ)句 </ if>
注意:拼接SQL語(yǔ)句的時(shí)候要注意AND符號(hào)
實(shí)現(xiàn):
Student.java 下面所需要的bean同這個(gè)一樣
package bean;import java.io.Serializable;
import java.util.Date;public class Student implements Serializable{private int sid;private String sname;private Date birthday;private String Ssex;private int classid;private Clazz clazz;public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getSsex() {return Ssex;}public void setSsex(String ssex) {Ssex = ssex;}public int getClassid() {return classid;}public void setClassid(int classid) {this.classid = classid;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public Student(int sid, String sname, Date birthday, String ssex, int classid, Clazz clazz) {super();this.sid = sid;this.sname = sname;this.birthday = birthday;Ssex = ssex;this.classid = classid;this.clazz = clazz;}public Student() {super();}@Overridepublic String toString() {return "Student [sid=" + sid + ", sname=" + sname + ", birthday=" + birthday + ", Ssex=" + Ssex + ", classid="+ classid + ", clazz=" + clazz + "]";}
}
StudentMapper.java
public List<Student> selectIf(Student s);
StudentMapper.xml
<!-- OGNL 對(duì)象圖導(dǎo)航語(yǔ)言 屬性 運(yùn)算符 邏輯 字符串增強(qiáng) == --><!-- test中的表達(dá)式成立 就把if標(biāo)簽里面的字串拼接 -->
<select id="selectIf" parameterType="student"resultType="student"><include refid="stusql"></include>where 1=1<if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if>
</select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student();
//s.setSname("測(cè)試");
//s.setBirthday(new Date());
//s.setSsex("女");
s.setClassid(1);
List<Student> list = studentMapper.selectIf(s);//s.setSid(1);
list.forEach(System.out::println);
DaoUtil.closeSqlSession(sqlSession);
choose 、when 、otherwise 元素
為什么用choose 元素
- 場(chǎng)景1 當(dāng)新聞編號(hào)不為空,則只用新聞編號(hào)作為查詢(xún)條件;
- 場(chǎng)景2 當(dāng)新聞編號(hào)為空,而新聞標(biāo)題不為空,則用新聞標(biāo)題作為條件進(jìn)行模糊查詢(xún)
- 場(chǎng)景3 當(dāng)新聞編號(hào)和新聞標(biāo)題都為空,則要求新聞作者不能為空
語(yǔ)法:
<choose>
<when test=“條件”>滿(mǎn)足條件的語(yǔ)句</ when><otherwise> 滿(mǎn)足其他條件的語(yǔ)句<otherwise>
</choose>
choose類(lèi)似于switch 只要滿(mǎn)足條件只走一個(gè)
注意:拼接SQL語(yǔ)句的時(shí)候要注意AND和逗號(hào)
實(shí)現(xiàn):
StudentMapper.java
public List<Student> selectChoose(Student s);
StudentMapper.xml
<select id="selectChoose" parameterType="student" resultType="student">select * from student<where><choose><when test="sname">and sname=#{sname}</when><when test="birthday">and birthday=#{birthday}</when><when test="Ssex">and Ssex=#{ssex}</when><when test="classid">and classid=#{classid}</when><otherwise>classid=2</otherwise></choose></where>
</select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student();
s.setClassid(1);
List<Student> list = studentMapper.selectChoose(s);
list.forEach(System.out::println);
DaoUtil.closeSqlSession(sqlSession);
trim、where、set元素
trim(不常用)
語(yǔ)法:
語(yǔ)法:
<trim prefix = “”suffixOverrides = “” prefixOverrides=“”suffix=“”></trim>prefix 需要拼接的子句,可以是where,or 或者set;suffixOvrrides 忽略通過(guò)管道分隔的文本序列后綴。一般不與prefixOvrrides 同時(shí)使用prefixOvrrides 忽略通過(guò)管道分隔的文本序列前綴。一般不與suffixOvrrides 同時(shí)使用
實(shí)現(xiàn):
StudentMapper.java
public List<Student> findStudentTrim(Student s);
StudentMapper.xml
<!-- trim 萬(wàn)能標(biāo)簽prefix 開(kāi)始添加一個(gè)什么prefixOverrides 開(kāi)始去掉一個(gè)什么suffix 結(jié)束添加一個(gè)什么suffixOverrides 結(jié)束去掉一個(gè)什么--><select id="findStudentTrim" parameterType="student" resultType="student">select * from student <trim prefix=" where " prefixOverrides="and" ><if test="ssex != null"> and ssex= #{ssex}</if><if test="classid != 0"> and classid = #{classid}</if></trim></select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();
// s.setSname("測(cè)試");
// s.setBirthday(new Date());
// s.setSsex("女");s.setClassid(1);
List<Student> list = studentMapper.findStudentTrim(s);
list.forEach(System.out::println);
DaoUtil.closeSqlSession(sqlSession);
StudentMapper.java
public int updateTrim(Student s);
StudentMapper.xml
<update id="updateTrim" parameterType="student">update student<trim prefix="set" prefixOverrides="" suffix="" suffixOverrides=","><if test="sname!=null">sname=#{sname},</if><if test="birthday!=null">birthday=#{birthday},</if><if test="Ssex!=null">Ssex=#{ssex},</if><if test="classid!=0">classid=#{classid},</if></trim>where sid=#{sid}
</update>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student();
s.setSname("測(cè)試");
s.setBirthday(new Date());
s.setSsex("女");
s.setClassid(1);s.setSid(38);
int count = studentMapper.updateTrim(s);
if (count > 0) {sqlSession.commit();System.out.println("更新成功~");
} else {sqlSession.rollback();System.out.println("更新失敗~");
}
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
where
語(yǔ)法:
語(yǔ)法:
<where><if test =”條件”> 滿(mǎn)足條件的語(yǔ)句 </if>
</where>
說(shuō)明:where 元素只會(huì)在至少有一個(gè)子元素的 條件返回SQL子句的情況下才去插入 “WHERE”子句。而且,若語(yǔ)句的開(kāi)頭為 “AND”或“OR”,where 元素也會(huì)將它們?nèi)コ?/p>
實(shí)現(xiàn):
StudentMapper.java
public List<Student> selectWhere(Student s);
StundetMapper.xml
<!-- where標(biāo)簽 1.添加一個(gè)where關(guān)鍵詞 2. 去掉where后的第一個(gè)and 3.當(dāng)沒(méi)where標(biāo)簽中沒(méi)有任何成立的字串時(shí) 什么也不添加 -->
<select id="selectWhere" parameterType="student"resultType="student">select * from student<where><if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></where>
</select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student();
//s.setSname("測(cè)試");
//s.setBirthday(new Date());
//s.setSsex("女");
s.setClassid(1);
s.setSid(38);List<Student> list = studentMapper.selectWhere(s);
list.forEach(System.out::println);
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
set
語(yǔ)法:
<set><if test =”條件”> 滿(mǎn)足條件的語(yǔ)句 </if>
</set>
說(shuō)明: set 標(biāo)簽元素主要是用在更新操作的時(shí)候, 它的主要功能和 where 標(biāo)簽元素其實(shí)是差不多的,主要是在包含的語(yǔ)句前輸出一個(gè) set, 然后如果包含的語(yǔ)句是以逗號(hào)結(jié)束的話(huà)將會(huì)把該逗號(hào)忽略,如果 set 包含的內(nèi)容為空的 話(huà)則會(huì)出錯(cuò)。有了 set 元素就可以動(dòng)態(tài)的更 新那些修改了的字段。
實(shí)現(xiàn):
StudentMapper.java
public int updateSet(Student s);
StudentMapper.xml
<update id="updateSet" parameterType="student">update student<set><if test="sname!=null">sname=#{sname},</if><if test="birthday!=null">birthday=#{birthday},</if><if test="Ssex!=null">Ssex=#{ssex},</if><if test="classid!=0">classid=#{classid},</if></set>where sid=#{sid}
</update>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student();
s.setSname("測(cè)試");
s.setBirthday(new Date());
s.setSsex("女");
s.setClassid(1);
s.setSid(2);int count = studentMapper.updateSet(s);
if (count > 0) {sqlSession.commit();System.out.println("更新成功~");
} else {sqlSession.rollback();System.out.println("更新失敗~");
}
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
foreach元素
語(yǔ)法:
<foreach item = “” index=“” collection=“” open=“” separator=“” close=“”></foreach>item 循環(huán)中的當(dāng)前元素;
index 當(dāng)前循環(huán)元素的位置下標(biāo);
collection 方法傳遞的參數(shù),一個(gè)數(shù)組或者集合;
close 以什么符號(hào)結(jié)束將這些集合元素包裝起來(lái);
open 以什么符號(hào)開(kāi)始將這些集合元素包裝起來(lái);
separator 各個(gè)元素的間隔符號(hào)。
參數(shù)是數(shù)組
實(shí)現(xiàn):
StudentMapper.java
public List<Student> selectForEach(int[] array);
StudentMapper.xml
<select id="selectForEach" resultType="student"><!-- select * from student where sid in --><include refid="stusql"></include>where sid in<!-- collection 參數(shù)名 item 要遍歷的元素別名 open 起始字符 separator 分隔符 close 結(jié)束字符 --><foreach collection="array" item="item" open="(" separator=","close=")">#{item}</foreach>
</select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
int[] array = { 1, 3, 5, 7, 9 };
List<Student> list = studentMapper.selectForEach(array);
list.forEach(System.out::println);
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
參數(shù)是ArrayList
StudentMapper.java
public List<Student> selectForEachList(List<Integer> list);
StudentMapper.xml
<select id="selectForEachList" resultType="student">select * from student where sid in<foreach collection="list" item="item" open="(" separator="," close=")">#{item}</foreach>
</select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Integer> listInteger = Arrays.asList(1, 3, 5, 7, 9);
List<Student> list = studentMapper.selectForEachList(listInteger);
list.forEach(System.out::println);
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
批量增加
實(shí)現(xiàn):
StudentMapper.java
public int insertlist(List<Student> list);
StudentMapper.xml
<!-- 批量添加 -->
<insert id="insertlist">insert into student(sname,birthday,ssex,classid) values<foreach collection="list" item="s" separator=",">(#{s.sname},#{s.birthday},#{s.ssex},#{s.classid})</foreach>
</insert>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s1 = new Student();
s1.setBirthday(new Date());
s1.setClassid(1);
s1.setSname("劉備");
s1.setSsex("男");
Student s2 = new Student();
s2.setBirthday(new Date());
s2.setClassid(2);
s2.setSname("關(guān)羽");
s2.setSsex("男");
Student s3 = new Student();
s3.setBirthday(new Date());
s3.setClassid(3);
s3.setSname("張飛");
s3.setSsex("男");List<Student> stulist = new ArrayList<>();
stulist.add(s1);
stulist.add(s2);
stulist.add(s3);
int ret = studentMapper.insertlist(stulist);if (ret == stulist.size()) {sqlSession.commit();
} else {sqlSession.rollback();
}// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
bind元素
定義一個(gè)變量
語(yǔ)法:
<bind name=“”value=“_parameter”>
</bind>name 自定義變量的變量名
value 自定義變量的變量值
_parameter 傳遞進(jìn)來(lái)的參數(shù)
實(shí)現(xiàn):
StudentMapper.java
// 模糊查詢(xún)
public List<Student> selectStudentLike(String keyname);
StudentMapper.xml
<select id="selectStudentLike" parameterType="String"resultType="student"><!-- 方式1 在業(yè)務(wù)層處理 不推薦--><!-- select * from student where sname like #{v} --><!-- 方式2 mysql的函數(shù)進(jìn)行拼接 --><!-- select * from student where sname like concat('%',#{v},'%') --><!-- 方式3 sql語(yǔ)法 --><!-- select * from student where sname like "%"#{v}"%" --><!-- 方式4 ${v} 不推薦,不能防止sql注入--><!-- select * from student where sname like '%${v}%' --><!-- 方式5 bind標(biāo)簽 推薦 --><bind name="v" value="'%'+_parameter+'%'"/>select * from student where sname like #{v}
</select>
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 方式1:業(yè)務(wù)層進(jìn)行拼接
List<Student> list = studentMapper.selectStudentLike("%三%");
list.forEach(System.out::println);
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 方式2,3,4,5
List<Student> list = studentMapper.selectStudentLike("三");
list.forEach(System.out::println);
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
#{}和${}區(qū)別
- #{}匹配的是一個(gè)占位符,相當(dāng)于JDBC中的一個(gè)?,會(huì)對(duì)一些敏感的字符進(jìn)行過(guò)濾,編譯過(guò)后會(huì)對(duì)傳遞的值加上雙引號(hào),因此可以防止SQL注入問(wèn)題。
- 匹配的是真實(shí)傳遞的值,傳遞過(guò)后,會(huì)與 s q l 語(yǔ)句進(jìn)行字符串拼接。 {}匹配的是真實(shí)傳遞的值,傳遞過(guò)后,會(huì)與sql語(yǔ)句進(jìn)行字符串拼接。 匹配的是真實(shí)傳遞的值,傳遞過(guò)后,會(huì)與sql語(yǔ)句進(jìn)行字符串拼接。{}會(huì)與其他sql進(jìn)行字符串拼接,不能預(yù)防sql注入問(wèn)題。
#{}是預(yù)編譯處理,$ {}是字符串替換。
mybatis在處理#{}時(shí),會(huì)將sql中的#{}替換為?號(hào),調(diào)用PreparedStatement的set方法來(lái)賦值;
mybatis在處理 $ { } 時(shí),就是把 ${ } 替換成變量的值。使用 #{} 可以有效的防止SQL注入,提高系統(tǒng)安全性。
示例完整代碼:
StudentMapper.java
package mapper;import java.util.List;
import java.util.Map;import bean.Student;public interface StudentMapper {public List<Student> selectIf(Student s);public List<Student> selectWhere(Student s);public List<Student> selectChoose(Student s);public List<Student> findStudentTrim(Student s);public int updateSet(Student s);public int updateTrim(Student s);public List<Student> selectForEach(int[] array);public List<Student> selectForEachList(List<Integer> list);public int insertlist(List<Student> list);// 模糊查詢(xún)public List<Student> selectStudentLike(String keyname);
}
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 指向接口的類(lèi)路徑 -->
<mapper namespace="mapper.StudentMapper"><!-- sql片段 --><sql id="stusql">select * from student</sql><select id="selectIf" parameterType="student"resultType="student"><include refid="stusql"></include>where 1=1<if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></select><select id="selectWhere" parameterType="student"resultType="student">select * from student<where><if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></where></select><!-- trim 萬(wàn)能標(biāo)簽prefix 開(kāi)始添加一個(gè)什么prefixOverrides 開(kāi)始去掉一個(gè)什么suffix 結(jié)束添加一個(gè)什么suffixOverrides 結(jié)束去掉一個(gè)什么--><select id="findStudentTrim" parameterType="student" resultType="student">select * from student <trim prefix=" where " prefixOverrides="and" ><if test="ssex != null"> and ssex= #{ssex}</if><if test="classid != 0"> and classid = #{classid}</if></trim></select><select id="selectChoose" parameterType="student"resultType="student">select * from student<where><choose><when test="sname">and sname=#{sname}</when><when test="birthday">and birthday=#{birthday}</when><when test="Ssex">and Ssex=#{ssex}</when><when test="classid">and classid=#{classid}</when><otherwise>classid=2</otherwise></choose></where></select><update id="updateSet" parameterType="student">update student<set><if test="sname!=null">sname=#{sname},</if><if test="birthday!=null">birthday=#{birthday},</if><if test="Ssex!=null">Ssex=#{ssex},</if><if test="classid!=0">classid=#{classid},</if></set>where sid=#{sid}</update><update id="updateTrim" parameterType="student">update student<trim prefix="set" prefixOverrides="" suffix="" suffixOverrides=","><if test="sname!=null">sname=#{sname},</if><if test="birthday!=null">birthday=#{birthday},</if><if test="Ssex!=null">Ssex=#{ssex},</if><if test="classid!=0">classid=#{classid},</if></trim>where sid=#{sid}</update><select id="selectForEach" resultType="student"><!-- select * from student where sid in --><include refid="stusql"></include>where sid in<!-- collection 參數(shù)名 item 要遍歷的元素別名 open 起始字符 separator 分隔符 close 結(jié)束字符 --><foreach collection="array" item="item" open="(" separator=","close=")">#{item}</foreach></select><select id="selectForEachList" resultType="student">select * from student where sid in<foreach collection="list" item="item" open="(" separator="," close=")">#{item}</foreach></select><!-- 批量添加 --><insert id="insertlist">insert into student(sname,birthday,ssex,classid) values<foreach collection="list" item="s" separator=",">(#{s.sname},#{s.birthday},#{s.ssex},#{s.classid})</foreach></insert><select id="selectStudentLike" parameterType="String"resultType="student"><!-- 方式1 在業(yè)務(wù)層處理 不推薦--><!-- select * from student where sname like #{v} --><!-- 方式2 mysql的函數(shù)進(jìn)行拼接 --><!-- select * from student where sname like concat('%',#{v},'%') --><!-- 方式3 sql語(yǔ)法 --><!-- select * from student where sname like "%"#{v}"%" --><!-- 方式4 ${v} 不推薦,不能防止sql注入--><!-- select * from student where sname like '%${v}%' --><!-- 方式5 bind標(biāo)簽 推薦 --><bind name="v" value="'%'+_parameter+'%'"/>select * from student where sname like #{v}</select>
</mapper>
測(cè)試類(lèi):
package test;import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;import org.apache.ibatis.session.SqlSession;import bean.Student;
import dao.DaoUtil;
import mapper.StudentMapper;public class Test {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// Student s = new Student();
// s.setSname("測(cè)試");
// s.setBirthday(new Date());
// s.setSsex("女");
// s.setClassid(1);
//
// s.setSid(2);// List<Student> list = studentMapper.selectIf(s);// 動(dòng)態(tài)SQL
// List<Student> list = studentMapper.selectWhere(s);
// List<Student> list = studentMapper.selectChoose(s);
// List<Student> list = studentMapper.findStudentTrim(s);// int[] array = { 1, 3, 5, 7, 9 };
// List<Student> list = studentMapper.selectForEach(array);
// List<Integer> listInteger = Arrays.asList(1, 3, 5, 7, 9);
// List<Student> list = studentMapper.selectForEachList(listInteger);// 方式1:業(yè)務(wù)層進(jìn)行拼接
// List<Student> list = studentMapper.selectStudentLike("%三%");// 方式2,3,4,5List<Student> list = studentMapper.selectStudentLike("三");list.forEach(System.out::println);// int count = studentMapper.updateSet(s);
// int count = studentMapper.updateTrim(s);
// if (count > 0) {
// sqlSession.commit();
// System.out.println("更新成功~");
// } else {
// sqlSession.rollback();
// System.out.println("更新失敗~");
// }// Student s1 = new Student();
// s1.setBirthday(new Date());
// s1.setClassid(1);
// s1.setSname("劉備");
// s1.setSsex("男");
// Student s2 = new Student();
// s2.setBirthday(new Date());
// s2.setClassid(2);
// s2.setSname("關(guān)羽");
// s2.setSsex("男");
// Student s3 = new Student();
// s3.setBirthday(new Date());
// s3.setClassid(3);
// s3.setSname("張飛");
// s3.setSsex("男");
//
// List<Student> stulist = new ArrayList<>();
// stulist.add(s1);
// stulist.add(s2);
// stulist.add(s3);
// int ret = studentMapper.insertlist(stulist);
//
// if (ret == stulist.size()) {
// sqlSession.commit();
// } else {
// sqlSession.rollback();
// }
//
// // 釋放資源DaoUtil.closeSqlSession(sqlSession);}
}
映射器注解
映射器配置文件的缺陷
- 繁瑣:配置文件的書(shū)寫(xiě)本身繁瑣,需要掌 握的內(nèi)容比較多
- 不直觀:配置文件和接口直接只是名稱(chēng)相同, 對(duì)應(yīng)起來(lái)比較麻煩.
常用的注解
- 基本注解:實(shí)現(xiàn)簡(jiǎn)單的增刪改查操作。
- 結(jié)果映射注解:實(shí)現(xiàn)結(jié)果的映射關(guān)系, 也可以完成級(jí)聯(lián)映射。
- 動(dòng)態(tài)SQL注解:實(shí)現(xiàn)動(dòng)態(tài) SQL 的內(nèi)容
基本注解
基本注解的分類(lèi)
- 增加操作 @Insert 類(lèi)似 < insert > 完成新增
- 刪除操作 @Delete 類(lèi)似 < delete > 完成刪除
- 修改操作 @Update 類(lèi)似 < update > 完成修改
- 查詢(xún)操作 @Select 類(lèi)似 < select > 完成查詢(xún)
@Insert注解
**功能:**完成新增操作,類(lèi)似配置文件的元素;
**說(shuō)明:**新增時(shí)所用的參數(shù)取值是接口方法的入?yún)?#xff0c;可以是對(duì)象,也可以是 Map 集合。
語(yǔ)法:
@Insert (“ sql 語(yǔ)句”)
主鍵回填
**功能:**完成數(shù)據(jù)庫(kù)自增主鍵的回填
語(yǔ)法:
@Options(useGeneratedKeys = true, keyProperty = "主鍵屬性")
實(shí)現(xiàn):
實(shí)體類(lèi)Student.java
package bean;import java.util.Date;public class Student {private int sid;private String sname;private Date birthday;private String Ssex;private int classid;private Clazz clazz;public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getSsex() {return Ssex;}public void setSsex(String ssex) {Ssex = ssex;}public int getClassid() {return classid;}public void setClassid(int classid) {this.classid = classid;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public Student(int sid, String sname, Date birthday, String ssex, int classid, Clazz clazz) {super();this.sid = sid;this.sname = sname;this.birthday = birthday;Ssex = ssex;this.classid = classid;this.clazz = clazz;}public Student() {super();}@Overridepublic String toString() {return "Student [sid=" + sid + ", sname=" + sname + ", birthday=" + birthday + ", Ssex=" + Ssex + ", classid="+ classid + ", clazz=" + clazz + "]";}
}
StudentMapper.java
@Insert("insert into student(sname,birthday,ssex,classid) " + "values(#{sname},#{birthday},#{ssex},#{classid})")
@Options(useGeneratedKeys = true, keyProperty = "sid")
// 主鍵回填注解@Options
public int addStudent(Student s);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student();
s.setSname("一貓人");
s.setBirthday(new Date());
s.setSsex("男");
s.setClassid(1);//s.setSid(18);
System.out.println(s);
int count = studentMapper.addStudent(s);
System.out.println(s);
if (count > 0) {sqlSession.commit();
} else {sqlSession.rollback();
}
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
主鍵自增
**功能:**完成自定義主鍵的自增
語(yǔ)法:
@SelectKey ( statement = "自增規(guī)則", keyProperty = "主鍵屬性",
resultType = 結(jié)果類(lèi)型, before = true )
@Delete刪除
**功能:**完成刪除操作,類(lèi)似配置文件的元素;
說(shuō)明:刪除時(shí)所用的參數(shù)取值是接口方法的入?yún)?#xff0c;可以是對(duì)象,也可以是 Map 集合。
語(yǔ)法:
@Delete (“ sql 語(yǔ)句”)
實(shí)現(xiàn):
StudentMapper.java
@Delete("delete from student where sid=#{v}")
public int deleteStudent(int sid);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
int count = studentMapper.deleteStudent(42);if (count > 0) {sqlSession.commit();
} else {sqlSession.rollback();
}
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
@Update更新
**功能:**完成更新操作,類(lèi)似配置文件的元素;
**說(shuō)明:**更新時(shí)所用的參數(shù)取值是接口方法的入?yún)?#xff0c;可以是對(duì)象,也可以是Map 集合。
語(yǔ)法:
@Update (“ sql 語(yǔ)句”)
實(shí)現(xiàn):
StudentMapper.java
@Update("update student set sname=#{sname},birthday=#{birthday},ssex=#{ssex},classid=#{classid} where sid=#{sid}")
public int updateStudent(Student s);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 修改
Student s = new Student();
s.setSname("一貓人");
s.setBirthday(new Date());
s.setSsex("男");
s.setClassid(1);s.setSid(41);
int count = studentMapper.updateStudent(s);
if (count > 0) {sqlSession.commit();
} else {sqlSession.rollback();
}
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
@Select查詢(xún)
**功能:**完成查詢(xún)操作,類(lèi)似配置文件的 元素;
**說(shuō)明:**查詢(xún)時(shí)所用的參數(shù)取值是接口方法的入?yún)?#xff0c;可以是 對(duì)象,也可以是 Map 集合。
語(yǔ)法:
@Selete (“ sql 語(yǔ)句”)
實(shí)現(xiàn):
StudentMapper.java
@Select("select * from student")
public List<Student> findAll();@Select("select * from student where sname=#{v}")
public Student findByName(String name);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = studentMapper.findAll();
for (Student student : list) {System.out.println(student);
}
Student s = studentMapper.findByName("賈策");
System.out.println(s);
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
注解和sqlMapper.xml 可以同時(shí)使用
注解底層還是sqlMapper 方法還是不能重載
傳遞多個(gè)參數(shù)的方式
- 方法1:Map 方式 跟sqlmap一樣
- 方法2:JavaBean 方式跟sqlmap一樣
- 方法3:@Param 方式
實(shí)現(xiàn):
StudentMapper.java
@Select("select * from student where ssex=#{sex} limit #{cpage},#{size}")
public List<Student> selectSexLimit(@Param("sex") String sex,@Param("cpage") int cpage, @Param("size") int size);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = studentMapper.selectSexLimit("男", (3 - 1) * 3, 3);
for (Student student : list) {System.out.println(student);
}
// 釋放資源
DaoUtil.closeSqlSession(sqlSession);
結(jié)果映射注解
@Results結(jié)果映射
功能: 完成數(shù)據(jù)庫(kù)字段和 JavaBean 屬性的映射關(guān)系;
說(shuō)明:每個(gè) @Results 可以包含多個(gè) @Result,其中通過(guò) id 屬性來(lái)判斷是否為主鍵。
語(yǔ)法:
@Results({ @Result(id = 是否為主鍵, column = "字段", property = "屬性" ) })
@Results復(fù)用
實(shí)現(xiàn):
SMasterMapper.java
// @Results(id="smaster_map",value = {
// @Result(column = "smid",property = "smid"),
// @Result(column = "sm_name",property = "smname"),
// @Result(column = "smsex",property = "smsex")
// })@Results({@Result(column = "smid",property = "smid"),@Result(column = "sm_name",property = "smname"),@Result(column = "smsex",property = "smsex")})@Select("select * from schoolmaster")public List<SMaster> findAll();@Select("select * from schoolmaster where smid=#{v}")
// @ResultMap("smaster_map")public SMaster findById(int id);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
SMasterMapper sMasterMapper = sqlSession.getMapper(SMasterMapper.class);
List<SMaster> list = sMasterMapper.findAll();
list.forEach(System.out::println);
SMaster s = sMasterMapper.findById(2);
System.out.println(s);
注解映射各用各的
一對(duì)一映射
功能:一對(duì)一的關(guān)系映射;
說(shuō)明:FetchType.lazy 是延時(shí)加載,FetchType.EAGER 是即時(shí)加載。
語(yǔ)法:
@One( Select = 一對(duì)一查詢(xún)方法,
fetchType = FetchType.EAGER )
實(shí)現(xiàn):
StudentMapper.java
@Results({ @Result(column = "classid", property = "classid"),@Result(property = "clazz", column = "classid", one = @One(select = "mapper.ClazzMapper.selectAll")) })
@Select("select * from student")
public List<Student> selectStudentAndClazz();
Clazz.java
@Select("select * from class where classid=#{v}")
public List<Clazz> selectAll(int classid);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = studentMapper.selectStudentAndClazz();
for (Student student : list) {System.out.println(student);
}
DaoUtil.closeSqlSession(sqlSession);
注解沒(méi)有表聯(lián)查 只有單表和自己寫(xiě)的映射關(guān)系
一對(duì)一映射的實(shí)現(xiàn)案例
一對(duì)多映射
功能:一對(duì)多的關(guān)系映射;
說(shuō)明:FetchType.lazy 是延時(shí)加載,FetchType.EAGER 是即時(shí)加載。
語(yǔ)法:
@Many( Select = 一對(duì)多查詢(xún)方法, fetchType = FetchType.EAGER )
實(shí)現(xiàn):
ClazzMapper.java
@Results({ @Result(column = "classid", property = "classid"),@Result(column = "classid", property = "stulist", many = @Many(select = "mapper.StudentMapper.selectStudentByClassId")) })@Select("select * from class")public List<Clazz> selectClazzAndStudent();
StudentMapper.java
@Select("select * from student where classid=#{v}")
public List<Student> selectStudentByClassId(int classid);
測(cè)試:
SqlSession sqlSession = DaoUtil.getSqlSession();
ClazzMapper clazzMapper = sqlSession.getMapper(ClazzMapper.class);
List<Clazz> list = clazzMapper.selectClazzAndStudent();
for (Clazz clazz : list) {System.out.println(clazz);
}
DaoUtil.closeSqlSession(sqlSession);
一對(duì)多映射的實(shí)現(xiàn)案例
示例完整代碼:
ClazzMapper.java
package mapper;import java.util.List;import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;import bean.Clazz;public interface ClazzMapper {@Select("select * from class where classid=#{v}")public List<Clazz> selectAll(int classid);@Select("select * from class")public List<Clazz> selectClazzId(int classid);@Results({ @Result(column = "classid", property = "classid"),@Result(column = "classid", property = "stulist", many = @Many(select = "mapper.StudentMapper.selectStudentByClassId")) })@Select("select * from class")public List<Clazz> selectClazzAndStudent();
}
StudentMapper.java
package mapper;import java.util.List;
import java.util.Map;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.jdbc.SQL;import bean.Student;public interface StudentMapper {@Select("select * from student")public List<Student> findAll();@Select("select * from student where sname=#{v}")public Student findByName(String name);@Select("select * from student where ssex=#{sex} limit #{cpage},#{size}")public List<Student> selectSexLimit(@Param("sex") String sex, @Param("cpage") int cpage, @Param("size") int size);@Insert("insert into student(sname,birthday,ssex,classid) " + "values(#{sname},#{birthday},#{ssex},#{classid})")@Options(useGeneratedKeys = true, keyProperty = "sid")// 主鍵回填注解@Optionspublic int addStudent(Student s);@Update("update student set sname=#{sname},birthday=#{birthday},ssex=#{ssex},classid=#{classid} where sid=#{sid}")public int updateStudent(Student s);@Delete("delete from student where sid=#{v}")public int deleteStudent(int sid);@Results({ @Result(column = "classid", property = "classid"),@Result(property = "clazz", column = "classid", one = @One(select = "mapper.ClazzMapper.selectAll")) })@Select("select * from student")public List<Student> selectStudentAndClazz();@Select("select * from student where classid=#{v}")public List<Student> selectStudentByClassId(int classid);
}
測(cè)試1:
package test;import java.util.Date;
import java.util.List;import org.apache.ibatis.session.SqlSession;import bean.Student;
import dao.DaoUtil;
import mapper.StudentMapper;public class Test01 {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// List<Student> list = studentMapper.findAll();List<Student> list = studentMapper.selectSexLimit("男", (3 - 1) * 3, 3);for (Student student : list) {System.out.println(student);}
//
// Student s = studentMapper.findByName("賈策");
// System.out.println(s);// 添加
// Student s = new Student();
// s.setSname("一貓人");
// s.setBirthday(new Date());
// s.setSsex("男");
// s.setClassid(1);
//
// s.setSid(41);
// System.out.println(s);
// int count = studentMapper.addStudent(s);
// System.out.println(s);// int count = studentMapper.updateStudent(s);
// int count = studentMapper.deleteStudent(42);// if (count > 0) {
// sqlSession.commit();
// } else {
// sqlSession.rollback();
// }// 釋放資源DaoUtil.closeSqlSession(sqlSession);}
}
測(cè)試2:
package test;import java.util.List;import org.apache.ibatis.session.SqlSession;import bean.SMaster;
import dao.DaoUtil;
import mapper.SMasterMapper;public class Test02 {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();SMasterMapper sMasterMapper = sqlSession.getMapper(SMasterMapper.class);List<SMaster> list = sMasterMapper.findAll();list.forEach(System.out::println);SMaster s = sMasterMapper.findById(2);System.out.println(s);}
}
測(cè)試3:
package test;import java.util.List;import org.apache.ibatis.session.SqlSession;import bean.Clazz;
import bean.Student;
import dao.DaoUtil;
import mapper.ClazzMapper;
import mapper.StudentMapper;public class Test03 {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();
// StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// List<Student> list = studentMapper.selectStudentAndClazz();
// for (Student student : list) {
// System.out.println(student);
// }ClazzMapper clazzMapper = sqlSession.getMapper(ClazzMapper.class);List<Clazz> list = clazzMapper.selectClazzAndStudent();for (Clazz clazz : list) {System.out.println(clazz);}DaoUtil.closeSqlSession(sqlSession);}
}