Mybatis入门案例

mybatis入门案例

pom.xml,mybatis.xml,db.properties,UserDao.xml文件配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>MybatisTest</artifactId>
    <version>1.0-SNAPSHOT</version>



    <!-- 解决 File encoding has not been set, using platform encoding UTF-8,
    i.e. build is platform dependent!-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!--配置maven阿里云仓库开始,不用去改maven的setting-->
    <repositories>
        <repository>
            <id>public</id>
            <name>localprivatenexus</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>public</id>
            <name>localprivatenexus</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <!--配置maven阿里云结束-->
    <dependencies>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

    </dependencies>
    <build>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

    </build>




</project>

mybatis.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>
    <!-- stdout logging  标准输出日志
     settings 控制mybatis全局行为的
     -->
    <!--<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>-->
    
    <!-- 环境配置 数据库的连接信息
         default: 与environment 中某个id值保持一致 表示你默认要用到那个数据库
    -->
    <!-- 加载数据库配置文件 -->
    <properties resource="db.properties"/>
    <environments default="development">
        <!-- environment :一个数据库的信息配置,环境 environments表示多个环境
             id: 一个唯一值 可自定义 表示环境的名称
        -->
        <environment id="development">
            <!-- transactionManager :mybatis的事务类型
                  type: JDBC(表示使用jdbc中connection对象的commit,rollback 做事务处理
                  dataSource : 表示数据源 用来连接数据库的
                  type: POOLED (连接池 例如c3p0 Druid)
            -->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 一个mapper标签指定一个文件的位置
          从类路径开始的路径信息。 target/classes(类路径)   -->
    <mappers>
        <mapper resource="Dao\UserDao.xml"/>
    </mappers>
</configuration>

UserDao.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="Dao.UserDao">
    <!-- id 为接口中查询方法的方法名 也可自定义
         resultType:表示结果类型,遍历resultSet得到的java类型 ==全限定名称== !
     -->
    <select id="userList" resultType="entity.User">
    select id,username,password from test01 order by id
    </select>
    <insert id="insertUser">
        insert into test01 values (#{id},#{username},#{password})
    </insert>
    <delete id="deleteUser" >
        delete from test01 where id=#{id}
    </delete>
</mapper>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/mybatis?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=33333333

创建实体类和dao层

entity.User

package entity;

/**
 * Created with IntelliJ IDEA.
 *
 * @author Administrator
 * @Auther: 风离
 * @Date: 2021/03/06/10:56
 * @Description:
 */
public class User {
    private String username,password;
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

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

    public User() {
    }

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

Dao.UserDao

package Dao;

import entity.User;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 风离
 * @Date: 2021/03/06/11:00
 * @Description: 使用jdk动态代理 不用写实现类
 */
public interface UserDao {
    //查询所有账号数据
    public List<User> userList() throws IOException;
    //插入一条数据: user 表示要插入数据库的数据
    // int 表示影响的行数
    public int insertUser(User user) throws IOException;
    public int deleteUser(User user) throws IOException;

}

实现类

package Dao;

import entity.User;
import org.apache.ibatis.session.SqlSession;
import utils.MybatisUtils;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 风离
 * @Date: 2021/03/09/0:12
 * @Description:
 */
public class UserDaoImpl implements UserDao {
    @Override
    public List<User> userList() throws IOException {
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        String sqlId="Dao.UserDao."+"userList";
       return sqlSession.selectList(sqlId);
       //sqlSession.close();
    }

    @Override
    public int insertUser(User user) throws IOException {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        String sqlId="Dao.UserDao."+"insertUser";
        return sqlSession.insert(sqlId,user);
        //sqlSession.close();
    }

    @Override
    public int deleteUser(User user) throws IOException {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        String sqlId="Dao.UserDao."+"deleteUser";
        return sqlSession.delete(sqlId,user.getId());
        //sqlSession.close();
    }
}

重复步骤则封装成工具类

MybatisUtils

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 风离
 * @Date: 2021/03/08/21:13
 * @Description:
 */
public class MybatisUtils {
   public static SqlSessionFactory sqlSessionFactory=null;
    static {
        //1.定义mybatis主配置文件的名称,从类路径的根target/classes
        String config="mybatis.xml";
        //2.读取这个config表示的文件
        try {
            InputStream in= Resources.getResourceAsStream(config);
            //3.创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
            //4.创建SqlSessionFactory对象
            sqlSessionFactory=builder.build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession() throws IOException {
        //5【重要】.获取SqlSession对象,从SqlSessionFactory中获取 带参数true 默认自动提交事务
        if (sqlSessionFactory != null) {
            return sqlSessionFactory.openSession(true);
        }
        return null;
    }
}

测试类

import Dao.UserDao;
import Dao.UserDaoImpl;
import entity.User;
import org.apache.ibatis.session.SqlSession;
import utils.MybatisUtils;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 风离
 * @Date: 2021/03/06/15:03
 * @Description:第一个访问通过mybatis访问数据库案例
 */
public class Test {
    public static void main(String[] args) throws IOException {
        //User user=new User("伍六七","rewq4321",777);
        //System.out.println(user.toString());
        UserDao userDao=new UserDaoImpl();
        userDao.userList().forEach(user -> System.out.println(user));
        //System.out.println("插入数据的条数为:"+userDao.insertUser(user));

    }
}

看看是否能查出来~~

Mybatis入门案例

完美!! 下一篇 为:利用jdk动态代理来简化查询过程,即省略手动实现类

上一篇:IO流


下一篇:hbase安装并且简单的例子