快盘下载:好资源、好软件、快快下载吧!

快盘排行|快盘最新

当前位置:首页软件教程电脑软件教程 → Mybatis急速入门(上篇)

Mybatis急速入门(上篇)

时间:2022-09-26 14:05:06人气:作者:快盘下载我要评论

一、创建maven工程

Mybatis急速入门(上篇)

二、创建数据库mybatis;字符编码utfmb4

DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user (
id char(32) NOT NULL,
user_name varchar(32) DEFAULT NULL,
password varchar(32) DEFAULT NULL,
name varchar(32) DEFAULT NULL,
age int(10) DEFAULT NULL,
sex int(2) DEFAULT NULL,
birthday date DEFAULT NULL,
created datetime DEFAULT NULL,
updated datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO mybatis.tb_user ( user_name, password, name, age, sex, birthday, created, updated) VALUES ( ;zpc;, ;123456;, ;鹏程;, ;22;, ;1;, ;1990-09-02;, sysdate(), sysdate());
INSERT INTO mybatis.tb_user ( user_name, password, name, age, sex, birthday, created, updated) VALUES ( ;hj;, ;123456;, ;静静;, 22, 1, ;1993-09-05;, sysdate(), sysdate());

三、pom依赖

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>

3.1全局依赖文件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>
    <properties>
        <property name=;driver; value=;com.mysql.jdbc.Driver;/>
        <property name=;url; value=;jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true;/>
        <property name=;username; value=;root;/>
        <property name=;password; value=;root;/>
    </properties>

    <!-- 环境;可以配置多个;default;指定采用哪个环境 -->
    <environments default=;test;>
        <!-- id;唯一标识 -->
        <environment id=;test;>
            <!-- 事务管理器;JDBC类型的事务管理器 -->
            <transactionManager type=;JDBC; />
            <!-- 数据源;池类型的数据源 -->
            <dataSource type=;POOLED;>
                <property name=;driver; value=;com.mysql.jdbc.Driver; />
                <property name=;url; value=;jdbc:mysql://127.0.0.1:3306/mybatis; />
                <property name=;username; value=;root; />
                <property name=;password; value=;root; />
            </dataSource>
        </environment>
        <environment id=;development;>
            <!-- 事务管理器;JDBC类型的事务管理器 -->
            <transactionManager type=;JDBC; />
            <!-- 数据源;池类型的数据源 -->
            <dataSource type=;POOLED;>
                <property name=;driver; value=;${driver}; /> <!-- 配置了properties;所以可以直接引用 -->
                <property name=;url; value=;${url}; />
                <property name=;username; value=;${username}; />
                <property name=;password; value=;${password}; />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource=;mapper/MyMapper.xml;></mapper>
    </mappers>
</configuration>


3.2配置Map.xml;一个dao对应一个map文件;

<?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=;com.luoke.dao.UserDao;>
    <!-- statement;内容;sql语句。id;唯一标识;随便写;在同一个命名空间下保持唯一
       resultType;sql语句查询结果集的封装类型,tb_user即为数据库中的表
     -->
    <select id=;selectUser; resultType=;com.luoke.entity.User;>
        select * from tb_user where id = #{id}
    </select>
</mapper>


3.3在全局配置中增加map映射

   <mappers>
     <mapper resource=;mappers/MyMapper.xml; />
   </mappers>

3.4实体类User

;Data
;ToString
public class User {
    private String id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private String created;
    private String updated;
}

3.5dao接口

public interface UserDao {
    public User selectUser();
}

3.6编写MybatisTest查询

public class MybatisTest {
    public static void main(String[] args) throws IOException {
        //读取全局配置文件
        String resource = ;mybatis-config.xml;;
        //读取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            // 操作CRUD;第一个参数;指定statement;规则;命名空间;“.”;statementId
            // 第二个参数;指定传入sql的参数;这里是用户id
            User user = sqlSession.selectOne(;selectUser;, 1);
            System.out.println(user);
        } finally {
            sqlSession.close();
        }
    }
}

3.7MyBatis使用步骤总结

1)配置mybatis-config.xml 全局的配置文件 (1、数据源;2、外部的mapper)
2)创建SqlSessionFactory
3)通过SqlSessionFactory创建SqlSession对象
4)通过SqlSession操作数据库 CRUD
5)调用session.commit()提交事务
6)调用session.close()关闭会话

