SSM之mybatis的基本环境配置与测试

1.创建maven工程导入依赖

        <!-- mybatis依赖-->
         <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--junit(用于测试)-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <!--log4j(日志)-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

2.在resources中创建db.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///mybatis-220301 //自己的数据库
jdbc.user = root  //数据库账户
jdbc.password = root //密码

3.创建实体类

public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

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

    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;
    }
}

4.在mapper文件夹中创建UserMapper类

import com.hqyj.lls.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
    //查所有
    @Select("select * from user")
    List<User> select();

    //根据id 查所有
    @Select("select * from user where id = #{id}")
    List<User> selectOne(Integer id);

    //删除
    @Delete("delete from user where id = #{userid}")
    Integer delete(int id);

    //添加
    @Insert("insert into user values (#{id},#{username},#{password})")
    Integer insert(User user);

    //修改
    @Update("update user set username = #{name},password = #{pwd} where id = #{id}")
    Integer update(@Param("id") Integer id,@Param("name") String name,@Param("pwd") String pwd);
}

5.新建一个utils工具文件夹,在文件夹中新建一个MybatisUtils工具类来加载mybatis-config.xml文件

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 {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            InputStream rs = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(rs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

6.在resources中创建Mybatis核心配置文件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"/>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--    配置别名-->
    <typeAliases>
        <typeAlias type="com.hqyj.lls.entity.User" alias="User"/>

    </typeAliases>

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

<!--    //指定当前的Mapper接口-->
    <mappers>
        <mapper class="com.hqyj.lls.mapper.UserMapper"/>
    </mappers>
</configuration>

7.使用测试类测试

import com.hqyj.lls.entity.User;
import com.hqyj.lls.mapper.UserMapper;
import com.hqyj.lls.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestUser {
    private static SqlSession session = MybatisUtils.getSession();

    /**
     * #{}和 ${}有什么区别
     * #{}是占位符,等价丁PreparedStatement
     * ${}是字符串替换,等价于Statement ,注意在使用时考虑sql的语法问题,一般为参数的引号替换!
     *
     */

    //查所有
    @Test
    public void select(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> select = mapper.select();
        for (User user:select){
            System.out.println(user);
        }
    }

    //根据id查
    @Test
    public void selectOne(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectOne(1);
        System.out.println(users);
    }

    //根据id删除
    @Test
    public void delete(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        Integer delete = mapper.delete(3);
        System.out.println(delete);
    }

    //添加
    @Test
    public void insert(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = new User(5, "zhaoliu", "789");
        Integer insert = mapper.insert(user);
        System.out.println(insert);
    }

    //修改
    @Test
    public void update(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        Integer lisi = mapper.update(2, "lisi", "132");
        System.out.println(lisi);
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值