MyBatis系列:一、入门
MyBatis无需我介绍,本系列文章是纯干货,没有一点废话。
1.创建一个maven项目,引入mysql的驱动和mybatis的maven引用
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency>
2.编写mybatis配置文件放置于resources目录下,名字随意
<?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="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> </mappers> </configuration>
3.使用XML的方式创建SqlSessionFactory
//你的配置文件名称
String source = "mybatis-config.xml";
//加载配置文件 InputStream inputStream = Resources.getResourceAsStream(source); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
4.创建一个实体类完成一个基础的查询
创建JavaBean-Blog
public class Blog { private int id; private String name; private String remark; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return this.name+this.remark; } }
创建Blog对应的Mapper接口BlogMapper,接口内定义一个查询方法
public interface BlogMapper { public Blog selectBlog(int id); }
创建BlogMapper对应的XML映射文件BlogMapper
namespace要与接口名称一致
select节点的id要和接口中定义的方法名字一样
resultType设置要返回的实体类型
<?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="BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id=#{id} </select> </mapper>
然后我们需要在第一步设置的配置文件的mapper节点中加入我们新写的BlogMapper
<mappers> <mapper resource="BlogMapper.xml"></mapper> </mappers>
5.在数据库中创建一个和上面Blog一样的表并且设置id为自增,添加一条测试数据
在main方法中编写如下代码,会从数据库中读取出相应的数据并且输出到控制台
public static void main(String[] str) throws IOException { String source = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(source); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(1); System.out.println( blog); }
本文介绍了Mybatis从创建工厂到从数据库读取出数据的基础流程,接下来将会详细的介绍各个节点的作用。