mybatis概述
mybatis是一个优秀的基于java的持久层框架,内部封装了jdbc,并且通过xml或注解的方式将重复细节的配置,系统帮我们配置;几乎避免了所有JDBC代码和手动设置参数以及获取结果集,将接口和Java的JavaBean映射成数据库中的记录
搭建步骤
- 创建maven项目,导入依赖
<dependencies>
<!--MyBatis坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
- 创建JavaBean实体类,属性名和sql表列名一致,如果不一致得用resultMap封装。
public class User implements Serializable{
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
- 创建Mapper接口
public interface UserMapper{
//....各种待实现的增删改
List<User> queryAll();
}
- 创建Mapper映射文件,映射文件得跟接口连接上
<mapper namespace="com.xxf.dao.UserMapper">
<!--查询-->
<select id="queryAll" resultType="com.xxf.domain.User" >
<!--sql语句体-->
select * from user
</select>
<mapper>
- 创建核心配置文件SqlMapConfig.xml,映射文件中的别名在核心配置文件中取,而且最后一定得连接Mapper映射文件
<?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="引入外部配置文件" />
<typeAliases>
<!--别名配置-->
<typeAlias type="com.Demo1.domain.User"/>
</typeAliases>
<!--运行环境配置,default是默认环境,可改变-->
<environments default="prod">
<environment id="prod">
<!--事务管理器,mybatis默认是给JDBC,但后期spring整合一般用第三方事务管理,C3P0,Druid,光连接池-->
<transactionManager type="JDBC"/>
<!--POOLED开启连接池,UNPOOLED关闭连接池-->
<dataSource type="POOLED">
<!--数据库连接四大参数-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mvc?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--mappers映射器-->
<mappers>
<mapper resource="com/Demo1/dao/UserMapper.xml"/>
</mappers>
</configuration>
属性标签顺序