开源项目 mapper
使用教程
项目介绍
mapper
是一个开源的 MyBatis 通用 Mapper 项目,旨在简化 MyBatis 的使用。通过提供一系列通用的 Mapper 接口和方法,mapper
使得开发者能够更快速地进行数据库操作,减少样板代码的编写。
项目快速启动
环境准备
- Java 开发环境:确保你已经安装了 JDK 8 或更高版本。
- Maven:确保你已经安装了 Maven 构建工具。
- 数据库:确保你有一个可用的数据库,并已配置好相应的数据库连接。
快速启动步骤
-
克隆项目:
git clone https://github.com/devfeel/mapper.git cd mapper
-
添加依赖: 在你的
pom.xml
文件中添加以下依赖:<dependency> <groupId>com.github.abel533</groupId> <artifactId>mapper</artifactId> <version>最新版本</version> </dependency>
-
配置 MyBatis: 在
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/yourdb"/> <property name="username" value="yourusername"/> <property name="password" value="yourpassword"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/yourpackage/mapper/YourMapper.xml"/> </mappers> </configuration>
-
创建实体类和 Mapper 接口: 创建一个简单的实体类
User.java
:public class User { private Integer id; private String name; // 省略 getter 和 setter 方法 }
创建一个 Mapper 接口
UserMapper.java
:import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { }
-
编写 Mapper XML 文件: 创建
UserMapper.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="com.yourpackage.mapper.UserMapper"> <select id="selectAll" resultType="com.yourpackage.entity.User"> SELECT * FROM user </select> </mapper>
-
测试代码: 编写一个简单的测试类
UserMapperTest.java
:import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; import java.util.List; public class UserMapperTest { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userMapper = session.getMapper