4、配置文件

4.1、properties(资源文件)

之前我们的jdbc的连接参数都是写在db.properties文件中的,在mybatis中我们也可以这样做.

在src下建立db.properties文件

db.driverClassName=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
db.username=jz
db.password=jz

同时修改我们的全局配置文件(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>
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driverClassName}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/luke/dao/UserMappper.xml"></mapper>
    </mappers>
</configuration>

随便拿一个测试程序测试一下,测试通过

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 579447973.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@2289aca5]
DEBUG - ==>  Preparing: select count(*) from tb_user
DEBUG - ==> Parameters: 
DEBUG - <==      Total: 1
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@2289aca5]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@2289aca5]
DEBUG - Returned connection 579447973 to pool.
4

4.2、驼峰命名

在前面的讲解中,当我们遇到数据库字段和实体类名称不一致时,采用的是别名方式,这里我们也可以通过设置驼峰命名来解决

小知识:

经典数据库的命名规则: 多个单词之间使用下划线分割 例如:user_name
java 经典命名规则:驼峰样式,多个单词,后续的单词首字母大写 例如:userName;
开启驼峰匹配:相当于去掉数据库名字中的下划线,然后在与 java 中的属性名进行对应

添加配置,并且修改映射文件中的sql语句

<properties resource="db.properties"/>
<settings>
  	<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

修改映射文件

<select id="queryAllUser" resultType="com.luke.pojo.User">
        select USERID,
                USER_NAME,
                PWD,
                AGE,
                SEX,
                BIRTHDAY
        from tb_user
</select>

测试:

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1107204185.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@41fe9859]
DEBUG - ==>  Preparing: select USERID, USER_NAME, PWD, AGE, SEX, BIRTHDAY from tb_user
DEBUG - ==> Parameters: 
DEBUG - <==      Total: 4
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@41fe9859]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@41fe9859]
DEBUG - Returned connection 1107204185 to pool.
User [userid=1, userName=张三, pwd=123456, age=10, sex=男, birthday=Tue Apr 20 09:43:59 CST 2021]
User [userid=2, userName=李四, pwd=123456, age=10, sex=男, birthday=Tue Apr 20 09:43:59 CST 2021]
User [userid=3, userName=王五, pwd=123456, age=10, sex=男, birthday=Tue Apr 20 09:43:59 CST 2021]
User [userid=4, userName=赵六, pwd=123456, age=10, sex=男, birthday=Tue Apr 20 09:43:59 CST 2021]

4.3、typeAliases

在之前的Mapper.xml文件中我们发现,我们在配置文件中写了大量的package.className,比如

<?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">
<!--
   namespace:命名空間 (保证唯一)
-->
<mapper namespace="com.luke.pojo.User">
    <insert id="insertUser" parameterType="com.luke.pojo.User">
        insert into tb_user (userid,user_name,pwd,age,sex,birthday)
        values(seq_user.nextval,#{userName},#{pwd},#{age},#{sex},#{birthday})
    </insert>


    <update id="updateUser" parameterType="com.luke.pojo.User">
        update tb_user set user_name=#{userName},pwd=#{pwd},age=#{age},sex=#{sex},birthday=#{birthday}
        where userid=#{userid}
    </update>

    <delete id="deleteUserById" parameterType="long">
        delete from tb_user where userid=#{userid}
    </delete>

    <select id="selectCount" resultType="int">
        select count(*) from tb_user
    </select>

    <select id="queryAllUser" resultType="com.luke.pojo.User">
        select USERID,
                USER_NAME,
                PWD,
                AGE,
                SEX,
                BIRTHDAY
        from tb_user
    </select>

    <select id="queryUserById" resultType="com.luke.pojo.User">
        select  USERID,
                USER_NAME,
                PWD,
                AGE,
                SEX,
                BIRTHDAY
        from tb_user where userid = #{userid}
    </select>
</mapper>

这里我们就可以通过typeAliases来进行对配置文件作简化操作, 接下来我们在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>

    <properties resource="db.properties"></properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--设置别名-->
    <typeAliases>
        <typeAlias type="com.luke.pojo.User" alias="User"></typeAlias>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driverClassName}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/luke/dao/UserMappper.xml"></mapper>
    </mappers>
</configuration>

接下来我们修改UserMapper.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">
<!--
   namespace:命名空間 (保证唯一)
-->
<mapper namespace="com.luke.pojo.User">
    <insert id="insertUser" parameterType="User">
        insert into tb_user (userid,user_name,pwd,age,sex,birthday)
        values(seq_user.nextval,#{userName},#{pwd},#{age},#{sex},#{birthday})
    </insert>


    <update id="updateUser" parameterType="User">
        update tb_user set user_name=#{userName},pwd=#{pwd},age=#{age},sex=#{sex},birthday=#{birthday}
        where userid=#{userid}
    </update>

    <delete id="deleteUserById" parameterType="long">
        delete from tb_user where userid=#{userid}
    </delete>

    <select id="selectCount" resultType="int">
        select count(*) from tb_user
    </select>

    <select id="queryAllUser" resultType="User">
        select USERID,
                USER_NAME,
                PWD,
                AGE,
                SEX,
                BIRTHDAY
        from tb_user
    </select>

    <select id="queryUserById" resultType="User">
        select  USERID,
                USER_NAME,
                PWD,
                AGE,
                SEX,
                BIRTHDAY
        from tb_user where userid = #{userid}
    </select>
</mapper>

但是以上方式也有缺点,我们的实体类也会出现很多,此时我们通过扫描包的方式进行注册

<typeAliases>
        <!--单一配置
        <typeAlias type="com.luke.pojo.User" alias="User"></typeAlias>
        -->
        <package name="com.luke.pojo"></package>
</typeAliases>

每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为 author;若有注解,则别名为其注解值.

@Alias("hello")
public class User implements Serializable {

注意扫包配置不要删除。

在mybatis中,内置了一些别名,以上这些大家自己查阅文档即可

别名 映射的类型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

4.4、类型处理器(typeHandlers)

类型处理器是在设置参数,以及从result中检索值来匹配java数据类型,MyBatis提供了非常多的默认类型处理器,满足我们的开发要求。不需要咱们自定义,这里大家了解即可。

4.5、environments

开发环境:开发人员日常开发的时候使用的环境
测试环境:测试人员测试的时候使用环境
预发布环境:几乎和线上环境一模一样,在上线之前在进行一次测试。
生成环境:线上环境。正式的 java 程序运行的环境

MyBatis允许配置多个环境,比如说开发环境,测试环境,生成环境,但是在构建SqlSessionFactory时只能选择一个,虽然这种方式也可以做到很方便的分离多个环境,但是在实际场景下我们是更多的使用Spring来管理数据源,做到环境的分离

4.6、Mapper映射器

既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要定义 SQL 映射语句了。但是首先我们需要告诉 MyBatis 到哪里去找到这些语句。 Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的 URL),或类名和包名等。例如:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

一般情况下使用resource或者package方式。

4.7、生命周期与作用域

SqlSessionFactoryBuilder:这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

SqlSessionFactory:SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式

SqlSession:每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。

posted @ 2021-04-21 10:57  Mirindasky  阅读(119)  评论(0编辑  收藏  举报