MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo

参考

(1)使用IDEA创建javaweb项目
(2)MyBatis学习笔记(一)入门(重点)
(3)IntelliJ IDEA手动配置连接MySQL数据库
(4)IntelliJ IDEA单元测试入门


创建Java Web项目

参考:使用IDEA创建javaweb项目
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第1张图片
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第2张图片


导入MyBatis所需的jar包

参考:MyBatis学习笔记(一)入门
mybatis需要jar包:mybatis-3.4.2.jar
mysql驱动jar包:mysql-connector-java-5.1.39-bin.jar
日志记录jar包:log4j-1.2.17.jar,slf4j-api-1.7.12.jar,slf4j-log4j12-1.7.12.jar
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第3张图片


创建数据库mybatis和表t_user

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第4张图片
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第5张图片


IDEA配置MySQL数据源

参考:IntelliJ IDEA手动配置连接MySQL数据库
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第6张图片
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第7张图片
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第8张图片
点击Test Connection
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第9张图片
点击OK后,可以看到
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第10张图片


MyBatis入门Demo

参考:MyBatis学习笔记(一)入门

(1)代码结构

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第11张图片

(2)mysql驱动配置文件

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第12张图片

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

(3)日志配置文件

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第13张图片

### 设置Logger输出级别和输出目的地 ###
log4j.rootLogger=debug,stdout,logfile

### 把日志信息输出到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

### 把日志信息输出到文件:jbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n

###显示SQL语句部分
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

(4)MyBatis配置文件mybatis.cfg.xml

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第14张图片
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第15张图片



<configuration>

    
    <properties resource="mysql.properties">properties>


    
    <environments default="zzbatis">
        <environment id="zzbatis">
            
            <transactionManager type="JDBC" />

            
            
            
            
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            dataSource>
        environment>
    environments>


configuration>

(5)创建对应的实体对象UserBean

这里写图片描述

package com.zz.mybatis.beans;

import java.io.Serializable;

public class UserBean implements Serializable{

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String password;
    private Double account;

    public UserBean() {
        super();
    }

    public UserBean(String username, String password, Double account) {
        super();
        this.username = username;
        this.password = password;
        this.account = account;
    }

    public UserBean(Integer id, String username, String password, Double account) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.account = account;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Double getAccount() {
        return account;
    }

    public void setAccount(Double account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "UserBean [id=" + id + ", username=" + username + ", password="
                + password + ", account=" + account + "]";
    }

}

(6)创建方法接口UserMapper.java和定义操作t_user表的sql映射文件UserMapper.xml

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第16张图片
UserMapper.java

package com.zz.mybatis.mapper;

import java.util.List;

import com.zz.mybatis.beans.UserBean;

public interface UserMapper {
    /**
     * 新增用戶
     * @param user
     * @return
     * @throws Exception
     */
    public int insertUser(UserBean user) throws Exception;
    /**
     * 修改用戶
     * @param user
     * @param id
     * @return
     * @throws Exception
     */
    public int updateUser (UserBean user,int id) throws Exception;
    /**
     * 刪除用戶
     * @param id
     * @return
     * @throws Exception
     */
    public int deleteUser(int id) throws Exception;
    /**
     * 根据id查询用户信息
     * @param id
     * @return
     * @throws Exception
     */
    public UserBean selectUserById(int id) throws Exception;
    /**
     * 查询所有的用户信息
     * @return
     * @throws Exception
     */
    public List selectAllUser() throws Exception;
}

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第17张图片
UserMapper.xml



<mapper namespace="com.zz.mybatis.mapper.UserMapper">
    
    <resultMap id="userMap" type="UserBean">
        <id property="id" column="id" javaType="java.lang.Integer">id>
        <result property="username" column="username" javaType="java.lang.String">result>
        <result property="password" column="password" javaType="java.lang.String">result>
        <result property="account" column="account" javaType="java.lang.Double">result>
    resultMap>
    
    
    
    


    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user (username,password,account) values (#{username},#{password},#{account})
    insert>

    <update id="updateUser" >
        update t_user set username=#{username},password=#{password},account=#{account} where id=#{id}
    update>

    <delete id="deleteUser" parameterType="int">
        delete from t_user where id=#{id}
    delete>

    <select id="selectUserById" parameterType="int" resultMap="userMap">
        select * from t_user where id=#{id}
    select>

    <select id="selectAllUser" resultMap="userMap">
        select * from t_user
    select>


mapper>

mybatis.cfg.xml里注册UserMapper.xml文件



<configuration>

    
    <properties resource="mysql.properties">properties>

    
    <typeAliases >
        
        
        <package name="com.zz.mybatis.beans"/>
    typeAliases>

    
    <environments default="zzbatis">
        <environment id="zzbatis">
            
            <transactionManager type="JDBC" />

            
            
            
            
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            dataSource>
        environment>
    environments>

    <mappers>
        
        
        <package name="com/zz/mybatis/mapper"/>
    mappers>

configuration>

(7)建立一个工具类DBTools

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第18张图片
DBTools.java:

package com.zz.mybatis.tools;

import java.io.Reader;

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 DBTools {
    public static SqlSessionFactory sessionFactory;

    static{
        try {
            //使用MyBatis提供的Resources类加载mybatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
            //构建sqlSession的工厂
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //创建能执行映射文件中sql的sqlSession
    public static SqlSession getSession(){
        return sessionFactory.openSession();
    }

}

(8)测试

参考:IntelliJ IDEA单元测试入门
MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第19张图片
UserServiceTest:

package com.zz.mybatis.service;

import com.zz.mybatis.beans.UserBean;
import com.zz.mybatis.mapper.UserMapper;
import com.zz.mybatis.tools.DBTools;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.*;

public class UserServiceTest {
    @Test
    public void insertUser() throws Exception {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        UserBean user = new UserBean("咖啡", "1314520", 7000.0);
        try {
            mapper.insertUser(user);
            System.out.println(user.toString());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

    @Test
    public void deleteUser() throws Exception {
        SqlSession session=DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);
        try {
            mapper.deleteUser(1);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

    @Test
    public void selectUserById() throws Exception {
        SqlSession session=DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);
        try {
            UserBean user=    mapper.selectUserById(2);
            System.out.println(user.toString());

            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

    @Test
    public void selectAllUser() throws Exception {
        SqlSession session=DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);
        try {
            List user=mapper.selectAllUser();
            System.out.println(user.toString());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

}

MyBatis学习笔记(一)IntelliJ IDEA的第一个MyBatis Demo_第20张图片

你可能感兴趣的:(Java__MyBatis)