1

image.png

<?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>

    <!--引入jdbc.properties文件,此后可以使用${key}的方式来访问value-->
    <properties resource="jdbc.properties"/>

    <!--
        设置别名的标签,为某个具体的类型来设置一个别名,在mybatis配置文件的范围中,来表示一个具体的类型
        mybatis核心配置文件必须按指定的顺序配置
        type=""需要起别名的类型
        alias 表示别名的名字
    -->
    <typeAliases>
        <!--<typeAlias type="com.huawei.mybatis.pojo.User" alias="uerMapperAliase"></typeAlias>-->
        <!--或者 若不设置alias,当前的别名拥有类型的别名,即类名且不区分大小写-->
        <!-- <typeAlias type="com.huawei.mybatis.pojo.User"></typeAlias>-->
        
        <!--以包的方式来写别名-->
        <!--通过包来设置类型别名,指定包下所有的类型拥有默认的别名,即类名且不区分大小写-->
        <package name="com.huawei.mybatis.pojo"/>
    </typeAliases>

    <!--
        配置连接数据库的环境
        default="" 设置默认使用环境的id
    -->
    <environments default="development">
        <!--
            environment 设置一个具体的连接数据库的环境
            id 设置环境的唯一标识不能重复
        -->
        <environment id="development">
            <!--
                transactionManager 设置事务管理器
                type 设置事务的管理方式
                type="JDBC"  使用JDBC原生的事务管理方式
                type="MANAGED" 表示被管理,例如Spring
            -->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--
                    dataSource 设置数据源
                    type="" 表示设置数据源的类型
                    type="POOLED" 表示使用数据库连接池
                    type="UNPOOLED" 表示不使用数据库连接池,每次连接重新创建连接池
                    type="JNDI" 表示使用上下文的数据源
                -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jsbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>

        <environment id="test">
            <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="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--引入mybatis的映射文件-->
    <mappers>
        <!--<mapper resource="mappers/UserMapper.xml"/>-->

        <!--
            通过包来引入映射文件,必须满足两个条件:
            1.mapper接口和映射文件所在的包必须一致
            2.mapper接口的名字和映射文件的名字必须一致
        -->
        <package name="com.huawei.mybatis.mapper"/>
    </mappers>
</configuration>

image.png

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

image.png
package com.huawei.mybatis.pojo;

public class User {

private Integer id;

private String username;

private  String password;

private Integer age;

private String gender;

private String email;

public User() {
}

public User(Integer id, String username, String password, Integer age, String gender, String email) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.age = age;
    this.gender = gender;
    this.email = email;
}

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 getPassword() {
    return password;
}

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

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

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

}

image.png

package com.huawei.mybatis.mapper;

import com.huawei.mybatis.pojo.User;

import java.util.List;

public interface UserMapper {
    /**
     * 添加用户信息
     * @return
     */
    int insertUser();

    /**
     * 修改用户信息
     * @return
     */
    int updateUser();

    /**
     * 删除用户信息
     */
    void deleteUser();

    /**
     * 根据用户id查询用户信息
     */
    User getUserById();

    /**
     * 查询所有用户信息
     */
    List<User> getAllUser();

}

image.png

<?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.huawei.mybatis.mapper.UserMapper">
    <!--
        mapper接口和映射文件要保持一致:
        1.mapper接口的全类名要和namespace保持一致
        2.mapper接口的方法名要和映射文件的id保持一致
    -->

    <!-- int insertUser(); -->
    <insert id="insertUser">
        insert into t_user values(null,'admin','123','23','男','12345@qq.com')
    </insert>

    <!--int updateUser();-->
    <update id="updateUser">
        update t_user set username='zhj',password='456' where id = 3
    </update>

    <!--void deleteUser();-->
    <delete id="deleteUser">
        delete from t_user where id = 3
    </delete>

    <!--User getUserById();-->
    <!--
    resultType 设置结果类型,查询的结果要转换的Java类型
    resuleMap 自定义类型,处理一对多或多对一的映射关系
    -->
    <select id="getUserById" resultType="com.huawei.mybatis.pojo.User">
        select * from t_user where id = 2
    </select>

    <!--List<User> getAllUser();-->
    <!--<select id="getAllUser" resultType="com.huawei.mybatis.pojo.User">-->
    <!--使用别名的方式-->
    <!--<select id="getAllUser" resultType="uerMapperAliase">-->
    <!--不写alias 使用不区分大小写类型来做别名-->
    <select id="getAllUser" resultType="User">
        select * from t_user
    </select>

</mapper>

image.png

package com.huawei.mybatis.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 SqlSessionUtil {
    public static SqlSession getSqlSession(){
        SqlSession sqlSession= null;
        try {
            // 获取核心配置文件的输入流
            InputStream inputStream=  Resources.getResourceAsStream("mybatis-config.xml");
            // 获取sqlSessionFactoryBuilder
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            // 获取sqlSessionFactory
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            // 获取
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }
}

image.png

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <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">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

image.png

package com.huawei.mybatis.test;

import com.huawei.mybatis.mapper.UserMapper;
import com.huawei.mybatis.pojo.User;
import com.huawei.mybatis.utils.SqlSessionUtil;
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 org.junit.Test;

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

public class MybatisTest {

    @Test
    public void testInsert() throws IOException {
        //获取核心配置文件的输入流
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //获取执行sql语句的对象 sqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        //获取sql的会话对象sqlSession,是mybatis提供的操作数据库的对象

        //设置自动提交事务
        SqlSession sqlSession =  sqlSessionFactory.openSession(true);
        // SqlSession sqlSession =  sqlSessionFactory.openSession();

        //获取UserMapper的代理实现类对象
        UserMapper userMapper  = sqlSession.getMapper(UserMapper.class);
        //调用userMapper接口的方法,实现用户新增的功能
        int result = userMapper.insertUser();
        System.out.println("结果:"+result);

        //这种实现方式需要自己提交事务
        // sqlSession.commit();

        //关闭sqlSession的会话
        sqlSession.close();
    }

    @Test
    public void testUpdate(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser();
        sqlSession.close();
    }

    @Test
    public void deleteUpdate(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUser();
        sqlSession.close();
    }

    @Test
    public void testGetUserById(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById();
        System.out.println(user);
    }

    @Test
    public void testGetAllUser(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getAllUser();

        // userList.forEach(x->{System.out.println(x);});
        userList.forEach(System.out::println);
        System.out.println("结果:" + userList);
    }


}

image.png


周周架构师
292 声望409 粉丝