一、数据库建表
二、entity目录下创建user实体类
三、dao目录下创建userMapper映射接口
@Mapper public interface UserMapper { User selectById(int id); User selectByName(String username); User selectByEmail(String email); int insertUser(User user); int updateStatus(int id, int status); int updateHeader(int id, String headerUrl); int updatePassword(int id, String password); }
四、创建user-mapper映射xml文件
xml文件的格式可以在mybatis官网找到,直接复制进文件就行。
<?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"> <!-- namespace里面写和哪个mapper对应--> <sql id="insertFields"> username, password, salt, email, type, status, activation_code, header_url, create_time </sql> <sql id="selectFields"> id, username, password, salt, email, type, status, activation_code, header_url, create_time </sql> <select id="selectById" resultType="User"> select <include refid="selectFields"></include> from user where id = #{id} </select> <select id="selectByName" resultType="User"> select <include refid="selectFields"></include> from user where username = #{username} </select> <select id="selectByEmail" resultType="User"> select <include refid="selectFields"></include> from user where email = #{email} </select> <insert id="insertUser" parameterType="User" keyProperty="id"> insert into user (<include refid="insertFields"></include>) values(#{username}, #{password}, #{salt}, #{email}, #{type}, #{status}, #{activationCode}, #{headerUrl}, #{createTime}) </insert> <update id="updateStatus"> update user set status = #{status} where id = #{id} </update> <update id="updateHeader"> update user set header_url = #{headerUrl} where id = #{id} </update> <update id="updatePassword"> update user set password = #{password} where id = #{id} </update> </mapper>
五、测试从数据库中查找
@Test public void testSelectUser() { User user = userMapper.selectById(101); System.out.println(user); user = userMapper.selectByName("liubei"); System.out.println(user); user = userMapper.selectByEmail("nowcoder101@sina.com"); System.out.println(user); }