简介
1.1 什么是 MyBatis ?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
1.2 功能架构
Mybatis的功能架构分为三层:
image
-
API接口层:提供给外部使用的接口 API,开发人员通过这些本地 API 来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
-
数据处理层:负责具体的 SQL 查找、SQL 解析、SQL 执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
-
基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件,为上层的数据处理层提供最基础的支撑。
1.3 框架架构
image快速入门
1.1 配置mybatis所需的jar包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
1.2 创建数据库
mysql> create table user(
-> id int primary key auto_increment,
-> username varchar(20),
-> password varchar(20),
-> sex varchar(10),
-> address varchar(20));
1.3 mysql驱动配置文件mysql.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis
jdbc.username=root
jdbc.password=root
1.4 mybatis配置文件mybatis.cfg.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="mysql.properties"></properties>
<!-- 为JAVA Bean起类别名 -->
<typeAliases >
<!-- 别名方式1,一个一个的配置 type中放置的是类的全路径,alias中放置的是类别名
<typeAliase type="com.mybatis.beans.UserBean" alias="UserBean"/> -->
<!-- 别名方式2,自动扫描,将JAVA类的类名作为类的类别名 -->
<package name="com.mybatis.beans"/>
</typeAliases>
<!-- 配置mybatis运行环境 -->
<environments default="development">
<environment id="development">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<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>
<!-- 告知映射文件方式1,一个一个的配置
<mapper resource="com/mybatis/mapper/UserMapper.xml"/>-->
<!-- 告知映射文件方式2,自动扫描包内的Mapper接口与配置文件 -->
<package name="com/mybatis/mapper"/>
</mappers>
</configuration>
1.5 UserBean类
public class UserBean {
private Integer id;
private String username;
private String password;
private String sex;
private String address;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
}
1.6 方法接口UserMapper.java
public interface UserMapper {
/*
* 新增用戶
* @param user
* @return
* @throws Exception
*/
public int insertUser(User user) throws Exception;
/*
* 修改用戶
* @param user
* @param id
* @return
* @throws Exception
*/
public int updateUser(User user) throws Exception;
/*
* 刪除用戶
* @param id
* @return
* @throws Exception
*/
public int deleteUser(Integer id) throws Exception;
/*
* 根据id查询用户信息
* @param id
* @return
* @throws Exception
*/
public User selectUserById(Integer id) throws Exception;
/*
* 查询所有的用户信息
* @return
* @throws Exception
*/
public List<User> selectAllUser() throws Exception;
}
1.7 SQL映射文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.UserMapper">
<!-- 自定义返回结果集 -->
<resultMap id="userMap" type="User">
<id property="id" column="id" javaType="int"></id>
<result property="username" column="username" javaType="String"></result>
<result property="password" column="password" javaType="String"></result>
<result property="sex" column="sex" javaType="String"></result>
<result property="address" column="address" javaType="String"></result>
</resultMap>
<!-- 定义 SQL 语句,其中 id 需要和接口中的方法名一致 -->
<!-- useGeneratedKeys:实现自动生成主键 -->
<!-- keyProperty: 唯一标记一个属性 -->
<!-- parameterType 指明查询时使用的参数类型,resultType 指明查询返回的结果集类型 -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into user (username,password,sex,address) values
(#{username},#{password},#{sex},#{address})
</insert>
<update id="updateUser" parameterType="User">
update user set
address=#{address} where
id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where
id=#{id}
</delete>
<!-- 如未为 Java Bean 起类别名,resultType="com.mybatis.bean.UserBean" -->
<!-- 使用resultType时,一定要保证,你属性名与字段名相同;如果不相同,就使用resultMap -->
<select id="selectUserById" parameterType="int" resultType="User">
select * from user where id=#{id}
</select>
<select id="selectAllUser" resultMap="userMap">
select * from user
</select>
</mapper>
1.8 测试类
public class UserTest {
private static SqlSessionFactory sqlSessionFactory;
public static void main(String[] args) {
// Mybatis 配置文件
String resource = "mybatis.cfg.xml";
// 得到配置文件流
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
// 创建会话工厂,传入 MyBatis 的配置文件信息
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// insertUser();
// updateUser();
// deleteUser();
// selectUserById();
selectAllUser();
}
// 新增用戶
private static void insertUser() {
// 通过工厂得到 SqlSession
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User();
user.setUsername("Tom");
user.setPassword("123456");
user.setSex("male");
user.setAddress("chengdu");
try {
mapper.insertUser(user);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
// 释放资源
session.close();
}
// 更新用戶
private static void updateUser() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = null;
try {
user = mapper.selectUserById(1);
} catch (Exception e1) {
e1.printStackTrace();
}
user.setAddress("chongqing");
try {
mapper.updateUser(user);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
session.close();
}
// 删除用戶
private static void deleteUser() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
try {
mapper.deleteUser(3);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
session.close();
}
// 根据id查询用户信息
private static void selectUserById() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
try {
User user = mapper.selectUserById(1);
session.commit();
System.out.println(user.getId() + " " + user.getUsername() + " "
+ user.getPassword() + " " + user.getSex() + " "
+ user.getAddress());
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
session.close();
}
// 查询所有的用户信息
private static void selectAllUser() {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
try {
List<User> userList = mapper.selectAllUser();
session.commit();
for (User user : userList) {
System.out.println(user.getId() + " " + user.getUsername() + " "
+ user.getPassword() + " " + user.getSex() + " "
+ user.getAddress());
}
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
session.close();
}
}
网友评论