MyBatis是支持客制化SQL、存储过程以及的高级映射的持久层框架,MyBatis避免了几乎所有JDBC代码和手动设置参数以及获取结果集。
MyBatis的操作步骤
1.导入相应的jar
2.MyBatis的全局配置文件(mybatis-config.xml)和db.properties
mybatis-config.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>
<!-- 这个就是根据db.properties取里面的值--!>
<properties resource="db.properties"></properties>
<environments default="development">
<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>
<!-- 这个映射地址的值xml实现的文件--!>
<mapper resource="com/etc/example/BlogMapper.xml"/>
</mappers>
</configuration>
db.properties
这个文件是
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://192.168.12.8:3307/mybatisdb?serverTimezone=Asia/Shanghai
username=root
password=root
3.创建实体类,dao接口等
BlogMapper.xml相当于接口的实现。
测试类Mybatis01.java为:
package com.etc.test;
public class Mybatis01 {
public static void main(String[] args) throws IOException {
//mybatis全局配置文件
String resource = "com/etc/conf/mybatis-config.xml";
//从配置文件里得到输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
//从输入流中得到SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//得到session(核心对象)
SqlSession session = sqlSessionFactory.openSession();
//从blogmapper反射得到方法。
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(1);
System.out.println(blog);
}
}
BlogMapper.java接口:
package com.etc.example;
import com.etc.entity.Blog;
public interface BlogMapper {
public Blog selectBlog(int id);
}
BlogMapper.xml:
需注意的是namespace是需要实现的接口
resultType需要到具体包的地址
select :id是在接口中要实现的方法名称
语句里的#{id}代表着传的参数信息。名字一样
<?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">
<mapper namespace="com.etc.example.BlogMapper">
<select id="selectBlog" resultType="com.etc.entity.Blog">
select * from Blog where id = #{id}
</select