- MyBatis它是一个持久层框架,解决项目对数据库的CRUD操作,只要会方法名、sql语句,学mybatis框架很轻松。
1.环境准备
- idea创建Maven项目
- 导入Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>company</groupId>
<artifactId>mybatis_day01_quick</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!--测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
2.创建数据库
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
导入数据
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'张三','2018-02-27 17:47:08','男','北京'),(42,'小二王','2018-03-02 15:09:37','女','北京'),(43,'小二王','2018-03-04 11:34:34','女','北京'),(45,'李四','2018-03-04 12:04:06','男','深圳'),(46,'拳王','2018-03-07 17:37:26','男','大连'),(48,'阿宝','2018-03-08 11:44:00','女','海南');
3.创建实体类
创建包:domain
创建类:User.java
package domain;
import java.util.Date;
/****
* author:dongchen
* data:2019/6/2421:51
* descripition:
**/
public class User {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}
4.创建接口
创建接口,UserDao.java,用来操作数据库
创建包dao,创建接口UserDao.java
package dao;
import domain.User;
import java.util.List;
/****
* author:dongchen
* data:2019/6/2514:51
* descripition:
**/
public interface UserDao {
//查询所有
List<User> findAll();
}
5.创建sqlMapConfig.xml
在resources包下,新建sqlMapConfig.xml
- sqlMapConfig.xml
为了更好将数据库连接信息抽取出来,我们原来在C3P0连接池中也已经将数据库连接信息抽取出来,我们现在也一样将数据库的连接信息抽取出来,放到一个xml(SqlMapConfig.xml)文件中,后面再去对此配置文件进行xml解析,这样就可以将配置文件中的信息读取出来,以便在jdbc代码中直接使用这些数据库连接信息.
<?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>
<!--1:连接数据库的信息
transactionManager:事务管理器:JDBC(固定写法)
dataSource:数据源:POOLED(固定写法)表示使用连接池的方式获取连接
-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///itcastmybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--2:加载映射文件
mapper resource:查找映射文件的位置(映射文件和Dao放置到同一个包下)
-->
<mappers>
<mapper resource="UserDao.xml"/>
</mappers>
</configuration>
6.创建UserDao.xml
因为是maven项目,所有xml的文件应该放在resources下,创建包com.itheima.dao,创建UserDao.xml
实际工作中实体类的属性名常与表格不一致,因此这里需要定义resultMap解决:
<?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="dao.UserDao">
<!--主键字段对应-->
<resultMap id="userMap" type="domain.User">
<!--非主键字段对应-->
<id property="userId" column="id"/>
<!--对照sql进行定义-->
<result property="userName" column="username"/>
<result property="userAddress" column="address"/>
<result property="userSex" column="sex"/>
<result property="userBirthday" column="birthday"/>
</resultMap>
<!--sql查-->
<select id="findAll" resultMap="userMap">
select * from user
</select>
</mapper>
7.创建测试类验证testMybatis.java
public class MyBatisTest {
/**
* 测试mybatis的环境搭建
*/
public static void main(String[] args) throws IOException {
// 1.读取配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
// 2.根据配置文件构建SqlSessionFactory
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
// 3.使用SqlSessionFactory创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4.使用SqlSession构建Dao的代理对象
UserDao userDao = sqlSession.getMapper(UserDao.class);
// 5.执行dao的findAll方法
List<User> list = userDao.findAll();
// 第4,第5步骤可以写成
// List<User> list = sqlSession.selectList("dao.UserDao.findAll");
for(User user:list){
System.out.println(user);
}
// 5.关闭资源
sqlSession.close();
in.close();
}
}
查看测试结果.
总结:
Mybatis操作的流程和原理是什么?
使用代理模式