MyBatis 是一款优秀的半自动的ORM持久层框架,它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old JavaObjects,普通老式 Java 对象)为数据库中的记录。
持久层:可以立即保存在磁盘上,在这里可以理解为与数据库相关操作。
创建测试的数据库 2.创建一个Java项目并导入mybatis框架的jar包 在项目中创建一个lib文件夹放入mybatis框架的jar包,并导入项目中。 #判断存在即删除数据库 drop database if exists mydb; #创建数据库 create database mydb; #使用数据库 use mydb; #创建表 create table t_user ( uid int primary key auto_increment, username varchar(20), password varchar(20), phone varchar(11), address varchar(50) ); insert into t_user(username,password,phone,address) values('张 三','666','18965423548','南阳'); insert into t_user(username,password,phone,address) values('李 四','333','18754263548','许昌'); insert into t_user(username,password,phone,address) values('小 美','123','18565234759','信阳'); select * from t_user
创建一个Java项目并导入mybatis框架的jar包
在项目中创建一个lib文件夹放入mybatis框架的jar包,并导入项目中。
![](https://i-blog.csdnimg.cn/blog_migrate/9ca66429818498f62a43cb61c5b68456.png)
3.创建跟表对应的实体类
在src中创建com.chen.bean包,然后创建User实体类。
package com.ghx.bean;
public class User {
private Integer uid;
private String username;
private String password;
private String phone;
private String address;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}
4.创建针对表操作的接口类
在src中创建com.chen.dao包,然后创建UserDao的接口,然后在接口中定义针对数据库的增删 改查等操作。
package com.ghx.dao;
import com.ghx.bean.User;
import java.util.List;
public interface UserDao {
List<User> selectAll();
int add(User user);
int delete(int uid);
int reviseEmp(Emp emp);
User selectByuid(int uid);
List<Emp> select(String keyword);
}
在接口的包中创建对应的mapper映射配置文件
在dao接口的同目录下创建跟接口名字一样的配置文件。
<?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">
<!--namespace是映射的dao接口-->
<mapper namespace="com.ghx.dao.UserDao">
<select id="selectAll" resultType="com.ghx.bean.User">
select *from t_user;
</select>
<insert id="add" parameterType="com.ghx.bean.User">
insert into t_user(username,password,phone,address) values(#{username}, #{password}, #{phone} ,#{address});
</insert>
<delete id="delete" parameterType="int">
delete from t_user where uid=#{uid}
</delete>
<select id="selectByuid" parameterType="int" resultType="com.ghx.bean.User">
select * from t_user where uid=#{uid}
</select>
<update id="reviseEmp" parameterType="com.ghx.bean.Emp">
update emp set ename=#{ename}, dept=#{dept}, job=#{job},sal=#{sal},phone=#{phone},address=#{address} where eid=#{eid};
</update>
<select id="select" parameterType="String" resultType="com.ghx.bean.Emp" >
select * from emp where ename like concat('%',#{keyword},'%')
</select>
</mapper>
6.在src目录中创建mybatis框架的核心配置文件
在src中创建一个文件,命名为SqlMapConfig.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>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="pooled">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
<environment id="oracle">
<transactionManager type=""></transactionManager>
<dataSource type=""></dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.ghx.dao.UserDao"></mapper>
</mappers>
</configuration>
在测试类中进行测试
使用mybatis框架需要按照框架的步骤进行,后期会讲解原理。。。。。。。。
package com.ghx.test;
import com.ghx.bean.User;
import com.ghx.dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserTest {
InputStream stream = null;
SqlSessionFactoryBuilder builder = null;
SqlSessionFactory factory = null;
SqlSession sqlSession = null;
UserDao userDao = null;
@Before
public void init() throws IOException {
stream = Resources.getResourceAsStream("mybatis.xml");
builder = new SqlSessionFactoryBuilder();
factory = builder.build(stream);
sqlSession = factory.openSession();
userDao = sqlSession.getMapper(UserDao.class);
}
@Test
public void selectAll() {
List<User> userList = userDao.selectAll();
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void addAll() {
User user = new User();
user.setUsername("胡有理");
user.setPassword("520");
user.setPhone("198554122");
user.setAddress("开封市通许县");
int add = userDao.add(user);
if (add > 0) {
System.out.println("add success");
}
}
@Test
public void deleteAll() {
int d = userDao.delete(21);
if(d>0){
System.out.println("delete success");
}
}
@Test
public void selectByuid() {
User userlist = userDao.selectByuid(1);
System.out.println(userlist);
}
@Test
public void update() {
Emp oldEmp = empDao.selectById(2);
System.out.println("修改前的" + oldEmp);
oldEmp.setEname("李长意");
oldEmp.setAddress("河南南阳");
empDao.reviseEmp(oldEmp);
Emp newemp = empDao.selectById(2);
System.out.println("修改后的" + newemp);
}
@Test
public void mohu(){
List<Emp> mohulist= empDao.select("长");
for (Emp emp : mohulist) {
System.out.println(emp);
}
}
@After
public void distory() throws IOException {
sqlSession.commit();
sqlSession.close();
stream.close();
}
}
运行结果如下:
User{uid=1, username='张三', password='666', phone='18965423548', address='南阳'}
User{uid=2, username='李四', password='333', phone='18754263548', address='许昌'}
User{uid=3, username='小美', password='123', phone='18565234759', address='信阳'}
User{uid=8, username='草莓熊', password='39362528', phone='1582694596', address='驻马店 新蔡县'}
add success
![](https://i-blog.csdnimg.cn/blog_migrate/1f6d8712ffb56d7df8402f3799b9cae8.png)
delete success
![](https://i-blog.csdnimg.cn/blog_migrate/08b0c1b6cd4f9ba1786aa90ceebd44db.png)
![](https://i-blog.csdnimg.cn/blog_migrate/6d071b628461c7e143ce6ea636058b6e.png)
Emp{eid=2, ename='李长意', dept='测试部', job='测试经
理', sal=9800.0, phone='13658942168', address='河南南阳'}
Emp{eid=3, ename='王长林', dept='研发部', job='开发工程
师', sal=8800.0, phone='13954865721', address='南阳'}
Emp{eid=9, ename='王长林', dept='研发部', job='开发工程
师', sal=8800.0, phone='13954865721', address='南阳'}