Java教程

MyBatis01——初始mybatis

本文主要是介绍MyBatis01——初始mybatis,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、简介:

 Github:https://github.com/mybatis/mybatis-3/releases

中文文档::https://mybatis.org/mybatis-3/zh/index.html
 

储备知识:mysql 数据库知识:建库、建表、增删改查、事务、范式等。

https://blog.csdn.net/qq_33369905/article/details/105828923?spm=1001.2014.3001.5502

二、我的第一个mybatis

1.创建maven项目后,pom.xml配置修改

(1)记得要检查一下settings是不是自己的仓库,有时候会默认m2.

(2)导入依赖,配置环境和资源文件

(3)maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:按照下面代码那样加<resource>引用

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


 <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="POOLED">
<!--    POOLED-连接池    <properties>    读取外部文件的配置信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useSLL=true&amp;useUnicode=true&amp;characterEncoding-UTF-8&amp;serverTimezone=GMT%2B8"/>
                <!--填写你的数据库用户名-->
                <property name="username" value="root"/>
                <!--填写你的数据库密码-->
                <property name="password" value="qwer1234"/>
            </dataSource>
        </environment>
    </environments>

<!-- 项目管理 maven只会打包resource里面的文件,如果文件不放在resource里面,需要通过配置通知maven -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
 </build>

2.maven删去src即为一个父工程,在父工程就可以new Module 创建子工程了,回顾maven知识体系架构(待续.....)

这样子的话,子项目就可以不用修改pom.xml直接使用到父项目的pom.xml配置了。

maven学习资源:Maven零基础入门教程(一套轻松搞定maven工具)_哔哩哔哩_bilibili

3.按照标准的目录结构创建子项目

(1)src/main/java和src/test/java 

这两个目录中的所有*.java文件会分别在comile和test-comiple阶段被编译,编译结果分别放到了target/classes和targe/test-classes目录中,但是这两个目录中的其他文件都会被忽略掉。     

(2)src/main/resouces和src/test/resources

这两个目录中的文件也会分别被复制到target/classes和target/test-classes目录中。

(3)target/classes

打包插件默认会把这个目录中的所有内容打入到jar包或者war包中

我们的方法类和实体类放在java文件里,而mybatis的核心文件mybatis-config.xml放在resources文件,test测试文件应与Java文件一致  ,例如:·

 

4.在resources包创建mybatis核心配置文件:mybatis-config.xml  关键的如下:

a.配置环境文件,设置连接池

b.引用映射文件,即mapper.xml,在代码的最下面<mappper>里设置,这个点容易忘记导致报错!!!!

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

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="POOLED">
<!--    POOLED-连接池    <properties>    读取外部文件的配置信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useSLL=true&amp;useUnicode=true&amp;characterEncoding-UTF-8&amp;serverTimezone=GMT%2B8"/>
                <!--填写你的数据库用户名-->
                <property name="username" value="root"/>
                <!--填写你的数据库密码-->
                <property name="password" value="qwer1234"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
<!-- 添加StudentMapper.xml映射文件路径的配置,用于将StudentMapper.xml映射文件加载到程序中  -->
<!--        <mapper resource="com/mapper/StudentMapper.xml"/>-->
        <package name="com.lcr.dao"/>
    </mappers>
</configuration>

5.在entity包关系型数据能够被封装成Java对象(全文以student为对象实例),在dao包里创建接口类.java        

public interface StudentMapper {
    //查询所有学生
    List<Student> selectAll();
    //查询某一学生
    Student getStudentById(int id);
    //插入一个学生
    int insertStudent(Student std);
    //修改学生
    int updateStudent(Student std);
    //删除学生
    int deleteStudent(int id);
}

 

6.与接口类通缉的dao包下创建"映射文件.xml"实现SQL语句和Java对象之间的映射,使SQL语句查询出来的关系型数据能够被封装成Java对象,关键点如下:

a.名空间为接口类的全路径

b.sql语句的 id = 接口类的方法名

c. parameterType是传入参数,resultType是返回参数,参数数据类型多样,但增删改返回的resultType固定为int类型

d.对于模糊查询,最好在sql使用通配符

<mapper namespace="com.lcr.dao.StudentMapper">

     <select id="selectAll" parameterType="int" resultType="com.lcr.entity.Student">
        select * from test.student
     </select>

    <select id="getStudentById" parameterType="int" resultType="com.lcr.entity.Student">
        select * from student where student_id = #{id}
    </select>

    <insert id="insertStudent" parameterType="com.lcr.entity.Student" >
        insert into test.student(name,sex) values(#{name},#{sex})
    </insert>

    <insert id="insertStudent2" parameterType="map" >
        insert into test.student(name,sex) values(#{name},#{sex})
    </insert>

    <update id="updateStudent" parameterType="com.lcr.entity.Student">
        update test.student set name=#{name},phone=#{phone} where student_id=#{studentId};
    </update>

    <delete id="deleteStudent" parameterType="int">
        delete from test.student where student_id = #{id}
    </delete>

</mapper>

7.实现方法,在测试中调用 

(1)在此之前,先在utils包下建一个数据库的工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //读取配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

 (2)以下是测试类的一个增删改查例子,关键点如下:

a.开启一个事务需要用到utils的创建方法,按照官方文档的创建形式来的

b. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);    getMapper是一个常用的调用接口类的方法,直接获取到 StudentMapper接口类的方法

c.  事务启动后一定要提交事务!    一定要关闭!       sqlSession.commit();          sqlSession.close();


public class StudentMapperTest {
    //增删改查
    @Test
    public void getStudentById() {
        //开启一个事务,开启事务实现类在工具类utils
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //查询某一学生
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student  student = studentMapper.getStudentById(2);
        sqlSession.close();
    }

    @Test
    public  void insertStudent2(){
        //使用map作为自定义参数组,避免使用POJO的时候参数太多
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("newName","cwg");
        map.put("newSex",true);
        studentMapper.insertStudent2(map);
        sqlSession.commit();
        sqlSession.close();

    }

    }
}

小结:

以上就是基础mybatis的使用,其中涉及到maven项目创建,mysql数据库原理SpringMVC简单使用、最重要的是配置文件操作的难点和重点,下一篇将重点学习mybatis的配置属性。

// 待解决问题:
void rollback() 回滚事务是啥?
 数据库的时间戳属性不能正常读出为什么?​

这篇关于MyBatis01——初始mybatis的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!