Mybatis之基本查询与态动SQL(四)
一、Mybatis环境准备
1.添加依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
</dependencies>
2.创建SqlMapConfig.xml
<?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">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<mapper resource="cn/ybzy/dao/IUserDao.xml"/>
</mappers>
</configuration>
3.创建实体类与接口
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//setter() getter()
}
public interface IUserDao {
}
4.创建映射文件IUserDao.xml
注意点:
1、持久层接口和持久层接口的映射配置必须在相同的包下
2、持久层映射配置中 mapper 标签的 namespace 属性取值必须是持久层接口的全限定类名
3、SQL 语句的配置标签<select>,<insert>,<delete>,<update>的 id 属性必须和持久层接口的
方法名相同。
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
</mapper>
5.创建测试环境
public class MybatisTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before
public void init()throws Exception{
//读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession对象
sqlSession = factory.openSession();
//获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy()throws Exception{
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
in.close();
}
}
二、Mybatis的基本查询
1.保存操作
public interface IUserDao {
void saveUser(User user);
}
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 保存用户 -->
<insert id="saveUser" parameterType="cn.ybzy.domain.User">
insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
</insert>
</mapper>
@Test
public void testSave(){
User user = new User();
user.setUserName("test save");
user.setUserAddress("中国");
user.setUserSex("男");
user.setUserBirthday(new Date());
userDao.saveUser(user);
}
2.删除操作
public interface IUserDao {
void deleteUser(Integer userId);
}
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 删除用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{uid}
</delete>
</mapper>
@Test
public void testDelete(){
userDao.deleteUser(1);
}
3.修改操作
public interface IUserDao {
/**
* 更新用户
* @param user
*/
void updateUser(User user);
}
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 更新用户 -->
<update id="updateUser" parameterType="cn.ybzy.domain.User">
update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
</update>
</mapper>
@Test
public void testUpdate(){
User user = new User();
user.setUserId(2);
user.setUserName("test update");
user.setUserAddress("大中国");
user.setUserSex("女");
user.setUserBirthday(new Date());
userDao.updateUser(user);
}
4.查询操作
public interface IUserDao {
User findById(Integer userId);
}
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultType="cn.ybzy.domain.User">
select * from user where id = #{uid}
</select>
</mapper>
@Test
public void testFindOne(){
User user = userDao.findById(2);
System.out.println(user);
}
5.模糊查询
public interface IUserDao {
List<User> findByName(String username);
}
模糊查询方式1
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 根据名称模糊查询 -->
<select id="findByName" parameterType="string" resultMap="userMap">
select * from user where username like #{name}
</select>
</mapper>
@Test
public void testFindByName(){
List<User> users = userDao.findByName("%save%");
for(User user : users){
System.out.println(user);
}
}
模糊查询方式2
该方式中,${value}的写法就是固定的,不能写成其它名字。
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 根据名称模糊查询 -->
<select id="findByName" parameterType="string" resultMap="userMap">
select * from user where username like '%${value}%'
</select>
</mapper>
@Test
public void testFindByName(){
List<User> users = userDao.findByName("save");
for(User user : users){
System.out.println(user);
}
}
6.聚合函数查询
public interface IUserDao {
int findTotal();
}
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 获取用户的总记录条数 -->
<select id="findTotal" resultType="int">
select count(id) from user;
</select>
</mapper>
@Test
public void testFindTotal(){
int count = userDao.findTotal();
System.out.println(count);
}
7.新增返回id值
新增后,同时还要返回当前新增数据的 id 值,若数据库主键id是自增策略,则 id 是由数据库的自动增长来实现的,相当于要在新增后将自动增长auto_increment 的值返回。
public interface IUserDao {
void saveUser(User user);
}
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 保存用户 -->
<insert id="saveUser" parameterType="cn.ybzy.domain.User">
<!-- 配置插入操作后,获取插入数据的id -->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
</insert>
</mapper>
@Test
public void testSave(){
User user = new User();
user.setUserName("test save return id");
user.setUserAddress("中国66");
user.setUserSex("男");
user.setUserBirthday(new Date());
System.out.println("保存前:"+user);
userDao.saveUser(user);
System.out.println("保存后:"+user);
}
8.传递pojo包装对象查询
定义QueryVo包装对象,使用包装对象传递输入参数。
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
public interface IUserDao {
List<User> findUserByVo(QueryVo vo);
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 根据queryVo的条件查询用户 -->
<select id="findUserByVo" parameterType="cn.ybzy.domain.QueryVo" resultMap="userMap">
select * from user where username like #{user.username}
</select>
</mapper>
@Test
public void testFindByVo(){
QueryVo vo = new QueryVo();
User user = new User();
user.setUserName("%王%");
vo.setUser(user);
List<User> users = userDao.findUserByVo(vo);
for(User u : users){
System.out.println(u);
}
}
9.实体类属性名和数据库列名不一致的查询
实体类User
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
}
数据库字段
接口方法:
List<User> findAll();
映射文件的配置
1.使用别名
<!-- 配置查询所有操作 -->
<select id="findAll" resultType="cn.ybzy.domain.User">
select id as userId,username as userName,birthday as userBirthday,
sex as userSex,address as userAddress from user
</select>
2.使用resultMap 结果类型
<?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">
<mapper namespace="cn.ybzy.dao.IUserDao">
<!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->
<resultMap id="userMap" type="cn.ybzy.domain.User">
<!-- 主键字段的对应 -->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="userMap">
select * from user;
</select>
</mapper>
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
}
三、Mybatis的动态SQL
1.动态SQL之if
标签
标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法
<!-- 根据条件查询-->
<select id="selectByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="username != null and username != ''">
and username = #{username }
</if>
<if test="age!= null and age >20">
and age= #{age}
</if>
</select>
2.动态SQL之where
标签
简化where 1=1 的条件拼装,可以采用标签来简化开发
<select id="selectByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="username != null and username != ''">
and username = #{username }
</if>
<if test="age!= null and age >20">
and age= #{age}
</if>
</where>
</select>
3. 动态标签之foreach
标签
在进行范围查询时,要将一个集合中的值,作为参数动态添加进来,就需要使用foreach标签
<foreach>标签
用于遍历集合
collection:
代表要遍历的集合元素,编写时不要写#{}
open:
代表语句的开始部分
close:
代表结束部分
item:
代表遍历集合的每个元素,生成的变量名
sperator:
代表分隔符
<select id="findUserByIds" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
4. SQL片段
将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的
<!-- 定义抽取重复的sql语句-->
<sql id="userSql">
select * from user
</sql>
<!-- 查询年龄大于20的 -->
<select id="findAll" resultMap="userMap">
<include refid="userSql"></include>
where age>20
</select>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137113.html