妈妈再也不用担心我如何入门MyBatis了!
程序员文章站
2022-05-15 13:14:12
...
一丶 MyBatis的概念
-
MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
二丶 MyBatis的作用
帮助程序员将数据存入到数据库中
1、可以把数据库表中的一行数据映射为一个java对象
2、对数据库进行增删改查
方便
- 传统的JDBC代码太复杂了,简化,框架,自动化
- 不用MyBatis也可以,技术没有高低之分
- 优点:
- 简单易学
- 灵活
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
三丶 MyBatis的使用
第一个Mybatis程序
思想:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试-->使用
1、通过maven引入需要的jar包
<!--导入依赖-->
<dependencies>
<!--mysqlq驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2、新建数据库和表字段
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`gender` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '张三', '18', '男');
INSERT INTO `student` VALUES ('2', '李四', '20', '男');
INSERT INTO `student` VALUES ('3', '小红', '30', '女');
INSERT INTO `student` VALUES ('4', '李红', '28', '女');
3、新建实体类
package com.dh.entity;
public class Student {
private Integer id;
private String name;
private Integer age;
private String gender;
public Student() {
}
public Student(Integer id, String name, Integer age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
4、编写StudentDao
package com.dh.dao;
import com.dh.entity.Student;
import java.util.List;
public interface StudentDao {
List<Student> selectStudents();
}
5、编写StudentDaoMapper.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--唯一字符串-->
<mapper namespace="com.dh.dao.StudentDao">
<!-- resultType 返回值类型-->
<select id="selectStudents" resultType="com.dh.entity.Student">
select * from student
</select>
</mapper>
6、在resources资源目录下新建mybatis.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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_login1"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/dh/dao/StudentDaoMapper.xml"/>
</mappers>
</configuration>
7、在pom.xml添加资源插件
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
8、测试
package com.dh;
import static org.junit.Assert.assertTrue;
import com.dh.entity.Student;
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;
/**
* Unit test for simple App.
*/
public class AppTest {
//定义 SqlSession
SqlSession session =null;
@Before
public void init() throws IOException {
//mybatis全局配置文件
String resource = "mybatis.xml";
//加载 mybatis 全局配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//根据 sqlSessionFactory 产生 session
session = sessionFactory.openSession();
}
@Test
public void testSelectStudentAll(){
String statement = "com.dh.dao.StudentDao.selectStudents";
List<Student> students = session.selectList(statement);
for(Student student : students){
System.out.println(student);
}
session.close();
}
}
9、使用
// 记载配置文件
InputStream in = Resources.getResourceAsStream(config);
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession
SqlSession session = factory.openSession();
// 获取数据
List<Stundet> stus = session.selectList("com.bigdata.dao.StudentDao.selectStudents");
// 释放资源
session.close();
结果应该是:
Student{id=1, name='张三', age=18, gender='男'}
Student{id=2, name='李四', age=20, gender='男'}
Student{id=3, name='小红', age=30, gender='女'}
Student{id=4, name='李红', age=28, gender='女'}
其他配置
支持中文
jdbc:mysql://localhost:3306/db_login1?useUnicode=true&characterEncoding=utf8
日志功能
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
自动提交事务
openSession(**true**);
配置文件读取数据库信息
<properties resource="jdbc.properties" />
${jdbc.driver}