MyBatis-第一个MyBatis程序

MyBatis-第一个MyBatis程序

二、第一个MyBatis程序

思路:搭建环境-》导入MyBatis-》编写代码-》测试

1、搭建环境
  • 搭建数据库
-- 创建数据库
create database `mybatis`;
use `mybatis`;
-- 创建表
create table if not exists `user`(
`id` int(4) not null auto_increment comment "学号",
`name` varchar(20) default null comment "姓名",
`pwd` varchar(20) default null comment "密码",
primary key (`id`)
)engine=innodb default charset=utf8;
-- 插入数据
insert into `user`(`name`,`pwd`)values("李冲","123"),("李世民","123"),("李网吧","123");
2、创建项目
  • 新建一个maven项目,删除src目录
  • 导入依赖
		<!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
  • 创建一个maven模块
  • 核心配置文件
<?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.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?
                useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
  • 编写mybatis工具类
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static{
        //使用mybatis第一步:获取sqlSessionFactory对象
        InputStream inputStream = null;
        try {
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例了;
    //SqlSession完全包含了面向数据库执行sql命令所需的所有方法;
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
3、编写代码
  • 实体类
public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

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

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
     @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
  • Dao层
public interface UserDao {
    List<User> getUserList();
}
  • 接口实现类(由UserDaoImpl转变成一个Mapper配置文件)
<?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="com.lengzher.Dao.UserDao">
    <select id="getUserList" resultType="com.lengzher.pojo.User">
    select * from mybatis.user;
   </select>
</mapper>
  • 测试
<!--在build中配置resource,来防止我们资源导出失败问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resource</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
public class UserDaoTest {
    @Test
    public void test(){

        SqlSession sqlSession = null;

        try{
            //第一步:获取sqlSession对象
            sqlSession = MybatisUtils.getSqlSession();

            //执行sql

            //方式一:getMapper
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();

            //方式二:
//        List<User> userList = sqlSession.selectList("com.lengzher.Dao.UserDao.getUserList");

            //遍历数组,输出
            for (User user : userList) {
                System.out.println(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭SqlSession
            sqlSession.close();
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值