1.mybatis-config文件解析
<?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 配置文件
settings mybatis设置
typeAliases 为Java类起别名
typeHandlers 类处理器
objectFactory 对象工厂
plugins 插件
environments 环境
transactionManager : 事务管理
dataSource : 数据源
mappers 映射器
优化我们的代码
优化配置文件
创建一个database.properties
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8
username = root
password = 123456
在mybatis核心配置文件中引入properties配置文件,并用${}表达式引入其中的值。
<configuration>
<!--配置文件修改-->
<properties resource="database.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/kuang/dao/userMapper.xml"/>
</mappers>
</configuration>
优化别名
注意点:位置必须正确
<!--配置别名-->
<typeAliases>
<!--配置指定类的别名-->
<typeAlias type="com.kuang.pojo.User" alias="User"/>
<!--
可以为一个包的所有类指定别名,这个别名为类名
com.kuang.pojo.User - > User
com.kuang.pojo.Student - > Student
-->
<package name="com.kuang.pojo"/>
</typeAliases>
优化完毕后我们在mapper映射文件中就可以使用别名了
<?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对应Mapper接口的类,包名+类名-->
<mapper namespace="com.kuang.dao.UserDao">
<!--select标签的id对应映射接口的方法名字 resultType:返回结果的类型 中间就编写sql语句-->
<select id="selectUser" resultType="User">
select * from user
</select>
<select id="selectUserById" resultType="User">
select * from user where id = #{id}
</select>
<!--
我们需要接受一个自定义的对象(引用对象),需要设置parameterType,为参数类型
接受这个对象的值,直接使用 #{对象字段名}
-->
<insert id="addUser" parameterType="User">
insert into user(id ,name, pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="deleteUserByID" parameterType="int">
delete from user where id = #{id}
</delete>
<update id="updateUser" parameterType="User">
update user set name =#{name},pwd = #{pwd} where id = #{id}
</update>
</mapper>
环境配置
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
映射器
- resource 【推荐】
- url
- class
- package
【推荐使用】
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>