Mybatis在持久层的一些配置及操作

一.在一个web项目里建立多个模块,多模块项目的初步了解

  • 从maven原型搭建项目
  • 父项目pom.xml的配置
  • 子模块的Dao层的Mybatis的使用

1.解析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>
	<!--唯一项目ID-->
    <groupId>org.example</groupId>
    <artifactId>mybatis</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <!--子模块-->
    <modules>
        <module>demo01</module>
    </modules>
	
    <properties>
        <maven.compiler.source>15</maven.compiler.source>
        <maven.compiler.target>15</maven.compiler.target>
    </properties>
    <!--项目依赖-->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
            </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
              <groupId>org.slf4j</groupId>
              <artifactId>slf4j-simple</artifactId>
              <version>1.7.25</version>
              <scope>compile</scope>
        </dependency>

    </dependencies>
    <!--解决无法读取java包中资源的问题-->
    <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>

</project>

2.子模块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">
    <!--继承父类依赖-->
    <parent>
        <artifactId>mybatis</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>demo01</artifactId>
    <dependencies>
        <dependency>
            <groupId>io.ktor</groupId>
            <artifactId>ktor-utils-jvm</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>15</maven.compiler.source>
        <maven.compiler.target>15</maven.compiler.target>
    </properties>
    <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>
</project>

3.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>
	<!--dafault可以换成别的,环境可以配置多个,主要用于切换数据库-->
    <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/mybatis?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false "/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
	<!--需要写出配置中所有的Mapper全类名,一定要用"/"分隔-->
    <mappers>
        <mapper resource="com/demo/dao/UserMapper.xml"/>
    </mappers>

</configuration>

这个配置相当于JDBC中的获取驱动后链接数据库获取Connection

4.子模块的Dao层的Mybatis的使用

  • 构建dao接口操作数据业务
public interface UserMapper {
    //查询全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //插入用户
    void addUser(User user);
    //修改用户
    void upDateUser(Map<String,Object> map);
    //删除用户
    void deleteUser(int id);
}
  • 建立对应的Mapper.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="com.demo.dao.UserMapper">
	<!--id表示对应接口中定义的方法,resultType表示对应Mapper操纵sql所产生的结果集类型-->
    <select id="getUserList" resultType="com.demo.pojo.User">
        select * from mybatis.user;
    </select>
    <!--parameterType表示需要传入参数的类型,映射到接口方法的参数,类似于JDBC中的通配符--->
    <select id="getUserById" resultType="com.demo.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id};
    </select>
    <insert id="addUser" parameterType="com.demo.pojo.User">
        insert into mybatis.user(id, name, pwd) VALUES (#{id},#{name},#{pwd});
    </insert>
    <update id="upDateUser" parameterType="Map">
        update mybatis.user set name=#{userName},pwd=#{password} where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id};
    </delete>

</mapper>

注意 在模糊查询中如

select * from Table where name like "%#{S}%"

模糊查询 name中含有S的行

  • 获取sqlSession的标准化方法
package com.demo.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 {
        InputStream resourceAsStream = null;
        try {
            //从config XML文件中获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            resourceAsStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resourceAsStream != null) {
                    resourceAsStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (resourceAsStream != null) {
                    resourceAsStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

上一篇:Java JDBC 编程指北


下一篇:mybatis快速入门