mybatis的简单搭建和使用(一)

前言

  mybatis是一个持久层的框架,那么问题来了,什么是持久层的框架呢,持久层就是把数据持久化的保存到数据库中,这种过程一般叫数据持久化的过程,现为了程序员能够很方便的操作数据库,于是就出现持久层的框架.mybatis就是其中的佼佼者,将java代码和sql语句分离的出来

一,环境的搭建

 1.首先在IDEA中创建一个quick start的maven项目, 然后一直点击下一步

2.创建好项目,在pom.xml中导入依赖包,主要导入三个依赖包,分别是log4j,mysql,mybatis

 <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

3,在main目录下创建resources文件夹,并且Mark resources as为 resource文件

4,在该文件夹中创建3个文件,分别是db.properties  , log4j.properties 和mybatis.xml

具体内容如下,db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis02?useSSL=false
username=root
password=123456

log4j.properties具体内容如下:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis.xml的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>
        <package name="com.shsxt.po"></package>
    </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>
        
       <package name="com.shsxt.mapper"/>
    </mappers>
</configuration>

5,在src/java目录下,创建package,名为mapper,该包下创建映射文件UserMapper.xml和UserMapper的接口以及实现类

    UserMapper.xml的具体内容如下:

<?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.shsxt.mapper.UserMapper">
<select id="queryById" parameterType="int" resultType="User">
        select * from user where id=#{id}
    </select>
</mapper>

UserMapper的接口内容如下:

实现类UserMapperImpl的具体内容如下:

import com.shsxt.mapper.UserMapper;
import com.shsxt.po.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;
import java.util.Map;

public class UserMapperImpl implements UserMapper {
    private SqlSessionFactory sqlSessionFactory;

    public UserMapperImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public User queryById(Integer id) {
        SqlSession session=null;
        User user=null;
        try {
            session=sqlSessionFactory.openSession();
             user=session.selectOne("com.shsxt.mapper.UserMapper.queryById" ,id);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(session!=null){
                session.close();
            }
        }

        return user;
    }

6,创建一个实体类user

public class User {
    private Integer id;
    private String username;
    private String realname;
    private String 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 getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    public String getPassword() {
        return password;
    }

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

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

7,创建一个mysql的数据库,名必须db.properties中  url=jdbc:mysql://localhost:3306/mybatis02?useSSL=false中的mybatis02的数据库名保持一致,

之后再创建一个user表,字段尽量与User类中的成员变量名保持一致

 

 8,在test文件夹中写一个test类,用于测试

Test_mybatis02中的具体内容如下:

import com.shsxt.mapper.Impl.UserMapperImpl;
import com.shsxt.mapper.UserMapper;
import com.shsxt.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test_mybatis02 {
    SqlSessionFactory sqlSessionFactory;
    @Before
    public void ready() throws IOException {
        InputStream inputStream= Resources.getResourceAsStream("mybatis.xml");
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    }

    /*
    * queryById*/
    @Test
    public void test01(){
        UserMapper userMapper=new UserMapperImpl(sqlSessionFactory);
       User user= userMapper.queryById(1);
       System.out.println(user);
    }
}

9,测试结果如下,说明搭建成功了,本次环境搭建稍微较为复杂,

10,在UserMapper.xml中写了sql语句会出现大量报黄色的现象,一般来说是两个原因

第一个,没有配置数据源,也就是没有在IDEA中配置数据库,可按照如下配置

 

1,点击右边上的database

2,点击+号,选择data source,选择mysql

 

3,如下图所示

 

第二个,在setting中搜索sql,如下图所示,将project sql dialect设置为mysql即可

 

转载于:https://www.cnblogs.com/liu1459310172/p/9759755.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值