?日志级别: debug< info < Warning < error?
<!-- 日志 , 会自动传递slf4j门面-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
@Test
public void testLogger(){
Logger logger = LoggerFactory.getLogger(MyBatisTest.class);
logger.debug("我是debug日志");
logger.info("我是info日志");
logger.warn("我是警告日志");
logger.error("我是错误日志");
}
? info == System.out
? ? logback日志默认加载resources中的logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置,ConsoleAppender表示输出到控制台 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是:TRACE、DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别,可也是包名或全类名。 -->
<logger name="com.atguigu.mybatis" level="DEBUG" />
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/top_news?serverTimezone=UTC&rewriteBatchedStatements=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
? ?<properties resource="jdbc.properties"/>? 注意properties标签位置
<!-- 加载配置文件 key-value的结构加载到mybatis的内存中-->
<properties resource="jdbc.properties"/>
<!--设置连接数据库的环境
default: 默认链接的数据库
id: 指定数据库连接的编号
-->
<environments default="development">
<environment id="development">
<!--事务管理器 控制事务 JDBC -->
<transactionManager type="JDBC"/>
<!--指定数据源 POOLED 池化-->
<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="mappers/UserMapper.xml"/>
</mappers>
编辑mybatis的核心配置文件<typeAliases>
? 注意标签位置
别名定义
<typeAliases>
<typeAlias type="com.liu.pojo.User" alias="User"/>
</typeAliases>
定义别名包 :指定公共前缀
<typeAliases>
<!-- <typeAlias type="com.liu.pojo.User" alias="User"/>-->
<!-- 定义别名包,可根据类名自动拼接-->
<package name="com.liu.pojo"/>
</typeAliases>
sql标签
<!--要求sql标签的id 必须与方法的名称一致 -->
<select id="findAll" resultType="User">
select id,name,age,sex from user
</select>
? ? ? ? ?${xxxx}取值
? ? ? ? ? ? ? ? $符取值? 没有引号? 需要自己手动添加
? ? ? ? ? ? ? ? $符取值 没有预编译的效果 ,有sql注入的风险
? ? ? ? ? ? ? ? $符只是字符串的拼接
? ? ? ? #{}取值
? ? ? ? ? ? ? ?#有预编译的效果
? ? ? ? ? ? ? ?#会为字符串自动添加引号
? ? ? ? ? ? ? ?
@Test
public void test02() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
String name = "星期一";
List<User> userList = mapper.findName(name);
userList.forEach(System.out::println);
}
<select id="findName" resultType="User">
select * from user where name = #{name}
</select>
模糊查询时使用
@Test
public void test03() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
String name = "节";
List<User> userList = mapper.findLikeName(name);
userList.forEach(System.out::println);
}
<select id="findLikeName" resultType="com.liu.pojo.User">
select id,name,age,sex from user where name like "%${name}%"
</select>
以字段为参数时
@Test
public void test04() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
String column = "age";
List<User> userList = mapper.findOrderBy(column);
userList.forEach(System.out::println);
}
<select id="findOrderBy" resultType="com.liu.pojo.User">
select id,name,age,sex from user order by "${age}"
</select>
? 原则:
单值传递与名无关,只与下标有关 args,param
1. 使用#号和$
符时,如果只有一个参数时,使用任意名称都可以获取参数
2. 但是使用$
{} 时 不能以数字为参数
3.使用$ 不能写NULL
使用$不能写数字,但是#可以
说明:接口中的参数个数有多个
取值规则:arg0,arg1? ? ?param1,param2
@Test
public void test06() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int age = 18;
String sex = "女";
List<User> userList = mapper.findByAS(age,sex);
userList.forEach(System.out::println);
}
<select id="findByAS" resultType="com.liu.pojo.User">
select * from user where age = #{param1} and sex = #{param2}
</select>
?说明: 基于mybatis的原则,可以把多值封装为单值对象
@Test
public void test05() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int age = 18;
String sex = "女";
Map map = new HashMap();
map.put("age",age);
map.put("sex",sex);
List<User> userList = mapper.findByAS(map);
userList.forEach(System.out::println);
}
??
<select id="findByAS" resultType="com.liu.pojo.User">
select * from user where age = #{age} and sex = #{sex}
</select>
mybatis针对Map封装数据提供了注解的支持
List<User> findByAnno(@Param("age") int age,
@Param("sex") String sex);
<select id="findByAnno" resultType="com.liu.pojo.User">
select * from user where age = #{age} and sex = #{sex}
</select>
增删改需要开启事务
增加
@Test
public void testInsert(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(null,"刘谦",30,"男");
int rows= mapper.insertUser(user);
System.out.println("影响的行数" + rows);
}
<insert id="insertUser">
insert into user values (null,#{name},#{age},#{sex})
</insert>
修改
@Test
public void testUpdate(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(41,"宋江",30,"男");
int rows = mapper.updateUser(user);
System.out.println("影响的行数"+rows);
}
@Test
public void testUpdate1(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int rows = mapper.updateUser(new User(2,"吴用",10,"男"));
System.out.println("影响的行数"+rows);
}
<update id="updateUser">
update user
set name = #{name},
age = #{age},
sex = #{sex}
where id = #{id}
</update>
删除
@Test
public void testDelete(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id = mapper.deleteUser(1);
System.out.println("影响的行数"+id);
}
<delete id="deleteUser">
delete from user where id = #{id}
</delete>
说明:MyBatis默认条件下使用mappers标签引入映射文件
优化:采用package标签优化属性
<!--引入映射文件-->
<mappers>
<!-- <mapper resource="mappers/UserMapper.xml"/>-->
<package name="com.liu.mapper"/>
</mappers>
注意事项:
mapper.xml映射文件的路径必须与接口的包路径一致? ? ?用 / 创建包
target包里面接口和xml在一个包下
@Test
public void test08(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap();
map.put("minage",18);
map.put("maxage",100);
List<User> userlist =mapper.findByAge(map);
userlist.forEach(System.out::println);
}
CDATA标签:
在sql语句中 当大于或者小于号或者其他符号被当做标签使用,则使用转义字符
<select id="findByAge" resultType="com.liu.pojo.User">
<![CDATA[
select * from user where age >= #{minage} and age <= #{maxage}
]]>
</select>
? ?有时查询的数据可能只返回部分结果,没有返回全部数据,用map返回
MyBatis针对与类型有两种写法? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 1. 包名.类型? java.util.Map
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2.小写字符? ?map? ? (要配置别名包)
@Test
public void test09(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
String sex = "男";
List<User> userlist =mapper.findBySex(sex);
System.out.println(userlist);
}
<select id="findBySex" resultType="map">
select name,age from user where sex = #{sex}
</select>
? ? ??
useGeneratedKeys = "true" 开启主键自增
keyColumn = "id"? ? 指定自增的字段? ?主键自增 一张表只有一个? ?可以不写
keyProperty= "id"? ? ? ? 制定映射的属性
@Test
public void testInsert(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(null,"刘谦",30,"男");
// int rows= mapper.insertUser(user);
// System.out.println("影响的行数" + rows);
mapper.insertUser(user);
System.out.println(user);
}
<insert id="insertUser" useGeneratedKeys="true"
keyColumn="id" keyProperty="id" >
insert into user
values (null, #{name}, #{age}, #{sex})
</insert>
? 1.foreach循环遍历
@Test
public void test10(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Integer[] array = {1,3,4,5,7};
List list = Arrays.asList(array);//利用get方法获取参数
List<User> userList = mapper.getArray(list);
System.out.println(userList);
}
<!-- collertion 遍历的数组集合
数组: array List集合:list
open/close 循环遍历的开始和结束
index 循环遍历时的索引值 利用 ${index} 或者 #{index}获取
item 循环遍历的数据 ${item} 或者 #{item}获取
separator 分隔符 1,2,3,4
-->
<select id="getArray" resultType="com.liu.pojo.User">
select * from user where id in
<foreach collection="list" open="(" close=") " index="index" item="item" separator=",">
#{item}
</foreach>
</select>
如果循环遍历时,参数是Map集合,则collection? 写map中的key? 也就是数组的名称
? ? 要求:map.value是一个可遍历的值 例如是一个list,array
//要求: 查询id= 1,3,4,5,同时sex = "男"
@Test
public void test11(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap();
map.put("ids",new Integer[]{1,3,4,5});
map.put("sex","男");
List<User> userList = mapper.selectArray(map);
System.out.println(userList);
}
<!--如果循环遍历时 参数是Map集合 则collection 写map中的key
要求: map.value 必须是可遍历的数据
-->
<select id="selectArray" resultType="com.liu.pojo.User">
select * from user where sex = #{sex} and id in
<foreach collection="ids" open="(" close=") " index="index" item="item" separator=",">
#{item}
</foreach>
</select>