和我一起迎接明天的太阳吧

klaus08

焦虑源于行动的匮乏

2021-07-26 MyBatis注解开发

注解开发简单demo


注解配置的本质是 Java 反射,底层是动态代理


程序结构


UserMapper.java

package com.klaus.dao;

import com.klaus.pojo.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {

    @Select("select * from user")
    List<User> getUser();
}

User.java

package com.klaus.pojo;

public class User {
    private int id;
    private String name;
    private String password;

    public User() {}

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

MyBatisUtils.java

package com.klaus.utils;

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

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {

    public static SqlSessionFactory sqlSessionFactory;

    static {
        // 获取sqlSessionFactory对象
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

db.properties

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

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 resource="db.properties"/>

    <typeAliases>
        <typeAlias type="com.klaus.pojo.User" alias="user"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 绑定配置文件 -->
    <mappers>
        <mapper class="com.klaus.dao.UserMapper"/>
    </mappers>

</configuration>

MyTest.java

package com.klaus.dao;

import com.klaus.pojo.User;
import com.klaus.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyTest {
    @Test
    public void testGetUser(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUser();

        for (User user: userList )
            System.out.println(user);

        sqlSession.close();
    }
}

CRUD


package com.klaus.dao;

import com.klaus.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserMapper {

    @Select("select * from user")
    List<User> getUser();

//    有多个参数时,必须给每个参数加上注解
//    sql中取的 #{}里的参数名 必须和 @Param()中声明的一致
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id")int id);

    @Insert("insert into user(id, name, pwd) values (#{id}, #{name}, #{password})")
    int addUser(User user);

    @Update("update user set name=#{name},pwd=#{password} where id=2")
    int updateUser(@Param("name") String name, @Param("password") String password);
}

这里,更新用户信息,两个参数必须使用 @Param 指明,然后才能在 sql 中使用。

@Update("update user set name=#{name},pwd=#{password} where id=2")

int updateUser(@Param("password") String name, @Param("name") String password);

posted @ 2021-07-26 20:43  klaus08  阅读(30)  评论(0编辑  收藏  举报