Mybatis用法
作者:互联网
一、介绍
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
二、使用
1、导入依赖
#lombok用来自动生成get、set方法的,可以不用
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
#连接数据库
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
#mybatis的依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
2、java对象
import lombok.*;
/**
* @ClassName: Employee
* @Description:
* @Author: kele
* @Date: 2021/3/15 10:49
**/
//@Getter //只获取get方法
//@Setter //获取set方法
@Data //get和set方法
@AllArgsConstructor //全参构造器
@NoArgsConstructor //空参构造器
@ToString //tostring方法
public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
}
}
3、Mybatis配置文件
<?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-connect.properties"/>
<!--setting必须放在properties的下面,设置自动驼峰命名-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<environments default="development">
<!--environment 元素体中包含了事务管理和连接池的配置-->
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--配置映射关系-->
<mappers>
<!--可以写多个映射关系-->
<mapper resource="sql.xml"/>
<mapper resource="employeeMapper.xml"/>
</mappers>
</configuration>
4、声明接口
使用自定义的接口可以对输入的sql进行检查
package mapper;
import com.kele.mybatisdemo.Employee;
import java.util.List;
/**
* @ClassName: EmployeeMapper
* @Description:
* @Author: kele
* @Date: 2021/3/15 16:59
**/
/**
* 对传入的对象进行检查,并确定返回值类型
*/
public interface EmployeeMapper {
//mybatis提供了动态代理机制,可以实例化一个对象
//通过select获取employee对象
Employee getEmp(int id);
//根据id删除对象
void delEmp(int id);
//插入数据
void insertEmp(Employee employee);
//修改数据
void updateEmp(Employee employee);
//查询所有数据
List<Employee> selectAll();
}
5、设置sql文件
<?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相当于包名-->
<!--namespace采用接口的全类名的方式进行,namespace: 必须和接口的全类名一致-->
<mapper namespace="mapper.EmployeeMapper">
<!--id是语句的唯一标识,引用的话使用namespace + id-->
<!--resultType是返回值的类型,全类名的格式-->
<!--#{} 代表引用-->
<!--select标签代表当前是一个select语句
编写什么语句要使用对应的标签
id: 语句的唯一标识。如果要引用这条语句!
必须和绑定的方法名一致!
在配置文件中(mapper中)引用的话使用namespace + id
resultType: 查询语句返回值的类型
#{id}: #{}代表一个占位符,类比为一个?
如果当前语句中,只有一个占位符#{},{}中的内容可以随便写
如果当前语句中有多个占位符,此时必须要保证占位符的名称和要传入的属性名一致!否则可能传入参数失败
-->
<select id="getEmp" resultType="com.atguigu.mybatisdemo.Employee">
select * from tbl_employee where id = #{id}
</select>
<insert id="insertEmp">
insert into tbl_employee(last_name,gender,email) values (#{lastName},#{gender},#{email})
</insert>
<delete id="delEmp">
delete from tbl_employee where id=#{id}
</delete>
<update id="updateEmp">
update tbl_employee set last_name=#{lastName},email=#{email} where id=#{id}
</update>
<select id="selectAll" resultType="com.atguigu.mybatisdemo.Employee">
select * from tbl_employee
</select>
</mapper>
6、java程序
仿照官网: https://mybatis.org/mybatis-3/zh/getting-started.html
import com.atguigu.mybatisdemo.Employee;
import mapper.EmployeeMapper;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @ClassName: MybatisMappingTest
* @Description:
* @Author: kele
* @Date: 2021/3/15 15:56
*
* Mybaits省去了大量的模版代码,推崇 sql和java代码 解耦
* sql: 编写在一个xml文件中
* java代码: 在java文件中
* Dao层框架操作数据库的套路:
* ①获取连接
* jdbc: Connection
* DriverManger.getConnection
* mybatis: SqlSession
* SqlSessionFactory.openSession
* 从xml中构建SqlSessionFactory
*
* ②调用Dao提供的方法执行CRUD
*
**/
public class MybatisMappingTest {
SqlSessionFactory sqlSessionFactory;
@Before
public void before() throws IOException {
// 定义xml文件的路径
String resource = "mybatis-config.xml";
// 创建一个流读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//基于读取的配置文件创建sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
/**
* 通过id查询数据
*/
@Test
public void test1() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
/**
* 通过id查询数据
*/
Employee emp = mapper.getEmp(1);
System.out.println(emp);
} finally {
sqlSession.close();
}
}
/**
* 插入数据
*/
@Test
public void test2() {
//获取连接,并设置自动提交事务,除了select不需要提交事务,增删改需要提交事务操作
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
/**
* 添加数据
*/
Employee employee = new Employee(null, "lisi", "female", "lisi.qq.com");
mapper.insertEmp(employee);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
/**
* 删除数据
*/
@Test
public void test3() {
//获取连接,并设置自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
//删除id为1der数据
mapper.delEmp(1);
} finally {
sqlSession.close();
}
}
/**
* 修改数据
*/
@Test
public void test4() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee(2, "waixingren", "male", "waixingren.qq.com");
//修改employee的数据
mapper.updateEmp(employee);
} finally {
sqlSession.close();
}
}
/**
* 查询所有数据
*/
@Test
public void test5() {
//获取连接,并设置自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
List<Employee> employees = mapper.selectAll();
for (Employee employee : employees) {
System.out.println(employee);
}
} finally {
sqlSession.close();
}
}
}
标签:Employee,用法,employee,sqlSession,EmployeeMapper,Mybatis,import,id 来源: https://blog.csdn.net/qq_38705144/article/details/114846339