目录
准备工作
获取参数值的方式(重点)
查询功能
查询一个实体类对象
查询一个list集合
查询单个数据
查询一条数据为map集合
查询多条数据为map集合
特殊SQL执行
模糊查询
批量删除
动态设置表名
添加功能获取自增的主键
准备工作
模块Mybatis_demo2
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><properties resource="jdbc.properties"/><!--类型别名,不区分大小写--><typeAliases><package name="com.qcby.pojo"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><!--设置连接数据库的驱动--><property name="driver" value="${jdbc.driver}"/><!--设置连接数据库的连接地址--><property name="url" value="${jdbc.url}"/><!--设置连接数据库的用户名--><property name="username" value="${jdbc.username}"/><!--设置连接数据库的密码--><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!--引入映射文件--><mappers><mapper resource="mapper/ParameterMapper.xml"/></mappers>
</configuration>
jdbc.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis1028
jdbc.username=root
jdbc.password=123456
实体类:
package com.qcby.pojo;public class User {private Integer id;private String username;private String password;private Integer age;private String sex;private String email;public User() {}public User(Integer id, String username, String password, Integer age, String sex, String email) {this.id = id;this.username = username;this.password = password;this.age = age;this.sex = sex;this.email = email;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", age=" + age +", sex='" + sex + '\'' +", email='" + email + '\'' +'}';}
}
封装SqlSession工具类:
package com.qcby.utils;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class SqlSessionUtils {public static SqlSession getSqlSession(){SqlSession sqlSession = null;try {InputStream is = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);sqlSession = sqlSessionFactory.openSession(true);} catch (IOException e) {e.printStackTrace();}return sqlSession;}
}
ParameterMapper:
package com.qcby.mapper;import com.qcby.pojo.User;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface ParameterMapper {/*** 查询所有的员工*/List<User> getAllUser();
}
ParameterMapperxml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.mapper.ParameterMapper"><!--查询所有--><select id="getAllUser" resultType="com.qcby.pojo.User">select * from t_user</select>
</mapper>
测试类:
package com.qcby;import com.qcby.mapper.ParameterMapper;
import com.qcby.pojo.User;
import com.qcby.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class ParameterMapperTest {@Testpublic void testGetAllUser(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);List<User> list = mapper.getAllUser();for (User user : list) {System.out.println(user);}}}
获取参数值的方式(重点)
MyBatis获取参数值的两种方式:${}和#{}
${}的本质就是字符串拼接,#{}的本质就是占位符赋值
${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
1.单个字面量类型的参数
若mapper接口中的方法参数为单个的字面量类型,此时可以使用${}和#{}以任意的名称获取参数的值,可以是aaa,建议与变量名保持一致,注意${}需要手动加单引号
#{}:
/*** 根据用户名查询用户信息*/User getUserByUserName(String username);
<select id="getUserByUserName" resultType="com.qcby.pojo.User">select * from t_user where username = #{username}</select>
@Testpublic void getUserByUserName(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);User user = mapper.getUserByUserName("admin");System.out.println(user);}
${}:
<select id="getUserByUserName" resultType="com.qcby.pojo.User">select * from t_user where username = '${username}'</select>
2.多个字面量类型的参数
若mapper接口中的方法参数为多个时,此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1...为键,以参数为值;以 param1,param2...为键,以参数为值;因此只需要通过${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
#{}:
/*** 验证登录*/User checkLogin(String username,String password);
<select id="checkLogin" resultType="com.qcby.pojo.User">select * from t_user where username = #{arg0} and password = #{arg1}</select>
@Testpublic void checkLogin(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);User user = mapper.checkLogin("admin","123456");System.out.println(user);}
${}:
<select id="checkLogin" resultType="com.qcby.pojo.User">select * from t_user where username = '${arg0}' and password = '${arg1}'</select>
3.map集合类型的参数
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中,只需要通过${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
User checkLoginMap(Map<String,Object> map);
<select id="checkLoginMap" resultType="com.qcby.pojo.User">select * from t_user where username = #{username} and password = #{password}</select>
@Testpublic void checkLoginMap(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);Map<String,Object> map = new HashMap<>();map.put("username","admin");map.put("password","123456");User user = mapper.checkLoginMap(map);System.out.println(user);}
4.实体类类型的参数
若mapper接口中的方法参数为实体类对象时,此时可以使用${}和#{},通过访问实体类对象中的属性名获取属性值,注意${}需要手动加单引号
/*** 添加用户信息*/int insertUser(User user);
<insert id="insertUser">insert into t_user values (null ,#{username},#{password},#{age},#{sex},#{email})</insert>
@Testpublic void insert(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);int result = mapper.insertUser(new User(null, "李四", "123", 23, "男", "123@qq.com"));System.out.println(result);}
5.使用@Param标识参数
可以通过@Param注解标识mapper接口中的方法参数
此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;以param1,param2...为键,以参数为值;只需要通过${}和#{}访问map集合的键就可以获取相对应的值, 注意${}需要手动加单引号
User checkLoginByParam(@Param("username") String username, @Param("password") String password);
<select id="checkLoginByParam" resultType="com.qcby.pojo.User">select * from t_user where username = #{username} and password = #{password}</select>
@Testpublic void checkLoginByParam(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);User user = mapper.checkLoginByParam("admin", "123456");System.out.println(user);}
查询功能
若查询出的数据只有一条,可以通过实体类对象或者集合接收
若查询出的数据有多条,可以通过实体类类型的list集合接收;可以通过map类型的list集合接收;可以在mapper接口的方法上添加@MapKey注解,此时就可以将每条数据转换的map集合作为值,以某个字段的值作为键,放在同一个map集合中
查询一个实体类对象
/*** 根据id查询用户信息*/User getUserById(@Param("id") Integer id);
<select id="getUserById" resultType="com.qcby.pojo.User">select * from t_user where id = #{id}</select>
@Testpublic void getUserById() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);System.out.println(mapper.getUserById(3));}
查询一个list集合
/*** 查询所有的用户信息*/List<User> getAllUser();
<select id="getAllUser" resultType="com.qcby.pojo.User">select * from t_user</select>
@Testpublic void getAllUser() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);List<User> users = mapper.getAllUser();for (User user : users) {System.out.println(user);}}
查询单个数据
/*** 查询用户的总记录数*/
Integer getCount();
在MyBatis中,对于Java中常用的类型都设置了类型别名* 例如:java.lang.Integer-->int,integer* 例如:int-->_int,_integer* 例如:Map-->map,List-->list <select id="getCount" resultType="java.lang.Integer">select count(*) from t_user</select>
@Testpublic void getCount() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);System.out.println(mapper.getCount());}
查询一条数据为map集合
/*** 根据id查询用户信息为一个map集合*/Map<String,Object> getUserByIdToMap(@Param("id") Integer id);
<select id="getUserByIdToMap" resultType="java.util.Map">select * from t_user where id = #{id}</select>
@Testpublic void getUserByIdToMap() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);System.out.println(mapper.getUserByIdToMap(3));}
查询多条数据为map集合
方法一:
/*** 查询所有用户信息为map集合* @return* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此
时可以将这些map放在一个list集合中获取*/
List<Map<String,Object>> getAllUserToMap();
<select id="getUserByIdToMap" resultType="java.util.Map">select * from t_user where id = #{id}</select>
@Testpublic void getAllUserToMap() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);System.out.println(mapper.getAllUserToMap());}
方法二:
/*** 查询所有用户信息为map集合* @return* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并
且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的
map集合*/
@MapKey("id")
Map<String,Object> getAllUserToMap();
特殊SQL执行
模糊查询
/*** 根据用户名模糊查询用户信息*/List<User> getUserByLike(@Param("username") String username);
<select id="getUserByLike" resultType="com.qcby.pojo.User"><!--select * from t_user where username like '%${username}%'--><!--select * from t_user where username like concat('%',#{username},'%')-->select * from t_user where username like "%"#{username}"%"</select>
@Testpublic void getUserByLike(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);List<User> list = mapper.getUserByLike("a");System.out.println(list);}
批量删除
/*** 批量删除*/Integer deleteMore(@Param("ids") String ids);
<delete id="deleteMore">delete from t_user where id in(${ids})</delete>
@Testpublic void deleteMore(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);Integer result = mapper.deleteMore("1,2,3");System.out.println(result);}
动态设置表名
/*** 查询指定表中的数据*/List<User> getUserByTableName(@Param("tableName") String tableName);
<select id="getUserByTableName" resultType="com.qcby.pojo.User">select * from ${tableName}</select>
@Testpublic void getUserByTableName(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);List<User> list = mapper.getUserByTableName("t_user");System.out.println(list);}
添加功能获取自增的主键
t_clazz(clazz_id,clazz_name) t_student(student_id,student_name,clazz_id)
1.添加班级信息
2.获取新添加的班级的id
3.为班级分配学生,即将某学的班级id修改为新添加的班级的id
void insertUser(User user);
<!--useGeneratedKeys:设置使用自增的主键keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参
数user对象的某个属性中--><insert id="insertUser" useGeneratedKeys="true" keyProperty="id">insert into t_user values (null,#{username},#{password},#{age},#{sex},#{email})</insert>
@Testpublic void insertUser(){SqlSession sqlSession = SqlSessionUtils.getSqlSession();SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);User user = new User(null,"王五","123",23,"男","123@qq.com");mapper.insertUser(user);System.out.println(user);}