准备工作
数据库(mydb):
user表
CREATE TABLE `author` (
`aid` int(255) NOT NULL AUTO_INCREMENT,
`aname` varchar(255) DEFAULT NULL,
`aage` int(255) DEFAULT NULL,
`atel` varchar(255) DEFAULT NULL,
`aaddress` varchar(255) DEFAULT NULL,
PRIMARY KEY (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
实体类(Author):
然后生成构造方法,get方法,set方法,toString方法
public class Author implements Serializable {
private int aid;
private String aname;
private int aage;
private String atel;
private String aaddress;
接口(AuthorMapper)
import com.yunhe.pojo.Author;
import java.util.ArrayList;
public interface AuthorMapper {
//通过Author中的id查询数据
ArrayList<Author> selectByAuthor(Author author);
// 通过Author中的id修改数据
int updateByAuthor(Author author);
//通过Author集合中插入数据
int insertByAuthor(ArrayList<Author> authors);
// 通过Author集合中批量删除
int deleteByAuthor(ArrayList<Author> authors);
// 通过数组删除
int deleteByArr(int[] arr);
}
1.1 概念
根据传入的参数获取书写一些带有逻辑功能的标签,实现相同的方法执行不同的sql语句,语法类似于jstl
1.2 查询语句(select)--------where 和 if 连用
if 标签:
可以动态的在sql中进行判断,只有返回true时才会将指定的sql语句拼写进行执行
where 标签:
动态的添加where ,当标签中有数据时会自动添加where 否则不会添加 ,并且如果where标签中数据是以and 或者or开头 会自动删除and或者or 防止语句出现问题
实例:
<select id="selectByAuthor" resultType="com.yunhe.pojo.Author">
select * from Author
<!-- where标签 当标签内存在数据时 自动以where 作为前缀 并且讲数据起始的and和or删除 -->
<where>
<if test="aid!=0">
aid = #{aid}
</if>
<if test="aname!=null">
and aname = #{aname}
</if>
<if test="aage!=0">
and aage = #{aage}
</if>
<if test="atel!=null">
and atel = #{atel}
</if>
<if test="aaddress!=null">
and aaddress like '%${aaddress}%'
<!-- and aaddress like concat('%',#{aaddress},'%') -->
</if>
</where>
</select>
1.3 修改数据(update) -----set 标签和if 标签
常用于修改数据时,根据传入的数据拼写修改数据的sql
<update id="updateByAuthor" parameterType="com.yunhe.pojo.Author">
update author
<!-- set 标签 当标签内存在数据时 自动以set 作为前缀 并且将数据结尾的 ,删除*/-->
<set>
<if test="aname!=null">
aname = #{aname},
</if>
<if test="aage!=0">
aage = #{aage},
</if>
<if test="atel!=null">
atel = #{atel},
</if>
<if test="aaddress!=null">
aaddress = #{aaddress}
</if>
</set>
where aid = #{aid}
</update>
1.4 批量添加(insert)--------foreach标签
当传递的数据是数组或者集合时,需要使用foreach标签进遍历拼写sql
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
item:遍历取出的数据
index:遍历数据的索引
colleaction:遍历的集合类型
open:开始拼接时添加的字符串
separator:每次遍历中间的字符串
close:结束后最后添加的字符串
1.5 批量删除(delete)
1.5.1 通过Author数组中的aid字段进行删除
<delete id="deleteByAuthor" parameterType="com.yunhe.pojo.Author">
delete from author where aid in
<foreach collection="list" item="author" separator="," open="(" close=")">
#{author.aid}
</foreach>
</delete>
1.5.1 通过int数组进行删除
<delete id="deleteByArr" parameterType="com.yunhe.pojo.Author">
delete from author where aid in
<foreach collection="array" item="i" separator="," open="(" close=")">
#{i}
</foreach>
</delete>