目录
一、Mybatis的概念
MyBatis是一个优秀的基于Java的持久层框架,支持自定义SQL,存储过程和高级映射。
MyBatis对原有JDBC操作进行了封装,几乎消除了所有的JDBC代码。
MyBatis可以使用简单的XML或Annotation来配置执行SQL,并自动完成ORM操作,将执行结果返回。
二、Mybatis环境搭建
在 pom.xml中引入MyBatis核心依赖
<?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.xx</groupId>
<artifactId>hello</artifactId>
<version>1.0-SNAPSHOT</version>
<!--依赖-->
<dependencies>
<!--MyBatis核心依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--MySql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
创建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">
<!--MyBatis配置-->
<configuration>
<!--JDBC环境配置、选中默认环境-->
<environments default="MySqlDB">
<!--MySql数据库环境配置-->
<environment id="MySqlDB">
<!--事务管理-->
<transactionManager type="JDBC"/>
<!--连接池-->
<dataSource type="org.apache.ibatis.datasource.pooled.PooledDataSourceFactory">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/x?characterEncoding=utf-8"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="xxxMapper.xml"/>
</mappers>
</configuration>
三、MyBatis开发步骤【重点】
1. 建表
2.定义实体类
/**
* author:土豆糯米
* datetime:2023/03/22/11:37
*/
public class Student {
private Integer id;
private String name;
private Integer age;
private String 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;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
public Student(Integer id, String name, Integer age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
}
3. 定义DAO接口
import java.util.List;
/**
* author:土豆糯米
* datetime:2023/03/22/15:36
*/
public interface StudentDao {
List<Student> getAll();
Student getOne(Integer id);
Integer add(Student student);
Integer delete(Integer id);
Integer update(Student student);
}
4.编写Mapper.xml
<?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 = 所需实现的接口全限定名-->
<mapper namespace="StudentDao">
<!--id = 所需重写的接口抽象方法,resultType = 查询后所需返回的对象类型-->
<select id="getAll" resultType="Student">
select * from student
</select>
<select id="getOne" resultType="Student">
select * from student where id = #{id}
</select>
<insert id="add" parameterType="Student">
insert into student values (#{id},#{name},#{age},#{gender})
</insert>
<update id="update" parameterType="Student">
update student set name = #{name}, age=#{age}, gender = #{gender} where id = #{id}
</update>
<delete id="delete" >
delete from student where id = #{id}
</delete>
</mapper>
5.注册Mapper
<!--Mapper文件注册位置-->
<mappers>
<!--注册Mapper文件-->
<mapper resource="StudentDaoMapper.xml"/>
</mappers>
6. 测试
public class StudentDemoTest {
SqlSession sqlSession = null;
@Before
public void before() throws IOException {
String config = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
}
//仅列出getAll()
@Test
public void getAll(){
//通过连接对象获得接口实现类对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> all = studentDao.getAll();
System.out.println(all);
}
四、一些细节补充
1. properties配置文件
在mybatis-config.xml的核心配置中,如果存在需要频繁改动的数据内容,可以提取到properties中。
在java.resources目录下写database.properties文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncpding=utf8
jdbc.username=root
jdbc.password=123456
2. 类型别名
为实体类定义别名,提高书写效率。
<?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 ... />
<!--定义别名-->
<typeAliases>
<!--定义某一个类的别名-->
<typeAlias type="com.xxx.entity.Student" alias="Student" />
<!--给某一个包下的所有类起别名将原类名作为别名-->
<package name="com.xxx.entity" />
</typeAliases>
...
</configuration>
五、ORM(Object Relational Mapping)映射
1.问题:MyBatis的自动ORM失效
MyBatis只能自动维护:数据库表的列名 与 实体类中属性名 相同时的一一对应关系,当两者不同时,则不能自动ORM。
2.方案1
在SQL中使用 as 为查询字段添加列别名,以匹配属性名。
3.方案2 结果映射
通过resultMap标签中:< resultMap id=“” type=“” >的映射,匹配数据库表的列名与实体类的属性名。
<mapper namespace="com.xxx.dao.StudentDao">
<!--定义resultMap标签-->
<resultMap id="ResultMap" type="Student">
<!--关联主键与列名-->
<id property="id" column="uid" />
<!--关联类属性与表列名-->
<result property="username" column="uname" />
<result property="password" column="upwd" />
</resultMap>
<!--使用resultMap作为ORM映射依据-->
<select id="selectAll" resultMap="ResultMap">
SELECT uid , uname , upwd FROM student
</select>
</mapper>