MyBatis入门案例

发布于:2023-02-18 ⋅ 阅读:(567) ⋅ 点赞:(0)

目录结构

在这里插入图片描述

项目依赖

        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <!-- log4j日志 方便查看mybatis执行的具体sql语句 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- 可以使你省略get、set等方法 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>

mybatis-config.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>

	<!-- 起别名,方便后期少写代码 -->
    <typeAliases>
        <typeAlias type="com.daidai.domain.User" alias="user"/>
    </typeAliases>

    <!--设置连接数据库的环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="000000"/>
            </dataSource>
        </environment>
    </environments>

    <!--加载映射文件 这个文件中包括具体的sql语句-->
    <mappers>
        <mapper resource="com/daidai/dao/UserMapper.xml"></mapper>
    </mappers>
</configuration>

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}%m (%F:%L) \n"/>
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug"/>
    </logger>
    <logger name="org.apache.ibatis">
<!--        3、核心配置文件详解-->
<!--        核心配置文件中的标签必须按照固定的顺序:-->
<!--        properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,refl-->
<!--        ectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?-->
        <level value="info"/>
    </logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>
</log4j:configuration>

实体类 User

package com.daidai.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class User {
    private Integer userId;
    private String userName;
    private String userPassword;
}

数据层操作接口 UserDao

定义增删改查操作

package com.daidai.dao;

import com.daidai.domain.User;

import java.util.List;

public interface UserDao {
    void addUser(User user);

    int delUser(int userId);

    int updUser(User user);

    List<User> selAll();

    User selOneById(int userId);
}

UserMapper.xml

1、映射文件的命名规则:
表所对应的实体类的类名+Mapper.xml
例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
因此一个映射文件对应一个实体类,对应一张表的操作
MyBatis映射文件用于编写SQL,访问以及操作表中的数据
MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2、 MyBatis中可以面向接口操作数据,要保证两个一致:
a) mapper接口的全类名和映射文件的命名空间(namespace)保持一致
b) mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致

<?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.daidai.dao.UserDao">

    <insert id="addUser" parameterType="user">
        insert into User values (#{userId}, #{userName}, #{userPassword})
    </insert>

    <delete id="delUser" parameterType="int">
        delete from user where id = #{userId}
    </delete>

    <update id="updUser" parameterType="user">
        update user set username = #{userName}, password = #{userPassword} where id = #{userId}
    </update>

    <select id="selAll" resultType="user">
        select * from user;
    </select>

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

</mapper>

测试

SqlSession:代表Java程序和数据库之间的会话。(HttpSession是Java程序和浏览器之间的会话)
SqlSessionFactory:是“生产”SqlSession的“工厂”。
工厂模式:如果创建某一个对象,使用的过程基本固定,那么我们就可以把创建这个对象的相关代码封装到一个“工厂类”中,以后都使用这个工厂类来“生产”我们需要的对象。

package com.daidai.test;

import com.daidai.dao.UserDao;
import com.daidai.domain.User;
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;
import java.util.List;

public class Test01 {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = new User();
        
		//@Accessors(chain = true) 可以支持链式调用        
        user.setUserId(1).setUserName("lisi").setUserPassword("000000");

        userDao.addUser(user);

        userDao.delUser(1);

        userDao.updUser(new User(2, "zhangsan", "00000"));

        List<User> userList = userDao.selAll();

        User selOneById = userDao.selOneById(2);

        for (User user1 : userList) {
            System.out.println(user);
        }
        System.out.println(selOneById);

    }
}
本文含有隐藏内容,请 开通VIP 后查看