两种方式:${}和#{}
${}
的本质就是字符串拼接,#{}
的本质就是占位符赋值${}
使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}
使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号3这里pom.xml、jdbc.properties、log4j.xml、mybatis-config.xml文件不变,延用第二章的
ParameterMapper.java
package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.pojo.User;
public interface ParameterMapper {
/**
* 验证登录(使用@Param)
*/
User checkLoginByParam(@Param("username") String username, @Param("password") String password);
/**
* 添加用户信息
*/
int insertUser(User user);
/**
* 验证登录(参数为map)
*/
User checkLoginByMap(Map<String, Object> map);
/**
* 验证登录
*/
User checkLogin(String username, String password);
/**
* 根据用户名查询用户信息
*/
User getUserByUsername(String username);
/**
* 查询所有的员工信息
*/
List<User> getAllUser();
}
User.java
package com.atguigu.mybatis.pojo;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
private String email;
//这里省略了有参无参构造、get、set、toString重载
}
SqlSessionUtils.java
package com.atguigu.mybatis.utils;
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.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.ParameterMapper">
<select id="getAllUser" resultType="User">
select * from t_user
select>
<select id="getUserByUsername" resultType="User">
select * from t_user where username = '${username}'
select>
<select id="checkLogin" resultType="User">
select * from t_user where username = '${param1}' and password = '${param2}'
select>
<select id="checkLoginByMap" resultType="User">
select * from t_user where username = #{username} and password = #{password}
select>
<insert id="insertUser">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
insert>
<select id="checkLoginByParam" resultType="User">
select * from t_user where username = #{username} and password = #{password}
select>
mapper>
ParameterMapperTest.java
package com.atguigu.mybatis.test;
import com.atguigu.mybatis.mapper.ParameterMapper;
import com.atguigu.mybatis.pojo.User;
import com.atguigu.mybatis.utils.SqlSessionUtils;
public class ParameterMapperTest {
/**
* MyBatis获取参数值的两种方式:${}和#{}
* ${}本质字符串拼接
* #{}本质占位符赋值
* MyBatis获取参数值的各种情况:
* 1、mapper接口方法的参数为单个的字面量类型
* 可以通过${}和#{}以任意的名称获取参数值,但是需要注意${}的单引号问题
* 2、mapper接口方法的参数为多个时
* 此时MyBatis会将这些参数放在一个map集合中,以两种方式进行存储
* a>以arg0,arg1...为键,以参数为值
* b>以param1,param2...为键,以参数为值
* 因此只需要通过#{}和${}以键的方式访问值即可,但是需要注意${}的单引号问题
* 3、若mapper接口方法的参数有多个时,可以手动将这些参数放在一个map中存储
* 只需要通过#{}和${}以键的方式访问值即可,但是需要注意${}的单引号问题
* 4、mapper接口方法的参数是实体类类型的参数
* 只需要通过#{}和${}以属性的方式访问属性值即可,但是需要注意${}的单引号问题
* 5、使用@Param注解命名参数
* 此时MyBatis会将这些参数放在一个map集合中,以两种方式进行存储
* a>以@Param注解的值为键,以参数为值
* b>以param1,param2...为键,以参数为值
* 因此只需要通过#{}和${}以键的方式访问值即可,但是需要注意${}的单引号问题
*/
@Test
public void testCheckLoginByParam(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLoginByParam("admin", "123456");
System.out.println(user);
}
@Test
public void testInsertUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
int result = mapper.insertUser(new User(null, "李四", "123", 23, "男", "[email protected]"));
System.out.println(result);
}
@Test
public void testCheckLoginByMap(){
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.checkLoginByMap(map);
System.out.println(user);
}
@Test
public void testCheckLogin(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLogin("admin", "123456");
System.out.println(user);
}
@Test
public void testGetUserByUsername(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.getUserByUsername("admin");
System.out.println(user);
}
@Test
public void testGetAllUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
List<User> list = mapper.getAllUser();
list.forEach(user -> System.out.println(user));
}
@Test
public void testJDBC() throws Exception {
String username = "admin";
Class.forName("");
Connection connection = DriverManager.getConnection("", "", "");
//PreparedStatement ps = connection.prepareStatement("select * from t_user where username = '" + username + "'");
PreparedStatement ps = connection.prepareStatement("selelt * from t_user where username = ?");
ps.setString(1, username);
}
}
详解如下:
/**
* 根据用户名查询用户信息
*/
User getUserByUsername(String username);
<select id="getUserByUsername" resultType="User">
select * from t_user where username = #{username}
select>
<select id="getUserByUsername" resultType="User">
select * from t_user where username = '${username}'
select>
@Test
public void testGetUserByUsername(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.getUserByUsername("admin");
System.out.println(user);
}
/**
* 验证登录
*/
User checkLogin(String username, String password);
@Test
public void testCheckLogin(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLogin("admin", "123456");
System.out.println(user);
}
若mapper接口中的方法参数为多个时,此时MyBatis会自动将这些参数放在一个map集合中
1. 以arg0,arg1...为键,以参数为值;
2. 以param1,param2...为键,以参数为值;
<select id="checkLogin" resultType="User">
select * from t_user where username = #{arg0} and password = #{arg1}
select>
<select id="checkLogin" resultType="User">
select * from t_user where username = '${param1}' and password = '${param2}'
select>
/**
* 验证登录(参数为map)
*/
User checkLoginByMap(Map<String, Object> map);
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中只需要通过${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
<select id="checkLoginByMap" resultType="User">
select * from t_user where username = #{username} and password = #{password}
select>
@Test
public void checkLoginByMap() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
Map<String,Object> map = new HashMap<>();
map.put("usermane","admin");
map.put("password","123456");
User user = mapper.checkLoginByMap(map);
System.out.println(user);
}
/**
* 添加用户信息
*/
int insertUser(User user);
若mapper接口中的方法参数为实体类对象时此时可以使用${}和#{},通过访问实体类对象中的属性名获取属性值,注意${}需要手动加单引号
<insert id="insertUser">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
insert>
@Test
public void insertUser() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = new User(null,"Tom","123456",12,"男","[email protected]");
mapper.insertUser(user);
}
可以通过@Param注解标识mapper接口中的方法参数,此时,会将这些参数放在map集合中
只需要通过${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
<select id="CheckLoginByParam" resultType="User">
select * from t_user where username = #{username} and password = #{password}
select>
@Test
public void checkLoginByParam() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
mapper.CheckLoginByParam("admin","123456");
}
建议分成两种情况进行处理
配置文件等延用第三章,这里对mapper/SelectMapper.java、resources/SelectMapper.xml、test/SelectMapperTest.java进行编写
SelectMapper.java
package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.pojo.User;
public interface SelectMapper {
/**
* 根据id查询用户信息
*/
List<User> getUserById(@Param("id") Integer id);
/**
* 查询所有的用户信息
*/
List<User> getAllUser();
/**
* 查询用户信息的总记录数
*/
Integer getCount();
/**
* 根据id查询用户信息为一个map集合
*/
Map<String, Object> getUserByIdToMap(@Param("id") Integer id);
/**
* 查询所有用户信息为map集合
*/
//List
@MapKey("id")
Map<String, Object> getAllUserToMap();
}
SelectMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.SelectMapper">
<select id="getUserById" resultType="User">
select * from t_user where id = #{id}
select>
<select id="getAllUser" resultType="User">
select * from t_user
select>
<select id="getCount" resultType="_int">
select count(*) from t_user
select>
<select id="getUserByIdToMap" resultType="map">
select * from t_user where id = #{id}
select>
<select id="getAllUserToMap" resultType="map">
select * from t_user
select>
mapper>
SelectMapperTest.java
package com.atguigu.mybatis.test;
import com.atguigu.mybatis.mapper.SelectMapper;
import com.atguigu.mybatis.utils.SqlSessionUtils;
public class SelectMapperTest {
/**
* MyBatis的各种查询功能:
* 1、若查询出的数据只有一条
* a>可以通过实体类对象接收
* b>可以通过list集合接收
* c>可以通过map集合接收
* 结果:{password=123456, sex=男, id=3, age=23, [email protected], username=admin}
* 2、若查询出的数据有多条
* a>可以通过实体类类型的list集合接收
* b>可以通过map类型的list集合接收
* c>可以在mapper接口的方法上添加@MapKey注解,此时就可以将每条数据转换的map集合作为值,以某个字段的值作为键,放在同一个map集合中
* 注意:一定不能通过实体类对象接收,此时会抛异常TooManyResultsException
*
* MyBatis中设置了默认的类型别名
* java.lang.Integer-->int,integer
* int-->_int,_integer
* Map-->map
* String-->string
*/
@Test
public void testGetAllUserToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllUserToMap());
}
@Test
public void testGetUserByIdToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getUserByIdToMap(3));
}
@Test
public void testGetCount(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getCount());
}
@Test
public void testGetAllUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllUser());
}
@Test
public void testGetUserById(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getUserById(3));
}
}
{password=123456, sex=男, id=1, age=23, username=admin}
/**
* 根据用户id查询用户信息
* @param id
* @return
*/
User getUserById(@Param("id") int id);
<select id="getUserById" resultType="User">
select * from t_user where id = #{id}
select>
@Test
public void testGetUserById(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getUserById(3));
}
/**
* 查询所有的用户信息
*/
List<User> getAllUser();
<select id="getAllUser" resultType="User">
select * from t_user
select>
@Test
public void testGetAllUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getAllUser());
}
/**
* 查询用户的总记录数
* @return
* 在MyBatis中,对于Java中常用的类型都设置了类型别名
* 例如:java.lang.Integer-->int|integer
* 例如:int-->_int|_integer
* 例如:Map-->map,List-->list
*/
int getCount();
<select id="getCount" resultType="_integer">
select count(id) from t_user
select>
@Test
public void testGetCount(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getCount());
}
Map<String, Object> getUserToMap(@Param("id") int id);
<select id="getUserToMap" resultType="map">
select * from t_user where id = #{id}
select>
/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
*/
List<Map<String, Object>> getAllUserToMap();
<select id="getAllUserToMap" resultType="map">
select * from t_user
select>
/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
*/
@MapKey("id")
Map<String, Object> getAllUserToMap();
<select id="getAllUserToMap" resultType="map">
select * from t_user
select>
对SQLMapper.java、SQLMapper.xml、SQLMapperTest.java进行编写 ,其他代码延用上面的
SQLMapper.java
package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.pojo.User;
public interface SQLMapper {
/**
* 根据用户名模糊查询用户信息
*/
List<User> getUserByLike(@Param("username") String username);
/**
* 批量删除
*/
int deleteMore(@Param("ids") String ids);
/**
* 查询指定表中的数据
*/
List<User> getUserByTableName(@Param("tableName") String tableName);
/**
* 添加用户信息
*/
void insertUser(User user);
}
SQLMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.SQLMapper">
<select id="getUserByLike" resultType="User">
select * from t_user where username like "%"#{username}"%"
select>
<delete id="deleteMore">
delete from t_user where id in (${ids})
delete>
<select id="getUserByTableName" resultType="User">
select * from ${tableName}
select>
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
insert>
mapper>
SQLMapperTest.java
package com.atguigu.mybatis.test;
import com.atguigu.mybatis.mapper.SQLMapper;
import com.atguigu.mybatis.pojo.User;
import com.atguigu.mybatis.utils.SqlSessionUtils;
public class SQLMapperTest {
@Test
public void testGetUserByLike(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<User> list = mapper.getUserByLike("a");
System.out.println(list);
}
@Test
public void testDeleteMore(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
int result = mapper.deleteMore("1,2,3");
System.out.println(result);
}
@Test
public void testGetUserByTableName(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<User> list = mapper.getUserByTableName("t_user");
System.out.println(list);
}
@Test
public void testInsertUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
User user = new User(null, "王五", "123", 23, "男", "[email protected]");
mapper.insertUser(user);
System.out.println(user);
}
@Test
public void testJDBC() throws Exception {
Class.forName("");
Connection connection = DriverManager.getConnection("", "", "");
PreparedStatement ps = connection.prepareStatement("insert", Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
ResultSet resultSet = ps.getGeneratedKeys();
}
}
/**
* 根据用户名进行模糊查询
* @param username
* @return java.util.List
* @date 2022/2/26 21:56
*/
List<User> getUserByLike(@Param("username") String username);
<select id="getUserByLike" resultType="User">
select * from t_user where username like "%"#{mohu}"%"
select>
select * from t_user where username like "%"#{mohu}"%"
是最常用的 @Test
public void testGetUserByLike(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<User> list = mapper.getUserByLike("a");
System.out.println(list);
}
只能使用${},如果使用#{},则解析后的sql语句为delete from t_user where id in ('1,2,3')
,这样是将1,2,3
看做是一个整体,只有id为1,2,3
的数据会被删除。正确的语句应该是delete from t_user where id in (1,2,3)
,或者delete from t_user where id in ('1','2','3')
/**
* 根据id批量删除
* @param ids
* @return int
* @date 2022/2/26 22:06
*/
int deleteMore(@Param("ids") String ids);
<delete id="deleteMore">
delete from t_user where id in (${ids})
delete>
//测试类
@Test
public void deleteMore() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
int result = mapper.deleteMore("1,2,3,8");
System.out.println(result);
}
只能使用**${}**,因为表名不能加单引号
/**
* 查询指定表中的数据
* @param tableName
* @return java.util.List
* @date 2022/2/27 14:41
*/
List<User> getUserByTableName(@Param("tableName") String tableName);
<select id="getUserByTableName" resultType="User">
select * from ${tableName}
select>
@Test
public void testGetUserByTableName(){
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)
在mapper.xml中设置两个属性
useGeneratedKeys:设置使用自增的主键
/**
* 添加用户信息
* @param user
* @date 2022/2/27 15:04
*/
void insertUser(User user);
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values (null,#{username},#{password},#{age},#{sex},#{email})
insert>
//测试类
@Test
public void insertUser() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
User user = new User(null, "ton", "123", 23, "男", "[email protected]");
mapper.insertUser(user);
System.out.println(user);
//输出:user{id=10, username='ton', password='123', age=23, sex='男', email='[email protected]'},自增主键存放到了user的id属性中
}