一、截图
-
1.源码结构图
-
2.resources截图
-
3.将resources目标标记为资源根目录
-
4.数据库表截图
-
5.程序运行截图
二、代码示例
- 1.jdbc.properties配置
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8
username=root
password=root
- 2.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>
<properties resource="jdbc.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<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>
<mapper resource="org/apache/ibatis/learning/mapper/CarMapper.xml"></mapper>
</mappers>
</configuration>
- 3.CarMapping.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">
<mapper namespace="org.apache.ibatis.learning.mapper.CarMapper">
<select id="selectCar" resultType="org.apache.ibatis.learning.mapper.Car">
select * from car where id = #{id}
</select>
</mapper>
- 4.CarMapper.java
package org.apache.ibatis.learning.mapper;
public interface CarMapper {
Car selectOne(int id);
}
- 5.Car.java
package org.apache.ibatis.learning.mapper;
import lombok.Data;
/**
* @Author wangyouhui
* @Description 实例类
**/
@Data
public class Car {
private String id;
private String name;
}
- 6.创建表语句
CREATE TABLE `car` (
`id` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
- 7.MybatisMain.java
package org.apache.ibatis.learning;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.learning.mapper.Car;
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;
/**
* @Author wangyouhui
* @Description 测试方法
**/
public class MybatisMain {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Car car = (Car)sqlSession.selectOne("org.apache.ibatis.learning.mapper.CarMapper.selectCar", 1);
System.out.println(car.getName());
}
}
三、错误说明
- 1.如果报mysql的驱动类Driver找不到,可以把pom.xml中的mysql-connector-java的scope注释掉
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
<!-- <scope>test</scope>-->
</dependency>