mybatis初探(一)
一、什么是mybatis
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。 MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录.
1)MyBATIS 目前提供了三种语言实现的版本,包括:Java、.NET以及Ruby。(我主要学习java,就讲java的使用)
2)它提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。
3)mybatis与hibernate的对比?
mybatis提供一种“半自动化”的ORM实现。 这里的“半自动化”,是相对Hibernate等提供了全面的数据库封装机制的“全自动化”ORM实现而言,“全自动”ORM实现了POJO和数据库表之间的映射,以及 SQL 的自动生成和执行。 而mybatis的着力点,则在于POJO与SQL之间的映射关系。
二、mybatis架构图
执行流程:
1、mapper-config.xml配合好全局属性,经数据源引入映射文件(mapper.xml)
2、通过SqlSessionFactory工厂bean获取sqlsession会话对象实例
3、sqlsession对象操作CRUD
4、执行器将statement中的数据库语句解析执行相关的数据库操作
三、mybatis入门实例
3.1、引入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--引入spring的相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version> 5.1.5.RELEASE </version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
3.2、配置mybatis-config.xml全局文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--各个标签的顺序不能变-->
<properties resource="application.properties"></properties>
<!--延时加载: -->
<!--1、直接加载:执行完对主加载对象的select语句,马上执行对关联对象的select查询。-->
<!--2、侵入式延迟(按需加载):执行对主加载对象的查询时,不会执行对关联对象的查询。但当要访问主加载对象的详情时,就会马上执行关联对象的select查询。-->
<!--3、深度延迟:执行对主加载对象的查询时,不会执行对关联对象的查询。访问主加载对象的详情时也不会执行关联对象的select查询。只有当真正访问关联对象的详情时,才会执行对关联对象的select查询。-->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<environments default="demoMyBatis">
<environment id="demoMyBatis">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/studentMapper.xml"/>
<mapper resource="mapper/UserMapper.xml"/>
<mapper resource="mapper/CountryMapper.xml"/>
<mapper resource="mapper/MinisterMapper.xml"/>
<mapper resource="mapper/NewsMapper.xml"/>
</mappers>
</configuration>
3.3、创建数据库表及其实例对象
1、创建student数据库表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(2) NOT NULL AUTO_INCREMENT,
`user_name` varchar(15) COLLATE utf8_bin NOT NULL,
`password` varchar(15) COLLATE utf8_bin NOT NULL,
`local_address` varchar(25) COLLATE utf8_bin NOT NULL,
`sex` varchar(4) COLLATE utf8_bin NOT NULL,
`age` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*Data for the table `student` */
insert into `student`(`id`,`user_name`,`password`,`local_address`,`sex`,`age`) values
(1,'李薇','234155','湖南常德','女',34),
(2,'李四','123456','深圳市龙华区','男',27),
(3,'mark','123456','美国华盛顿','男',47);
2、创建student实体
private int id;
private String username;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", localAddress='" + localAddress + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
private String password;
private String localAddress;
private String sex;
private int age;
public int getId() {
return id;
}
public void setId(int 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 String getLocalAddress() {
return localAddress;
}
public void setLocalAddress(String localAddress) {
this.localAddress = localAddress;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
3.4、配置StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.achuan.demo.dao.StudentDao">
<select id="selectById" parameterType="int" resultMap="student">
select * from student where id = #{id}
</select>
<select id="selectAll" resultMap="student">
select * from student;
</select>
<select id="selectBySex" parameterType="string" resultMap="student">
select * from student where sex = #{sex};
</select>
<!--useGeneratedKeys:开启主键回写
keyColumn:指定数据库的主键
keyProperty:主键对应的pojo属性名-->
<insert id="insert" parameterType="com.achuan.demo.entity.Student" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into student(
id,
user_name,
password,
sex,
local_address,
age
)values (
null,
#{username},
#{password},
#{sex},
#{localAddress},
#{age}
);
</insert>
<update id="update" parameterType="com.achuan.demo.entity.Student">
update student
<trim prefix="set" suffixOverrides=",">
<if test="username!=null">user_name = #{username},</if>
<if test="password!=null">password = #{password},</if>
<if test="sex!=null">sex = #{sex},</if>
<if test="localAddress!=null">local_address = #{localAddress},</if>
<if test="age!=null">age = #{age}</if>
</trim>
where id = #{id};
</update>
<delete id="deleteById" parameterType="int">
delete from student where id = #{id};
</delete>
<resultMap id="student" type="com.achuan.demo.entity.Student">
<!--jdbcType的值必须得大写-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_name" jdbcType="VARCHAR" property="username"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="local_address" jdbcType="VARCHAR" property="localAddress"/>
<result column="sex" jdbcType="VARCHAR" property="sex"/>
<result column="age" jdbcType="INTEGER" property="age"/>
</resultMap>
</mapper>
3.5、实现StudentDao接口
1、创建StudentDao接口并定义增删查改数据库操作方法
public interface StudentDao {
List<Student> selectAll();
Student selectById(int id);
List<Student> selectBySex(String sex);
void insert(Student student);
void deleteById(int id);
void update(Student student);
}
2、StudentDao的实现类StudentDaoImpl
public SqlSession sqlSession;
public StudentDaoImpl(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<Student> selectAll() {
return this.sqlSession.selectList("com.achuan.demo.dao.StudentDao.selectAll");
}
@Override
public Student selectById(int id) {
return this.sqlSession.selectOne("com.achuan.demo.dao.StudentDao.selectById",id);
}
@Override
public List<Student> selectBySex(String sex) {
return this.sqlSession.selectList("com.achuan.demo.dao.StudentDao.selectBySex",sex);
}
@Override
public void insert(Student student) {
this.sqlSession.insert("com.achuan.demo.dao.StudentDao.insert",student);
}
@Override
public void deleteById(int id) {
this.sqlSession.delete("com.achuan.demo.dao.StudentDao.deleteById",id);
}
@Override
public void update(Student student) {
this.sqlSession.update("com.achuan.demo.dao.StudentDao.update",student);
}
3.6、引入log4j日志
1、pom.xml中引入log4j相关依赖
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
2、配置log4j.properties文件
log4j.rootCategory=debug, stdout
log4j.rootLogger=debug, stdout
### stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p - %m%n
### set package ###
log4j.logger.org.springframework=info
log4j.logger.org.apache.catalina=info
log4j.logger.org.apache.commons.digester.Digester=info
log4j.logger.org.apache.catalina.startup.TldConfig=info
log4j.logger.chb.test=debug
3.7、StudentTest测试类进行测试
StudentDao studentDao;
SqlSession sqlSession;
@Before
public void before() throws IOException {
//1、读取mybatis全局配置文件并获取文件输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//2、通过输入流获取sqlsession的代理工厂bean
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3、通过代理工厂bean获取sqlSessions
sqlSession = sqlSessionFactory.openSession();
//4、将sqlsession加载进userdao实例对象中去
studentDao = new StudentDaoImpl(sqlSession);
}
@Test
public void test01(){
Student student = new Student();
student.setUsername("mark");
student.setPassword("123456");
student.setAge(47);
student.setSex("男");
student.setLocalAddress("美国华盛顿");
studentDao.insert(student);
//执行数据库操作以后将数据提交给数据库
this.sqlSession.commit();
}
运行结果:
3.8、mybatis使用流程总结
1)配置mybatis-config.xml 全局的配置文件 (1、数据源,2、外部的mapper)
2)创建SqlSessionFactory
3)通过SqlSessionFactory创建SqlSession对象
4)通过SqlSession操作数据库 CRUD
5)调用session.commit()提交事务
6)调用session.close()关闭会话