MyBatis入门篇-配置IDEA版本
MyBatis概述
1.mybatis是什么?有什么特点?
它是一款半自动的ORM持久层框架,具有较高的SQL灵活性,支持高级映射(一对一,一对多),动态SQL,延迟加载和缓存等特性,但它的数据库无关性较低
2.为什么mybatis是半自动的ORM框架?
用mybatis进行开发,需要手动编写SQL语句。而全自动的ORM框架,如hibernate,则不需要编写SQL语句。用hibernate开发,只需要定义好ORM映射关系,就可以直接进行CRUD操作了。由于mybatis需要手写SQL语句,所以它有较高的灵活性,可以根据需要,自由地对SQL进行定制,也因为要手写SQL,当要切换数据库时,SQL语句可能就要重写,因为不同的数据库有不同的方言(Dialect),所以mybatis的数据库无关性低。虽然mybatis需要手写SQL,但相比JDBC,它提供了输入映射和输出映射,可以很方便地进行SQL参数设置,以及结果集封装。并且还提供了关联查询和动态SQL等功能,极大地提升了开发的效率。并且它的学习成本也比hibernate低很多
————————————————————————————————————————————————
mybatis安装与配置
1.要使用 MyBatis, 只需将 mybatis-x.x.x.jar MyBatis下载文件置于类路径(classpath)中即可。
2.如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:
导入相应的jar包
<?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>com.dahua</groupId>
<artifactId>MyBatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- mybatis的jar-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- jdbc-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
<!-- 插件-->
<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>
</project>
3.本地创建数据库
新建数据库(mybatis)和表(student)字段
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;
INSERT INTO `student` VALUES (1, '张三', 18, '男');
INSERT INTO `student` VALUES (2, '李四', 20, '男');
INSERT INTO `student` VALUES (3, '小红', 20, '女');
4.编写实体类(Student)
重写GetSet方法,重写toString方法,将对象中各个属性值按字符串的方式输出出来
package com.dahua.entity;
public class Student {
private Integer id;//id
private String name;//名字
private Integer age;//年龄
private String gender;//性别
public Student() {
}
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 + '\'' +
'}';
}
}
5.创建实体类接口,和配置Mapper.xml文件,名字这里修改为了StudentDao.xml,名字不固定 然后编写mapper映射文件(编写SQL)
package com.dahua.Dao;
import com.dahua.entity.Student;
import java.util.List;
public interface StudentDao {
//查询所有学生信息
List<Student> selectStudents();
}
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--唯一字符串-->
<!--在mybatis中,映射文件中的namespace是用于绑定Dao接口的,即面向接口编程-->
<!--当你的namespace绑定接口后,你可以不用写接口实现类,mybatis会通过该绑定自动帮你找到对应要执行的SQL语句-->
<mapper namespace="com.dahua.Dao.StudentDao">
<!-- SQL语句-->
<!-- resultType 返回值类型 -->
<!--(对应着我们的实体类对象(Student)中的实体) -->
<select id="selectStudents" resultType="com.dahua.entity.Student">
select id,name,age,gender from student
</select>
</mapper>
6.在资源文件夹,创建mubatis.xml文件
XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理(TransactionManager)
<?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>
<!-- 默认-->
<!--配置mysql的环境,可以配置多个数据库-->
<environments default="development">
<environment id="development">
<!--配置事务的类型-->
<transactionManager type="JDBC"/>
<!--配置连接数据库的4个基本信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件地址,地址是斜杠-->
<!--通过mapper接口加载单个映射文件-->
<!--映射文件名保持一致-->
<mappers>
<mapper resource="com/dahua/Dao/StudentDao.xml"/>
</mappers>
</configuration>
7.创建StudentDao接口的实现类
package com.dahua.StudentDaoimpl;
import com.dahua.Dao.StudentDao;
import com.dahua.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class StudentDaoimpl implements StudentDao {
@Override
public List<Student> selectStudents() {
// 你要读取配置文件
String mybatis = "mybatis.xml";
// 通过流的方式读取配置文件
InputStream resourceAsStream = null;
List<Student> students = null;
SqlSession sqlSession = null;
try {
resourceAsStream = Resources.getResourceAsStream(mybatis);
//创建出SqlSessionFactory 工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取sqlSession的实例
sqlSession = sqlSessionFactory.openSession();
String sql = "com.dahua.Dao.StudentDao.selectStudents";
// 执行SQL
students = sqlSession.selectList(sql);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sqlSession != null){
sqlSession.close();
}
}
return students;//返回集合
}
}
8.创建测试类
Test,
package com.dahua.controller;
import com.dahua.Dao.StudentDao;
import com.dahua.StudentDaoimpl.StudentDaoimpl;
import com.dahua.entity.Student;
import java.util.List;
public class Test {
//接口实例化
static StudentDao studentDao = new StudentDaoimpl();
public static void main(String[] args) {
List<Student> students = studentDao.selectStudents();
for (Student stu:students) {
System.out.println(stu);
}
}
}