四、完整的CRUD

4.1添加日志依赖

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>

4.2在resource下创建log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.org.apache=DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

4.3UserDao完整接口


public interface UserDao {
    /**
     * 根据id查询用户信息
     * ;param id
     * ;return
     */
    public User queryUserById(String id);

    /**
     * 查询全部用户信息
     * ;return
     */
    public List<User> queryUserAll();

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

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

    /**
     * 根据id删除用户
     * ;param id
     */
    public void deleteUser(String id);
}

4.4创建UserDaoImpl


public class UserDaoImpl implements UserDao {
    public SqlSession sqlSession;

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

    ;Override
    public User queryUserById(String id) {
        return this.sqlSession.selectOne(;queryUserById;,id);
    }

    ;Override
    public List<User> queryUserAll() {
        return sqlSession.selectList(;queryUserAll;);
    }

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

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


    ;Override
    public void deleteUser(String id) {
        this.sqlSession.delete(;deleteUser;,id);
    }
}

4.5.编写UserDao对应的UserDaoMapper.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=;com.luoke.dao.UserDao;>
    <!-- statement;内容;sql语句。id;唯一标识;随便写;在同一个命名空间下保持唯一
       resultType;sql语句查询结果集的封装类型,tb_user即为数据库中的表
     -->
    <!--<select id=;queryUserById; resultType=;com.zpc.mybatis.pojo.User;>-->
    <!--select * from tb_user where id = #{id}-->
    <!--</select>-->

    <!--使用别名-->
    <select id=;queryUserById; resultType=;com.luoke.entity.User;>
        select
            tuser.id as id,
            tuser.user_name as userName,
            tuser.password as password,
            tuser.name as name,
            tuser.age as age,
            tuser.birthday as birthday,
            tuser.sex as sex,
            tuser.created as created,
            tuser.updated as updated
        from
            tb_user tuser
        where tuser.id = #{id};
    </select>

    <select id=;queryUserAll; resultType=;com.luoke.entity.User;>
        select * from tb_user;
    </select>

    <!--插入数据-->
    <insert id=;insertUser; parameterType=;com.luoke.entity.User;>
        INSERT INTO tb_user (
            user_name,
            password,
            name,
            age,
            sex,
            birthday,
            created,
            updated
        )
        VALUES
        (
            #{userName},
            #{password},
            #{name},
            #{age},
            #{sex},
            #{birthday},
            now(),
            now()
        );
    </insert>

    <update id=;updateUser; parameterType=;com.luoke.entity.User;>
        UPDATE tb_user
        <trim prefix=;set; suffixOverrides=;,;>
            <if test=;userName!=null;>user_name = #{userName},</if>
            <if test=;password!=null;>password = #{password},</if>
            <if test=;name!=null;>name = #{name},</if>
            <if test=;age!=null;>age = #{age},</if>
            <if test=;sex!=null;>sex = #{sex},</if>
            <if test=;birthday!=null;>birthday = #{birthday},</if>
            updated = now(),
        </trim>
        WHERE
        (id = #{id});
    </update>

    <delete id=;deleteUser;>
        delete from tb_user where id=#{id}
    </delete>
</mapper>

4.6在mybatis-config.xml中添加配置

    <mappers>
        <mapper resource=;mapper/MyMapper.xml;></mapper>
        <mapper resource=;mapper/UserDaoMapper.xml;></mapper>
    </mappers>

4.7测试代码

junit依赖导入

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

在UserDao中Alt;insert;fn


Mybatis急速入门(上篇)

生产的测试具体代码如下

public class UserDaoTest {

    public UserDao userDao;
    public SqlSession sqlSession;

    ;Before
    public void setUp() throws Exception {
        // mybatis-config.xml
        String resource = ;mybatis-config.xml;;
        // 读取配置文件
        InputStream is = Resources.getResourceAsStream(resource);
        // 构建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 获取sqlSession
        sqlSession = sqlSessionFactory.openSession();
        this.userDao = new UserDaoImpl(sqlSession);
    }

    ;Test
    public void queryUserById() throws Exception {
        System.out.println(this.userDao.queryUserById(;1;));
    }

    ;Test
    public void queryUserAll() throws Exception {
        List<User> userList = this.userDao.queryUserAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }

    ;Test
    public void insertUser() throws Exception {
        User user = new User();
        user.setAge(16);
        user.setBirthday(new Date(;1990/09/02;));
        user.setName(;大鹏;);
        user.setPassword(;123456;);
        user.setSex(1);
        user.setUserName(;evan;);
        this.userDao.insertUser(user);
        this.sqlSession.commit();
    }

    ;Test
    public void updateUser() throws Exception {
        User user = new User();
        user.setBirthday(new Date());
        user.setName(;静鹏;);
        user.setPassword(;654321;);
        user.setSex(1);
        user.setUserName(;evanjin;);
        user.setId(;1;);
        this.userDao.updateUser(user);
        this.sqlSession.commit();
    }

    ;Test
    public void deleteUser() throws Exception {
        this.userDao.deleteUser(;4;);
        this.sqlSession.commit();
    }

}

1、接口->实现类->mapper.xml
2、实现类中;使用mybatis的方式非常类似
3、xml中的sql statement 硬编码到java代码中。
思考;能否只写接口;不写实现类。只编写接口和Mapper.xml即可?

因为在dao;mapper;的实现类中对sqlsession的使用方式很类似。因此mybatis提供了接口的动态代理。

五.动态代理Mapper实现类

5.1.创建UserMapper接口;对应原UserDao;

public interface UserMapper {
   
   /**
    * 登录;直接使用注解指定传入参数名称;
    * ;param userName
    * ;param password
    * ;return
    */
   public User login(;Param(;userName;) String userName, ;Param(;password;) String password);
   
   /**
    * 根据表名查询用户信息;直接使用注解指定传入参数名称;
    * ;param tableName
    * ;return
    */
   public List<User> queryUserByTableName(;Param(;tableName;) String tableName);
   
   /**
    * 根据Id查询用户信息
    * ;param id
    * ;return
    */
   public User queryUserById(Long id);
   
   /**
    * 查询所有用户信息
    * ;return
    */
   public List<User> queryUserAll();
   
   /**
    * 新增用户信息
    * ;param user
    */
   public void insertUser(User user);
   
   /**
    * 根据id更新用户信息
    * ;param user
    */
   public void updateUser(User user);
   
   /**
    * 根据id删除用户信息
    * ;param id
    */
   public void deleteUserById(Long id);
}

5.2创建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=;com.luoke.mapper.UserMapper;>
    <!--
       1.#{},预编译的方式preparedstatement;使用占位符替换;防止sql注入;一个参数的时候;任意参数名可以接收
       2.${},普通的Statement;字符串直接拼接;不可以防止sql注入;一个参数的时候;必须使用${value}接收参数
     -->
    <select id=;queryUserByTableName; resultType=;com.luoke.entity.User;>
        select * from ${tableName}
    </select>

    <select id=;login; resultType=;com.luoke.entity.User;>
        select * from tb_user where user_name = #{userName} and password = #{password}
    </select>

    <!-- statement;内容;sql语句。
       id;唯一标识;随便写;在同一个命名空间下保持唯一;使用动态代理之后要求和方法名保持一致
       resultType;sql语句查询结果集的封装类型;使用动态代理之后和方法的返回类型一致;resultMap;二选一
       parameterType;参数的类型;使用动态代理之后和方法的参数类型一致
     -->
    <select id=;queryUserById; resultType=;com.luoke.entity.User;>
        select * from tb_user where id = #{id}
    </select>
    <select id=;queryUserAll; resultType=;com.luoke.entity.User;>
        select * from tb_user
    </select>
    <!-- 新增的Statement
       id;唯一标识;随便写;在同一个命名空间下保持唯一;使用动态代理之后要求和方法名保持一致
       parameterType;参数的类型;使用动态代理之后和方法的参数类型一致
       useGeneratedKeys:开启主键回写
       keyColumn;指定数据库的主键
       keyProperty;主键对应的pojo属性名
     -->
    <insert id=;insertUser; useGeneratedKeys=;true; keyColumn=;id; keyProperty=;id;
            parameterType=;com.luoke.entity.User;>
        INSERT INTO tb_user (
            id,
            user_name,
            password,
            name,
            age,
            sex,
            birthday,
            created,
            updated
        )
        VALUES
        (
            null,
            #{userName},
            #{password},
            #{name},
            #{age},
            #{sex},
            #{birthday},
            NOW(),
            NOW()
        );
    </insert>
    <!--
       更新的statement
       id;唯一标识;随便写;在同一个命名空间下保持唯一;使用动态代理之后要求和方法名保持一致
       parameterType;参数的类型;使用动态代理之后和方法的参数类型一致
     -->
    <update id=;updateUser; parameterType=;com.luoke.entity.User;>
        UPDATE tb_user
        <trim prefix=;set; suffixOverrides=;,;>
            <if test=;userName!=null;>user_name = #{userName},</if>
            <if test=;password!=null;>password = #{password},</if>
            <if test=;name!=null;>name = #{name},</if>
            <if test=;age!=null;>age = #{age},</if>
            <if test=;sex!=null;>sex = #{sex},</if>
            <if test=;birthday!=null;>birthday = #{birthday},</if>
            updated = now(),
        </trim>
        WHERE
        (id = #{id});
    </update>
    <!--
       删除的statement
       id;唯一标识;随便写;在同一个命名空间下保持唯一;使用动态代理之后要求和方法名保持一致
       parameterType;参数的类型;使用动态代理之后和方法的参数类型一致
     -->
    <delete id=;deleteUserById; parameterType=;java.lang.String;>
        delete from tb_user where id=#{id}
    </delete>
</mapper>

5.3全局配置文件mybatis-config.xml引入UserMapper.xml

    <mappers>
        <mapper resource=;mapper/MyMapper.xml;></mapper>
        <mapper resource=;mapper/UserDaoMapper.xml;></mapper>
        <mapper resource=;mapper/UserMapper.xml;></mapper>
    </mappers>

5.4创建UserMapper测试用例

public class UserMapperTest {
    public UserMapper userMapper;

    ;Before
    public void setUp() throws IOException {
        // 指定配置文件
        String resource = ;mybatis-config.xml;;
        // 读取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        // 1. 映射文件的命名空间;namespace;必须是mapper接口的全路径
        // 2. 映射文件的statement的id必须和mapper接口的方法名保持一致
        // 3. Statement的resultType必须和mapper接口方法的返回类型一致
        // 4. statement的parameterType必须和mapper接口方法的参数类型一致;不一定;
        this.userMapper = sqlSession.getMapper(UserMapper.class);
    }


    ;Test
    public void login() {
        System.out.println(this.userMapper.login(;hj;, ;123456;));
    }

    ;Test
    public void queryUserByTableName() {
        List<User> userList = this.userMapper.queryUserByTableName(;tb_user;);
        for (User user : userList) {
            System.out.println(user);
        }
    }

    ;Test
    public void queryUserById() {
        System.out.println(this.userMapper.queryUserById(;1;));
    }

    ;Test
    public void queryUserAll() {
        List<User> userList = this.userMapper.queryUserAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }

    ;Test
    public void insertUser() {
        User user = new User();
        user.setAge(20);
        user.setBirthday(new Date());
        user.setName(;大神;);
        user.setPassword(;123456;);
        user.setSex(2);
        user.setUserName(;bigGod222;);
        this.userMapper.insertUser(user);
        System.out.println(user.getId());
    }

    ;Test
    public void updateUser() {
        User user = new User();
        user.setBirthday(new Date());
        user.setName(;静静;);
        user.setPassword(;123456;);
        user.setSex(0);
        user.setUserName(;Jinjin;);
        user.setId(;1;);
        this.userMapper.updateUser(user);
    }

    ;Test
    public void deleteUserById() {
        this.userMapper.deleteUserById(;1;);
    }
}

动态代理;重点;

使用mapper接口不用写实现类即可完成数据库的操作;使用非常简单;也是官方推荐的使用方法
使用mapper接口的必须具备的条件
1;Mapper的namespace必须和mapper接口的全路径名一致
2;Mapper接口的方法名和sql定义的id一致
3;Mapper接口中方法的输入参数类型必须和sql定义的parameterType一致
4;Mapper接口中方法的输出参数类型必须和sql定义的resultType一致

网友评论

快盘下载暂未开通留言功能。

关于我们| 广告联络| 联系我们| 网站帮助| 免责声明| 软件发布

Copyright 2019-2029 【快快下载吧】 版权所有 快快下载吧 | 豫ICP备10006759号公安备案:41010502004165

声明: 快快下载吧上的所有软件和资料来源于互联网,仅供学习和研究使用,请测试后自行销毁,如有侵犯你版权的,请来信指出,本站将立即改正。