1. public class User {
  2. private Integer id;
  3. private String userName;
  4. private String password;
  5. public Integer getId() {
  6. return id;
  7. }
  8. public void setId(Integer id) {
  9. this.id = id;
  10. }
  11. public String getUserName() {
  12. return userName;
  13. }
  14. public void setUserName(String userName) {
  15. this.userName = userName;
  16. }
  17. public String getPassword() {
  18. return password;
  19. }
  20. public void setPassword(String password) {
  21. this.password = password;
  22. }
  23. @Override
  24. public String toString() {
  25. return "User{" +
  26. "id=" + id +
  27. ", userName='" + userName + '\'' +
  28. ", password='" + password + '\'' +
  29. '}';
  30. }
  31. }
  1. import com.example.mybatis.domain.User;
  2. import com.example.mybatis.service.impl.UserServiceImpl;
  3. import org.apache.ibatis.io.Resources;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  7. import org.junit.After;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.io.InputStream;
  11. /**
  12. * @Description:
  13. * @Author: baxiang
  14. * @Date: 2021/8/31.
  15. */
  16. public class UserServiceTest {
  17. private InputStream is;
  18. private UserService userService;
  19. private SqlSession sqlSession;
  20. @Before
  21. public void setUp() throws Exception {
  22. String resource = "mybatis-config.xml";
  23. // 读取配置文件
  24. is = Resources.getResourceAsStream(resource);
  25. // 构建SqlSessionFactory
  26. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
  27. // 获取sqlSession
  28. sqlSession = sqlSessionFactory.openSession();
  29. this.userService = new UserServiceImpl(sqlSession);
  30. }
  31. @After
  32. public void tearDown() throws Exception {
  33. sqlSession.commit();
  34. sqlSession.close();
  35. is.close();
  36. }
  37. @Test
  38. public void queryUserById() {
  39. System.out.println(this.userService.queryUserById(1));
  40. }
  41. @Test
  42. public void insertUser() {
  43. User user = new User();
  44. user.setUserName("test");
  45. user.setPassword("123456");
  46. this.userService.insertUser(user);
  47. this.sqlSession.commit();
  48. }
  49. @Test
  50. public void updateUser() {
  51. User user = new User();
  52. user.setId(1);
  53. user.setUserName("Test1");
  54. user.setPassword("654321");
  55. this.userService.updateUser(user);
  56. this.sqlSession.commit();
  57. }
  58. @Test
  59. public void deleteUserById() {
  60. this.userService.deleteUserById(1);
  61. this.sqlSession.commit();
  62. }
  63. }

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <!-- 根标签 -->
  6. <configuration>
  7. <!-- 属性 -->
  8. <properties>
  9. <property name="driver" value="com.mysql.jdbc.Driver"/>
  10. <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useSSL=false&amp;characterEncoding=utf-8&amp;allowMultiQueries=true"/>
  11. <property name="username" value="root"/>
  12. <property name="password" value="123456"/>
  13. </properties>
  14. <!-- 全局设置 -->
  15. <settings>
  16. <!-- 使用jdbc的getGeneratedKeys 获取数据库自增主键值 -->
  17. <setting name="useGeneratedKeys" value="true"/>
  18. <!-- 开启驼峰命名转换 -->
  19. <setting name="mapUnderscoreToCamelCase" value="true"/>
  20. </settings>
  21. <!-- 环境,可以配置多个,default:指定采用哪个环境 -->
  22. <environments default="dev">
  23. <!-- id:唯一标识 -->
  24. <environment id="dev">
  25. <!-- 事务管理器,JDBC类型的事务管理器 -->
  26. <transactionManager type="JDBC" />
  27. <!-- 数据源,池类型的数据源 -->
  28. <dataSource type="POOLED">
  29. <property name="driver" value="${driver}" /> <!-- 配置了properties,所以可以直接引用 -->
  30. <property name="url" value="${url}" />
  31. <property name="username" value="${username}" />
  32. <property name="password" value="${password}" />
  33. </dataSource>
  34. </environment>
  35. </environments>
  36. <mappers>
  37. <mapper resource="mappers/UserMapper.xml" />
  38. </mappers>
  39. </configuration>

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:命名空间,保证命名空间唯一 -->
<mapper namespace="UserMapper">

    <!--获取用户-->
    <select id="selectUser" resultType="com.example.mybatis.domain.User">
        SELECT
            id ,
            user_name ,
            password
        FROM
            user
        WHERE id = #{id};
    </select>

    <!--插入数据-->
    <insert id="insertUser" parameterType="com.example.mybatis.domain.User">
        INSERT INTO user (
            user_name,
            password
        )
        VALUES
            (
                #{userName},
                #{password}
            );
    </insert>

    <update id="updateUser" parameterType="com.example.mybatis.domain.User">
        UPDATE user
        <trim prefix="set" suffixOverrides=",">
            <if test="userName!=null">user_name = #{userName},</if>
            <if test="password!=null">password = #{password},</if>
        </trim>
        WHERE
        (id = #{id});
    </update>

    <delete id="deleteUser">
        DELETE FROM user WHERE id=#{id}
    </delete>
</mapper>

接口类

public interface UserService {
    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    User selectUser(Integer id);



    /**
     * 新增用户
     *
     * @param user
     */
    void insertUser(User user);

    /**
     * 更新用户信息
     *
     * @param user
     */
    void updateUser(User user);

    /**
     * 根据id删除用户信息
     *
     * @param id
     */
    void deleteUser(Integer id);
}

UserServiceImpl

import com.example.mybatis.domain.User;
import com.example.mybatis.service.UserService;
import org.apache.ibatis.session.SqlSession;



public class UserServiceImpl implements UserService {

    private SqlSession sqlSession;

    public UserServiceImpl(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public User selectUser(Integer id) {
        return this.sqlSession.selectOne("UserMapper.selectUser", id);
    }

    @Override
    public void insertUser(User user) {
        this.sqlSession.insert("UserMapper.insertUser", user);
    }

    @Override
    public void updateUser(User user) {
        this.sqlSession.update("UserMapper.updateUser", user);
    }

    @Override
    public void deleteUser(Integer id) {
        this.sqlSession.delete("UserMapper.deleteUser", id);
    }
}

动态代理Mapper

  • 接口->实现类->mapper.xml
  • 2、实现类中,使用mybatis的方式非常类似
  • 3、xml中的sql statement 硬编码到java代码中。

思考:能否只写接口,不写实现类。只编写接口和Mapper.xml即可?
因为在dao(mapper)的实现类中对sqlsession的使用方式很类似。因此mybatis提供了接口的动态代理。

import com.example.mybatis.domain.User;



public interface UserMapper {
    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    User selectUser(Integer id);


    /**
     * 新增用户
     *
     * @param user
     */
    void insertUser(User user);

    /**
     * 更新用户信息
     *
     * @param user
     */
    void updateUser(User user);

    /**
     * 根据id删除用户信息
     *
     * @param id
     */
    void deleteUser(Integer id);
}

,在UserMapper.xml中配置接口的全路径
mapper.xml namespace
如果希望使用mybatis通过的动态代理的接口,就需要namespace中的值,和需要对应的Mapper(dao)接口的全路径一致。Mapper中Namespace的定义本身是没有限制的,只要不重复即可,但如果使用Mybatis的DAO接口动态代理,则namespace必须为DAO接口的全路径,例如:com.example.mybatis.mapper.UserMapper
图片.png
// 1. 映射文件的命名空间(namespace)必须是mapper接口的全路径
// 2. 映射文件的statement的id必须和mapper接口的方法名保持一致
// 3. Statement的resultType必须和mapper接口方法的返回类型一致
// 4. statement的parameterType必须和mapper接口方法的参数类型一致(不一定)