MyBatis的实际应用案例分析
MyBatis是一个优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射。以下是一个简单的MyBatis使用案例,展示了如何配置MyBatis和使用它来查询数据库。
- 添加MyBatis依赖到项目的pom.xml文件中:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
- 创建一个MyBatis配置文件mybatis-config.xml:
<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/mydatabase"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/myapp/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- 创建一个映射器接口UserMapper.java:
package org.myapp.mapper;
public interface UserMapper {
User selectUserById(int id);
}
- 创建映射器接口的XML文件UserMapper.xml:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.myapp.mapper.UserMapper">
<select id="selectUserById" resultType="org.myapp.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 创建一个实体类User.java:
package org.myapp.model;
public class User {
private int id;
private String name;
// getters and setters
}
- 使用MyBatis来查询数据库:
String resource = "org/myapp/mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper
评论已关闭