1、新建一个maven工程,这里使用idea创建:
项目目录结构如下:
pom.xml文件中加入mybatis和mysql驱动依赖,如下:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> </dependencies>
数据库表:
新建student实体类:
public class Student { private Integer id; private String name; private Integer age; //set get 略 }
新建studentMapper接口:
public interface StudentMapper { /** * 根据id查询 * @param id * @return */ Student queryOne(@Param("id") Integer id); }
参考mybatis官网(https://mybatis.org/mybatis-3/zh/getting-started.html),这里选用的是xml的方式(也可以选择注解的方式,但一般复杂点的sql建议使用xml的方式)
新建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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=GMT&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/studentMapper.xml"/> <!-- 指定mpper.xml文件位置--> </mappers> </configuration>
新建测试类:
public class Test { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; //读取配置文件,java底层代码将配置文件以流的形式返回 InputStream inputStream = Resources.getResourceAsStream(resource); //使用dom解析xml并创建sqlSessionFactory SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream); //创建sqlsession SqlSession sqlSession = build.openSession(); //这里使用的是接口的方式查询 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); System.out.println(mapper.toString()); //调用查询方法 Student student = mapper.queryOne(1); System.out.println(student.getName()); } }
输出结果:jack