刚上手,感觉步骤很多记不住,简单记录一下创建Mybatis的步骤,方便以后回顾
- 创建一个Maven模块
- pom.xml中导入依赖坐标(logback日志还需要导入对应xml到resources)
<!--Mybatis依赖--> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- junit单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <!--非必要 日志信息可以输出到控制台--> <!-- 添加slf4j日志api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.20</version> </dependency> <!-- 添加logback-classic依赖 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- 添加logback-core依赖 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency> </dependencies>
如果报java: 错误: 不支持发行版本 XX
<properties> <maven.compiler.source>16</maven.compiler.source> <maven.compiler.target>16</maven.compiler.target> </properties>
mybatis-config.xml中编写Mybatis核心配置文件(数据库连接信息)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--起别名,可忽略包和大小写--> <typeAliases> <package name="com.work.pojo"/> </typeAliases> <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/mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!--加载User类sql映射文件--> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
UserMapper.xml中编写sql映射文件(统一管理sql语句)
<?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.work.mapper.UserMapper"> <!-- id:唯一标识,不能重复 resultType:定义你sql语句操作的实体类 --> <select id="selectAll" resultType="user"> select * from tb_user; </select> </mapper>
编码(mapper接口和sql映射文件在同一目录下)
public static void main(String[] args) throws IOException { //1.加载Mybatis核心配置文件,获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3.执行sql UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.selectAll(); System.out.println(users); //4.释放资源 sqlSession.close(); }
public interface UserMapper { List<User> selectAll(); }