MyBatis-第一个MyBatis程序

文章目录

  • MyBatis-第一个MyBatis程序
      • 二、第一个MyBatis程序
        • 1、搭建环境
          • 搭建数据库
        • 2、创建项目
        • 3、编写代码

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目录
  • 导入依赖
		
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
  • 创建一个maven模块
  • 核心配置文件

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&useUnicode=true&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配置文件)

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>
        <resources>
            <resource>
                <directory>src/main/resourcedirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            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 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();
        }

    }
}

你可能感兴趣的:(#,MyBatis,maven,java,数据库,mybatis)