Java框架--Mybaits(一)

2020-09-03  本文已影响0人  RicherYY
  1. 为什么要使用Mybatis?
  2. 快速入门
  3. 高级映射
  4. 动态SQL

1. 为什么要使用Mybatis?

image.png

2. 快速入门

通过使用增删改查来进行快速入门

2.0数据库结构表

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `sex` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'jack', 'F', 22);
INSERT INTO `user` VALUES (2, 'lucy', 'M', 25);
INSERT INTO `user` VALUES (3, 'Anna', 'F', 20);

image.png image.png image.png

2.1 配置db.properties文件

driver = com.mysql.cj.jdbc.Driver
username = root
password = 123456
url = jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC

2.2 配置mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 配置文件设置 -->
    <properties resource="resource/db.properties"/>
    <!-- 别名 -->
    <typeAliases>
        <package name="pojo"/>
    </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>
        <!--<mapper resource="dao/UserMapper.xml"/>-->
        <package name="dao"/>
    </mappers>

</configuration>

2.3 配置UserMapper.xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.UserMapper">
    <select id="findAllUser"  resultType="User">
        select * from  user;
    </select>

    <select id="findUserById" parameterType="int" resultType="User">
        select * from user where id = #{id};
    </select>

    <insert id="addUser" parameterType="User">
        insert into user (id,name,sex,age) values(#{id},#{name},#{sex},#{age});
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id};
    </delete>

    <update id="updateUserName" parameterType="User">
        update user set name = #{name} where id = #{id};
    </update>

</mapper>

2.4 配置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;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

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

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

2.5 实现DAO业务接口UserMapper

package dao;
import pojo.User;
import java.util.List;

public interface UserMapper {

    /**
     * 查找全部用户
     * @return 用户List集合
     */
    List<User> findAllUser();

    /**
     * 查找一个用户
     * @param id 用户id
     * @return 返回一个用户
     */
    User findUserById(int id);

    /**
     * 增加一个用户
     * @param user 增加用户的对象
     * @return 返回成功与否
     */
    int addUser(User user);
    /**
     * 删除一个用户
     * @param id
     * @return
     */
    int deleteUser(int id);

    /**
     * 更新一个用户的名字
     * @param user
     * @return
     */
    int updateUserName(User user);
}

2.6 编写测试类进行测试

package test;

import dao.UserMapper;
import org.apache.ibatis.session.SqlSession;
import pojo.User;
import utils.MybatisUtils;
import java.util.List;

public class MybatisTest {
    public static void main(String[] args) throws Exception{
        
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //查找全部用户
        List<User> userList = userMapper.findAllUser();
        for (User user : userList) {
            System.out.println("ID:" + user.getId() + ",NAME:" + user.getName()
                    + ",SEX:" + user.getSex() + ",AGE:" + user.getAge());
        }

        //查找单一用户
        User user1 = userMapper.findUserById(1);
        System.out.println(user1);
        
        //增加一个用户
        User user2 = new User(4,"aaa","F",12);
        int a = userMapper.addUser(user2);
        sqlSession.commit();
        sqlSession.close();
        System.out.println(a);
        
        //删除一个用户
        int b = userMapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
        System.out.println(b);
        
        //修改一个用户
        User user3 = new User();
        user3.setId(3);
        user3.setName("Anna");
        int c = userMapper.updateUserName(user3);
        sqlSession.commit();
        sqlSession.close();
        System.out.println(c);

    }
}
上一篇下一篇

猜你喜欢

热点阅读