目录
一、Mapper接口映射
1、创建数据库
2、搭建MVC分层结构
3、配置MyBatis全局参数
4、编辑DAO层接口
5、配置Mapper文件与DAO层绑定
(1)配置Mapper文件
(2)DAO层与Mapper文件标签的快速生成
6、代码测试
二、给类起别名
1、设置单个类别称typeAlias标签
2、批量设置别称package标签
3、Mapper映射文件修改
三、MyBatis开启驼峰映射
四、MyBatis开启日志打印
1、引入log4j日志依赖
2、log4j配置文件
3、在mybatis中开启日志
一、Mapper接口映射
不使用DAO层接口的实现类层,因为DAO层的实现类是用来实现SQL语句的,而在MyBatis框架中,SQL语句写在配置文件中,只需要将接口与配置文件连接即可操作SQL语句
1、创建数据库
CREATE DATABASE mybatisdatabase;
USE mybatisdatabase;
CREATE TABLE IF NOT EXISTS `admin`(
`uid` INT PRIMARY KEY AUTO_INCREMENT,
`username` VARCHAR(20),
`upassword` VARCHAR(20) NOT NULL,
`address` VARCHAR(10) NOT NULL
);
INSERT INTO `admin`(`username`,`upassword`,`address`) VALUES
('张三','123456','安徽合肥包河区'),
('李四','456789','安徽合肥高新区');
2、搭建MVC分层结构
3、配置MyBatis全局参数
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatisdatabase"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="admin-mapper.xml"/>
</mappers>
</configuration>
4、编辑DAO层接口
package com.mybatis.dao;
import com.mybatis.entity.Admin;
import java.util.List;
public interface AdminDao {
public int insertAdmin(Admin admin);
public int deleteAdmin(int uid);
public int updateAdmin(Admin admin);
public Admin selectOne(int uid);
public List<Admin> selectAll();
}
5、配置Mapper文件与DAO层绑定
(1)配置Mapper文件
namespac命名空间属性值为DAO层接口的全限定名
SQL语句标签的id属性值对应接口中的方法
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.dao.AdminDao">
<select id="selectOne" resultType="com.mybatis.entity.Admin">
select * from admin where uid = #{uid}
</select>
<select id="selectAll" resultType="com.mybatis.entity.Admin">
select * from admin
</select>
<insert id="insertAdmin" parameterType="com.mybatis.entity.Admin" useGeneratedKeys="true" keyColumn="uid" keyProperty="uid">
insert into `admin`(`username`,`upassword`,`address`) values (#{username},#{upassword},#{address})
</insert>
<delete id="deleteAdmin">
delete from admin where uid = #{uid}
</delete>
<update id="updateAdmin" parameterType="com.mybatis.entity.Admin">
update admin set username = #{username},upassword = #{upassword} where uid = #{uid}
</update>
</mapper>
(2)DAO层与Mapper文件标签的快速生成
鼠标点击方法名--->ALT+Enter--->Generate statement
6、代码测试
package com.mybatis;
import com.mybatis.dao.AdminDao;
import com.mybatis.entity.Admin;
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 org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class AppTest
{
//创建SqlSessionFactory工厂变量
SqlSessionFactory sqlSessionFactory;
@Before
public void init(){
System.out.println("执行init方法");
InputStream resourceAsStream;
try {
resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
throw new RuntimeException(e);
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
}
@Test
public void selectOne(){
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println("-----根据uid查询用户信息-----");
//获取接口实现类(多态)
//通过动态代理方式获得一个代理对象(实现类)
AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
//通过接口调用方法
Admin admin = adminDao.selectOne(1);
System.out.println("admin = " + admin);
sqlSession.close();
}
@Test
public void selectAll(){
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println("-----查询所有-----");
// 获取动态代理对象
AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
//通过接口调用方法
List<Admin> adminList = adminDao.selectAll();
System.out.println("adminList = " + adminList);
sqlSession.close();
}
@Test
public void addAdmin(){
//创建一个SqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建Admin对象
Admin admin = new Admin();
admin.setUsername("老六");
admin.setUpassword("147258");
admin.setAddress("山东曹县");
//获得动态代理对象
AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
//通过接口调用方法
int line = adminDao.insertAdmin(admin);
System.out.println("line = " + line);
//手动提交事务
sqlSession.commit();
//关闭资源
sqlSession.close();
}
@Test
public void deleteAdmin(){
//开启一个SqlSession会话
//开启自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//获取动态代理对象
AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
//通过接口调用方法
int line = adminDao.deleteAdmin(3);
System.out.println("line = " + line);
//关闭资源
sqlSession.close();
}
@Test
public void updateAdmin(){
//开启一个SqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建Admin对象
Admin admin = new Admin();
admin.setUsername("老四");
admin.setUpassword("666666");
admin.setUid(2);
//获取动态代理对象
AdminDao adminDao = sqlSession.getMapper(AdminDao.class);
//通过接口调用方法
int line = adminDao.updateAdmin(admin);
System.out.println("line = " + line);
//手动提交事务
sqlSession.commit();
//关闭资源
sqlSession.close();
}
}
二、给类起别名
在mybatis全局配置文件中<configuration>标签下使用typeAliases标签设置类的别名
1、设置单个类别称typeAlias标签
<typeAliases>
<typeAlias type="com.mybatis.entity.Admin" alias="admin"></typeAlias>
<typeAlias type="com.mybatis.dao.AdminDao" alias="adminDao"></typeAlias>
</typeAliases>
2、批量设置别称package标签
使用包名的方式给包中所有的类设置别名,默认别名为类名的首字母小写:
Admin ---> admin
AdminDao ---> adminDao
<typeAliases>
<package name="com.mybatis.entity"/>
<package name="com.mybatis.dao"/>
</typeAliases>
3、Mapper映射文件修改
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.dao.AdminDao">
<select id="selectOne" resultType="com.mybatis.entity.Admin">
select * from admin where uid = #{uid}
</select>
<select id="selectAll" resultType="admin">
select * from admin
</select>
<insert id="insertAdmin" parameterType="admin" useGeneratedKeys="true" keyColumn="uid" keyProperty="uid">
insert into `admin`(`username`,`upassword`,`address`) values (#{username},#{upassword},#{address})
</insert>
<delete id="deleteAdmin">
delete from admin where uid = #{uid}
</delete>
<update id="updateAdmin" parameterType="admin">
update admin set username = #{username},upassword = #{upassword} where uid = #{uid}
</update>
</mapper>
三、MyBatis开启驼峰映射
开启驼峰映射后,只要数据库字段名与实体类属性名字母相同,无论数据库字段名中加多少下划线都可以在实体类中识别成驼峰命名:
在mybatis全局配置文件中<configuration>标签下的使用settings标签设置setting开启驼峰映射
<settings>
<!-- 开启驼峰映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
四、MyBatis开启日志打印
可设置打印级别,设置控制台打印的内容
1、引入log4j日志依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、log4j配置文件
在resources目录下新建properties文件配置log4j信息
#打印日志的级别:可控制打印信息,哪些打印,哪些不打印
#Console:打印窗口
log4j.rootLogger=DEBUG,Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
#设置打印格式
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
#设置打印信息
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#打印日志级别:设置打印级别只要不是ERROR级别就不打印
log4j.logger.org.apache=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.springframework=ERROR
#这个需要
log4j.logger.log4jdbc.debug=ERROR
log4j.logger.com.gk.mapper=ERROR
log4j.logger.jdbc.audit=ERROR
log4j.logger.jdbc.resultset=ERROR
#这个打印SQL语句非常重要
log4j.logger.jdbc.sqlonly=DEBUG
log4j.logger.jdbc.sqltiming=ERROR
log4j.logger.jdbc.connection=FATAL
3、在mybatis中开启日志
在mybatis全局配置文件中<configuration>标签下的使用settings标签设置setting开启日志打印
<settings>
<!-- 开启日志打印-->
<setting name="logImpl" value="LOG4J"/>
</settings>