简介:
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录
用法步骤:
1、在pom.xml中导入mybatis依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency>
2、在mybatis-config.xml中进行mybatis的环境配置详细配置_MyBatis中文网
(注意:一定要在配置中进行mappers的注册)
<?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="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
3、根据数据库表编写实体类entity/pojo
4、创建一个mapper接口
@Mapper public interface UserMapper { User selectById(int id); User selectByName(String name); User selectByEmail(String email); int insertUser(User user); int insertStatus(int id,String status); int insertHeader(int id,String headerUrl); int updatePassword(int id,String password); }
5、创建对应mapper.xml映射文件在其中编写sql
(注意:namespace的参数要对应mapper接口)
<?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.nowcoder.community1.dao.UserMapper"> <sql id="selectFiles"> id, username, password, salt, email, type, status, activation_code, header_url, create_time </sql> <select id="selectById" resultType="User"> select <include refid="selectFiles"></include> from user where id = #{id} </select> </mapper>
6、编写测试类进行测试
public class MapperTests { @Autowired private UserMapper userMapper; @Test public void testSelectUser(){ User user = userMapper.selectById(101); System.out.println(user); } }