myBatis学习笔记(1)——快速入门

在项目中使用myBatis

  • 导入jar包
    这里写图片描述
  • 在src下创建配置文件


<configuration>
    
    <environments default="development">
        <environment id="development">
            
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/bank" />
                <property name="username" value="root" />
                <property name="password" value="123" />
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="userMapper.xml" />
    mappers>

configuration>
  • 创建user实体类
package com.bank.entities;

public class User {

    private String username;
    private int money;

    public User() {
        super();
    }

    public User(String username, int money) {
        super();
        this.username = username;
        this.money = money;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getMoney() {
        return money;
    }
    public void setMoney(int money) {
        this.money = money;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", money=" + money + "]";
    }

}

  • 创建userMapper.xml文件



<mapper namespace="com.bank.userMapper">
    
    <select id="getUser" parameterType="String"
        resultType="com.bank.entities.User">
        select * from user where username=#{username}
    select>

    <update id="updateUser" parameterType="com.bank.entities.User">
        update user set money=#{money} where username=#{username}
    update>

    <delete id="deleteUser" parameterType="String">
        delete from user where username=#{username}
    delete>
    
    <select id="getAll" resultType="com.bank.entities.User">
        select * from user
    select>
mapper>

在映射文件中,增删改查分别对应四个标签