mybatis学习day02
4.CRUD
增删改需要提交事务
4.1.namespace
namespace中的包名要和Dao、Mapper包对应
4.2.select
- ID 对应方法名
- reslutType:sql返回值的类型
- parameterType:方法参数类型
<!--select查询语句-->
<select id="getUserList" resultType="com.alex.pojo.User">
select * from USER ;
</select>
<select id="getUserById" parameterType="int" resultType="com.alex.pojo.User">
select * from user where id = #{id};
</select>
public void getUserByIdTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
4.3 insert
<insert id="insertUser" parameterType="com.alex.pojo.User">
insert into user(id,name,pwd) values(#{id},#{name},#{pwd});
</insert>
public void insertUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4,"张三丰","123564");
int res= mapper.insertUser(user);
if(res > 0 ){
System.out.println("插入成功");
}
sqlSession.commit();
sqlSession.close();
}
4.4 update
<update id="updateUser" parameterType="com.alex.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
public void updateUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.updateUser(new User(4, "张大大", "243523"));
if(res > 0){
System.out.println("更新成功");
}
sqlSession.commit();
sqlSession.close();
}
4.5 delete
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id};
</delete>
public void deleteUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.deleteUser(4);
if(res>0){
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
4.6 错误分析
-
Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '4' for key 'PRIMARY'
插入时主键存在异常,需要换一个主键
-
标签不要匹配错
-
程序配置文件需要符合规范
-
空指针异常
-
乱码问题
-
maven文件未导出问题
-
Caused by: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'com.alex.dao.UserMapper.getUserLike'. It's likely that neither a Result Type nor a Result Map was specified.
xml中没有指定返回值类型
4.7 万能map
-
why
- 在调用sql语句时,当传递一个对象需要使用该对象的构造方法,另外sql中有可能有非空的约束条件,可能在编写一个简单sql语句需要给出多个参数。
- 则可以通过map实现对对象的赋值过程,只需要在执行sql语句中传递相对应的值而不需要重新传递整个参数
User getUserByID_versionStronger(Map<String,Object> map);public void getUserByID_versionStronger(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<String, Object>(); map.put("identity",1); User user = mapper.getUserByID_versionStronger(map); System.out.println(user); sqlSession.close(); }<!--map使用sql查询--> <select id="getUserByID_versionStronger" parameterType="map" resultType="com.alex.pojo.User"> select * from user where id=#{identity}; </select>区别:
Map传递参数,在sql中取值
对象传递参数,在sql中取属性
多个参数用map,或注解
4.8 模糊查询
-
在sql拼接中使用通配符
注意 sql注入问题
<select id="getUserLike" resultType="com.alex.pojo.User">
select * from user where name like "%"#{name}"%";
</select>
List<User> userLike = mapper.getUserLike("张");
- 在Java执行中传递通配符
<select id="getUserLike" resultType="com.alex.pojo.User">
select * from user where name like #{name};
</select>
List<User> userLike = mapper.getUserLike("%张%");
5. 配置解析
5.1 核心配置文件
MyBatis 的配置文件包含了影响 MyBatis 行为甚深的设置(settings)和属性(properties)信息
configuration 配置
properties 属性
settings 设置
typeAliases 类型命名
typeHandlers 类型处理器
objectFactory 对象工厂
plugins 插件
environments 环境
environment 环境变量
transactionManager 事务管理器
dataSource 数据源
databaseIdProvider 数据库厂商标识
mappers 映射器
5.2 环境配置(environments)
- MyBatis 可以配置成适应多种环境
- 尽管可以配置多个环境,每个 SqlSessionFactory 实例只能选择其一
- mybatis默认事务管理器是JDBC,默认连接池为POOLED
5.3 属性(Properties)
-
可以通过Properties配置文件属性
-
这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递【db.properties】
-
配置Properties属性需要满足在配置文件中的第一个

编写一个配置文件
db.properties
diver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8
username=root
password=1234
核心配置中引入文件映射
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="1234"/>
</properties>
配置属性时
通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的是 properties 属性中指定的属性
外部映射的优先级比
标签的映射级别高
-
可直接外部映射
即Properties文件映射
-
可用外部映射和
标签映射 -
当出现重名问题看优先级使用外部映射
5.4 别名(typeAliases)
-
类型别名是为 Java 类型设置一个短的名字
-
用来减少类完全限定名的冗余
<typeAliases> <typeAlias type="com.alex.pojo.User" alias="user"/> <package name="com.alex.pojo.User"/> </typeAliases>
别名使用
-
标签使用时,可以DIY名称 -
标签使用时,使用首字母小写的非限定类名来作为它的别名。若想自行DIY则通过注解方式实现 @Alias("User" public class User
5.5 设置(Setting)


5.6 其他配置
- typeHandlers 类型处理器
- objectFactory 对象工厂
- plugins 插件
- mybatis-generator-core
- mybatis-plus
- 通用mapper
5.7 映射(Mapper)
MapperRegister:注册我们绑定的mapper映射文件
实现方式
-
resource实现
<mappers> <mapper resource="com/alex/dao/UserMapper.xml"/> </mappers> -
class实现
<mappers> <mapper class="com.alex.dao.UserMapper"/> </mappers>注意点
- 接口和其Mapper配置文件必须同名
- 接口和其Mapper配置文件必须在同一个包下
-
package实现
<mappers> <package name="com.alex.dao"/> </mappers>注意点
- 接口和其Mapper配置文件必须同名
- 接口和其Mapper配置文件必须在同一个包下
6. 生命周期和作用域

作用域和生命周期类是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder
- 局部方法变量
- 一旦创建了 SqlSessionFactory,就不再需要它了
SqlSessionFactory
-
理解为数据库连接池
-
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由对它进行清除或重建
-
使用单例模式或者静态单例模式
SqlSession
-
连接数据库的请求
-
不是线程安全的,不能被共享的
-
范围是请求或方法范围
-
用完后关闭操作,否则资源被占用
7. 解决属性名和字段名不一致的问题
7.1 问题
当出现属性名和字段名不一致时,查询返回的结果集中该字段不一致的部分结果为null
public class User {
private int id;
private String name;
private String password;
}
数据库中字段为 id name pwd
-
解决:修改sql语句起别名
<select id="getUserList" resultType="user"> select id,name,pwd as password from mybatis.user ; </select>
7.2 resultMap
<resultMap id="USER_SUPPER" type="user">
<result column="pwd" property="password"></result>
</resultMap>
<!--select查询语句-->
<select id="getUserList" resultMap="USER_SUPPER">
select * from mybatis.user ;
</select>
-
resultMap 元素是 MyBatis 中最重要最强大的元素
让你远离 90%的需要从结果 集中取出数据的 JDBC 代码的那个东西, 而且在一些情形下允许你做一些 JDBC 不支持的事 情
-
resultMap 的设计:简单语句不需要明确的结果映射,复杂语句需要描述它的关系
简单语句只需要修改 属性和字段不一致的地方。如上面代码

浙公网安备 33010602011771号