Java MyBatis的使用

首先maven引用配置:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.18</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.10</version>
    </dependency>

 

第一步:MySQL建表

CREATE TABLE `account` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(200) DEFAULT NULL COMMENT '用户名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

第二步:生成对应实体类

  这里推荐一个自动生成的平台:http://java.bejson.com/generator/  

import java.io.Serializable;
import lombok.Data;
import java.util.Date;
import java.util.List;

/**
*  用户表
* @author  2019-12-12
*/
@Data
public class Account implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
    * 主键
    */
    private Long id;

    /**
    * 用户名
    */
    private String name;

    public Account() {
    }

}

 

第三步:创建该表SQL查询的映射文件(accountMapper.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="accountMappero">

    <resultMap id="BaseResultMap" type=".entity.AccountEntity" >
                <result column="id" property="id" />
                <result column="name" property="name" />
    </resultMap>

    <sql id="Base_Column_List">
                id,
                name
    </sql>

    <insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType=".entity.AccountEntity">
        INSERT INTO account
        <trim prefix="(" suffix=")" suffixOverrides=",">
                        <if test ='null != name'>
                        name
                        </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
                        <if test ='null != name'>
                        #{name}
                        </if>
        </trim>
    </insert>

    <delete id="delete" >
        DELETE FROM account
        WHERE id = #{id}
    </delete>

    <update id="update" parameterType=".entity.AccountEntity">
        UPDATE account
        <set>
                    <if test ='null != name'>name = #{name}</if>
        </set>
        WHERE id = #{id}
    </update>


    <select id="load" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM account
        WHERE id = #{id}
    </select>

    <select id="pageList" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List" />
        FROM account
        LIMIT #{offset}, #{pageSize}
    </select>

    <select id="pageListCount" resultType="java.lang.Integer">
        SELECT count(1)
        FROM account
    </select>

</mapper>

 

 

第四步:配置数据库连接文件(conf.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://服务器地址:端口号/数据库名称?serverTimezone=GMT%2B8" />
                <property name="username" value="数据库用户名" />
                <property name="password" value="数据库密码" />
            </dataSource>
        </environment>
    </environments>     
    <mappers>
        <!-- 注册userMapper.xml文件-->
        <mapper resource="accountMapper.xml"/>
     </mappers>
    
</configuration>

 

第五步:编写测试方法

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;

import com.springdemo.model.User;
import com.springdemo.tools.DBTools;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {

    public static void main(String[] args) throws IOException {
    
        //mybatis的配置文件
        String resource = "conf.xml";
        //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = Resources.getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();
        /*
         * 映射sql的标识字符串 这里的accountMapper是accountMapper.xml中mapper的namespaces
         */
        String statement = "accountMapper.load";
        Account user = session.selectOne(statement,1);
        System.out.println(user);
        
}

 

最后:done

 

posted on 2019-12-12 15:27  梦林``ysl  阅读(197)  评论(0编辑  收藏  举报

导航