文章目录
- MyBatis:Day 04
- 框架
- 1. 依赖:pom.xml
- 2. 外部配置文件:db.properties
- 3. 核心配置文件:mybatis-config.xml
- 4. 实体类
- 5. 接口:xxxMapper.java
- 6. 实现类:xxxMapper.xml
- 7. 测试
MyBatis:Day 04
框架
1. 依赖:pom.xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2. 外部配置文件:db.properties
drive=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
username=xxx
password=xxx
3. 核心配置文件:mybatis-config.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<typeAlias type="com.Sun3285.pojo.xxx" alias="xxx"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${drive}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/Sun3285/dao/xxxMapper.xml"/>
</mappers>
</configuration>
4. 实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class 实体类 implements Serializable {
private int xxx;
private String xxx;
}
5. 接口:xxxMapper.java
public interface xxxMapper {
返回值类型 方法名(@Param("xxx") int xxx);
}
6. 实现类:xxxMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Sun3285.dao.xxxMapper">
<cache/>
<select id="方法名" parameterType="参数类型" resultType="返回值类型">
sql 语句
</select>
</mapper>
7. 测试
public class Tset01 {
@Test
public void test01() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(xxxMapper.class);
mapper.方法
xxxxxx
sqlSession.close();
}
}