目录
一 介绍二 框架mybatis配置SqlSessionFactoryExecutorMapped Statement
三 实践依赖项目结构SqlMapConfig实体类映射文件数据库配置测试代码
参考
一 介绍
MyBatis是一个优秀的持久层框架,,它对jdbc的操作数据库的过程进行封装。
本质 Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。
二 框架
mybatis配置
SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。 mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。
SqlSessionFactory
通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂 由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。
Executor
mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。
Mapped Statement
Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程
三 实践
依赖
plugins
{
id
'java'
}
group
'com.zyc'
version
'1.0-SNAPSHOT'
sourceCompatibility
= 1.8
repositories
{
mavenCentral()
}
dependencies
{
testCompile group
: 'junit', name
: 'junit', version
: '4.12'
compile group
: 'org.mybatis', name
: 'mybatis', version
: '3.4.6'
compile group
: 'mysql', name
: 'mysql-connector-java', version
: '5.1.46'
}
项目结构
SqlMapConfig
<?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>
<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://localhost:3306/mybatis1?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zyc/mapping/User.xml"/>
</mappers>
</configuration>
实体类
package com
.zyc
.entity
;
import java
.util
.Date
;
public class User {
private Integer id
;
private String username
;
private String sex
;
private String address
;
private Date birthday
;
public Integer
getId() {
return id
;
}
public void setId(Integer id
) {
this.id
= id
;
}
public String
getUsername() {
return username
;
}
public void setUsername(String username
) {
this.username
= username
;
}
public String
getSex() {
return sex
;
}
public void setSex(String sex
) {
this.sex
= sex
;
}
public String
getAddress() {
return address
;
}
public void setAddress(String address
) {
this.address
= address
;
}
public Date
getBirthday() {
return birthday
;
}
public void setBirthday(Date birthday
) {
this.birthday
= birthday
;
}
@Override
public String
toString() {
return "User [id=" + id
+ ", username=" + username
+ ", sex=" + sex
+ ", address=" + address
+ ", birthday=" + birthday
+ "]";
}
}
映射文件
<?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.zyc.mapping.User">
<select id="findUserById" parameterType="int" resultType="com.zyc.entity.User">
select username,DATE_FORMAT(birthday,'%Y-%m-%d')birthday,sex,address from t_user where id=#{id}
</select>
<select id="findUserByName" parameterType="java.lang.String" resultType="com.zyc.entity.User" >
select * from t_user where username LIKE '%${value}%'
</select>
<select id="getUserList" resultType="com.zyc.entity.User">
select username,birthday,sex,address from t_user
</select>
<insert id="insertUser" parameterType="com.zyc.entity.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into t_user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
<update id="updateUser" parameterType="com.zyc.entity.User">
update t_user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
where id=#{id}
</update>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from t_user where id=#{id}
</delete>
</mapper>
数据库配置
CREATE TABLE t_user
(
id
INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username
VARCHAR(30) NOT NULL COMMENT '用户名称',
birthday
DATE DEFAULT NULL COMMENT '生日',
sex
CHAR(2) DEFAULT NULL COMMENT '性别',
address
VARCHAR(256) DEFAULT NULL COMMENT '地址'
);
INSERT INTO t_user
(username
,birthday
,sex
,address
)
VALUES
('小A','2015-06-27','2','北京'),
('小B','2015-06-27','2','北京'),
('小C','2015-06-27','1','北京'),
('小D','2015-06-27','2','北京');
测试代码
public class Test1 {
private SqlSession sqlSession
= null
;
private String resource
= "SqlMapConfig.xml";
private InputStream inputStream
= null
;
@Before
public void befor() {
try {
inputStream
= Resources
.getResourceAsStream(resource
);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);
sqlSession
= sqlSessionFactory
.openSession();
} catch (IOException e
) {
e
.printStackTrace();
}
}
@After
public void after() {
if (sqlSession
!= null
) {
sqlSession
.close();
}
if (inputStream
!= null
) {
try {
inputStream
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
@Test
public void findUserByIdTest() {
User user
= sqlSession
.selectOne("com.zyc.mapping.User.findUserById", 1);
System
.out
.println(user
.toString());
}
@Test
public void findUserByNameTest() {
List
<User> list
= sqlSession
.selectList("com.zyc.mapping.User.findUserByName","小");
System
.out
.println(list
);
}
@Test
public void insertUserTest(){
User user
= new User();
user
.setUsername("小红");
user
.setSex("1");
user
.setBirthday(new Date());
user
.setAddress("北京");
sqlSession
.insert("com.zyc.mapping.User.insertUser",user
);
sqlSession
.commit();
System
.out
.println(user
.getId());
}
@Test
public void updateUserTest(){
User user
= new User();
user
.setId(2);
user
.setUsername("小黑");
user
.setSex("2");
user
.setBirthday(new Date());
user
.setAddress("上海");
sqlSession
.update("com.zyc.mapping.User.updateUser",user
);
sqlSession
.commit();
}
@Test
public void deleteUserTest(){
sqlSession
.delete("com.zyc.mapping.User.deleteUser",1);
sqlSession
.commit();
}
}
参考
Mybatis学习总结(一)——入门基础