三大框架之Mybatis总结
1. Mybatis是什么?
Mybatis是一个支持定制化动态sql语句,使用映射解析xml文件实现功能,减少java代码,降低耦合性,以及使用其逆向工程的生成简单的DAO和javabean,多功能高效半自动化的针对数据库持久层的集合框架.其特点具有轻量级,高效性,优化性,自动开启事务,xml映射.
2. 搭建Mybatis运行环境
需要导入jar包:
log4j-1.2.17.jar 配合mybatis使用的日志jar包,方便我们对代码的运行过程了解
mybatis-3.4.1.jar mybatis的核心框架jar包,包含封装好的mybatis功能方法
mysql-connector-java-5.1.7-bin.jar 配合java数据接口的mysql数据库实现类驱动
添加配置文件:
mybatis-config.xml 使用mybatis的环境设置
log4j.properties 使用日志的环境配置
UserMapper.xml 对于mybatis来说xml是核心实现业务操作的文件
3配置xml文件的分析
mybatis-config.xml 使用mybatis的环境设置
<?xml version=*"1.0"* encoding=*"UTF-8"* ?>文档类型
环境配置文件根标签(xml中必须设置根标签)
环境标签 根据不同的人员设置,我们开发人员一般就是开发环境
<environments default=“development”>
<environment id=“development”>
事务管理器,一般默认类型JDBC即为开启事务
<transactionManager type=“JDBC” />
<!-- dataSource 数据源
POOLED 表示使用数据库连接池
-->
<dataSource type=“POOLED”>
<property name=“driver” value=“com.mysql.jdbc.Driver” />
<property name=“url” value=“jdbc:mysql://localhost:3306/mybatis” />
<property name=“username” value=“root” />
<property name=“password” value=“root” />
每个环境配置,使用时必须配置好所需的mapper.xml的实现文件
<mapper resource=“com/atguigu/pojo/UserMapper.xml” />
log4j.properties 使用日志的环境配置
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output…
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
UserMapper.xml 对于我们使用mybatis来说Mapper.xml是核心实现业务操作的文件
<?xml version=*"1.0"* encoding=*"UTF-8"* ?><mapper namespace=“com.atguigu.pojo.User”>
<!–
select 定义select查询语句
id 给你要定义的sql语句,设置一个唯一的id值。
resultType 查询完返回的类型
#{id} 这是一个占位符
-->
<select id=“selectUserById” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user where id = #{id}
<!–
id 定义一个唯一标识
resultType 定义查询返回的类型
-->
<select id=“queryUsers” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user
<!–
delete标签定义delete语句
parameterType 设置参数的类型(可选)
-->
<delete id=“deleteUserById” parameterType=“int”>
delete from t_user where id = #{id}
<!–
update标签定义一个update语句
-->
<update id=“updateUser” parameterType=“com.atguigu.pojo.User”>
update t_user set last_name = #{lastName},sex = #{sex} where id = #{id}
<!–
insert标签定义insert语句
-->
<insert id=“saveUser” parameterType=“com.atguigu.pojo.User”>
insert into t_user(last_name
,sex
) values(#{lastName},#{sex})
配置mybatis配置文件的提示:
Config 文件的key: http://mybatis.org/dtd/mybatis-3-config.dtd
mapper文件的key: http://mybatis.org/dtd/mybatis-3-mapper.dtd
4.Mapper接口方式的mybatis的规范
4.1、Mapper接口编程的命名习惯
一般你的实体bean对象叫 User
你的接口叫 UserMapper
你的配置文件命名,一般也叫 UserMapper.xml
4.2、Mapper接口开发有四个开发规范*必须遵守*
1、mapper.xml配置文件的名称空间,必须是接口的全类名
2、mapper.xml配置文件中sql语句的id定义的值。必须跟方法名一致。
3、mapper.xml配置文件,参数类型必须和方法的参数类型一致(建议略写)。
4、mapper.xml配置文件,返回类型必须与接口方法的返回值类型一致。
5.mybatis的核心配置
5.1****properties
mybatis-config.xml配置文件
需要有一个单独的jdbc.properties属性配置文件
5.2s****ettings
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。下表描述了设置中各项的意图、默认值等
5.3****typeAliases
类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。系统提示的预定义别名
已经为许多常见的 Java 类型内建了相应的类型别名。它们都是大小写不敏感的,需要注意的是由基本类型名称重复导致的特殊处理
5.4****typeHandlers
类型处理器
Environments
5.5****environments
可以配置多个数据库环境default属性表示默认使用哪个环境
environment可以配置一个数据库环境 id 定义这个数据库环境的唯一标识
5.6****transactionManager
标签说明
在 MyBatis 中有两种类型的事务管理器(也就是 type=”[JDBC|MANAGED]”):
JDBC – 这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务范围。
MANAGED – 这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。这两种事务管理器类型都不需要任何属性。它们不过是类型别名,换句话说,你可以使用 TransactionFactory 接口的实现类的完全限定名或类型别名代替它们。
Spring + MyBatis,没有必要配置事务管理器, 因为 Spring 模块会使用自带的管理器来覆盖前面的配置。
5.7****dataSource
标签说明
type 属性的值有三种: UNPOOLED 、 POOLED 。自定义(实现DataSourceFactory接口)
有三种内建的数据源类型(也就是 type=”[UNPOOLED|POOLED|JNDI]”):
UNPOOLED– 这个数据源的实现只是每次被请求时打开和关闭连接。虽然一点慢,它对在及时可用连接方面没有性能要求的简单应用程序是一个很好的选择。 不同的数据库在这方面表现也是不一样的,所以对某些数据库来说使用连接池并不重要,这个配置也是理想的。UNPOOLED 类型的数据源仅仅需要配置以下
POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这是一种使得并发 Web 应用快速响应请求的流行处理方式。
如果需要自定义数据库连接池,需要实现通过需要实现接口 org.apache.ibatis.datasource.DataSourceFactory接口
5.8****databaseIdProvider
MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。 MyBatis 会加载不带 databaseId 属性和带有匹配当前数据库 databaseId 属性的所有语句。mybatis提供了一个类VendorDatabaseIdProvider,中的getDatabaseId() 方法用于获取数据库的标识。
property 标签name属性是获取数据库ID标识。
property 标签value属性是我们给mybatis定义的一个简短的标识。
5.9Mapper
设置导入mapper方式一
设置导入mapper方式二
只用url去引入mapper的.xml文件
<!-- 按照指定的包名去搜索,所有mapper配置文件
注意:
1、你的接口名和mapper配置文件名,要一致
2、你的mapper接口和mapper配置文件必须在同一个包下
-->
**6.**MyBatis的注解使用方式(了解。主要使用xml)
public interface UserMapper {
@SelectKey(before = false, statement = “select last_insert_id()”, keyProperty = “id”, resultType = Integer.class)
@Insert(value = “insert into t_user(last_name
,sex
) values(#{lastName},#{sex})”)
public int saveUser(User user);
@Select(value = “select id,last_name lastName,sex from t_user where id = #{id}”)
public User queryUserById(int id);
7. mybatis的参数传递
7.1 一****个普通数据类型
推荐使用#{变量名}(优先) 或 #{value}
方法:
public User queryUserById(int id);
在xml中传递参数值的使用方法:
select id
,last_name
lastName,sex
from t_user where id = #{id}
7.2 多个普通数据类型
在方法的参数是多个普通数据类型的情况,传递的参数的方式是使用#{ param1 }、#{param2} ……
第一个参数使用#{param1}传递
第二个参数使用#{param2}传递
第三个参数使用#{param3}传递
……
第N个,参数使用#{paramN}传递
代码方法是:
public List queryUsersByNameAndSex(String name, int sex);
在xml中传递参数值的使用方法:
<select id=“queryUsersByNameAndSex” resultType=“com.atguigu.pojo.User”>
select id
,last_name
lastName,sex
from t_user where last_name like #{param1} and sex = #{param2}
7.3 @Param注解命名参数
代码中:
public List queryUsersByNameAndSex(@Param(“name”) String name,
@Param(“sex”) int sex);
在xml中传递参数如下:
<select id=“queryUsersByNameAndSex” resultType=“com.atguigu.pojo.User”>
select id
,last_name
lastName,sex
from t_user where last_name like #{name} and sex = #{sex}
7.4 传递一个Map对象作为参数
当代码中以map做为参数值传递。
Map<String, Object>param = new HashMap<String, Object>();
param.put(“name”, “%bbb%”);
param.put(“sex”, 1);
那么在xml中配置的时候,以#{mapKey}的方式输出参数值。
代码:
public List queryUsersByMap(Map<String, Object> param);
xml中如何输入map中参数的值:
<select id=“queryUsersByMap” resultType=“com.atguigu.pojo.User”>
select id
,last_name
lastName,sex
from t_user where last_name like #{name} and sex = #{sex}
7.5 一个Pojo数据类型
如果传入的参数是pojo数据类型(javaBean对象)。那么在xml中使用#{属性名}
代码中:
public List queryUsersByUser(User user);
在xml配置文件中:
<select id=“queryUsersByUser” resultType=“com.atguigu.pojo.User”>
select id
,last_name
lastName,sex
from t_user where last_name like #{lastName} and sex = #{sex}
7.6多个Pojo数据类型
如果参数是传入多个pojo对象。
第一个pojo对象,使用 param1表示
要输出第一个pojo对象的属性#{ param1.property }
第二个pojo对象,使用param2表示
要输出第一个pojo对象的属性#{ param2.property }
代码:
public List queryUsersByUsers(User name, User sex);
在xml中的配置是:
<select id=“queryUsersByUsers” resultType=“com.atguigu.pojo.User”>
select id
,last_name
lastName,sex
from t_user where last_name like #{param1.lastName} and sex = #{param2.sex}
7.7模糊查询
需求:现在要根据用户名查询用户对象。 也就是希望查询如下: select * from t_user where user_name like ‘%张%’#{}和${}的区别
#{} 是占位符 ?
xml中的配置:
select id
,last_name
lastName,sex
from t_user where last_name like #{name}
解析后的sql语句是:
select id
,last_name
lastName,sex
from t_user where last_name like ?
${} 是原样输出参数的值。然后做字符串的拼接操作。
xml中的配置:
select id
,last_name
lastName,sex
from t_user where last_name like ‘${name}’
解析后的sql语句是:
select id
,last_name
lastName,sex
from t_user where last_name like ‘%bbbb%’
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-umVfSo3v-1573718292251)(file:///C:\Users\尚硅谷\AppData\Local\Temp\ksohtml61712\wps1.jpg)]
MySQL的字符串拼接,concat函数实现。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vz8hrvjs-1573718292252)(file:///C:\Users\尚硅谷\AppData\Local\Temp\ksohtml61712\wps2.jpg)]
代码中:
public List queryUsersByName(@Param(“name”)String name);
xml中的配置推荐:
<select id=“queryUsersByName” resultType=“com.atguigu.pojo.User”>
select id
,last_name
lastName,sex
from t_user where last_name like concat(’%’,#{name},’%’)
8自定义结果集****
8.1的作用。
原来我们查询都是返回一个简单的JavaBean对象。我们可以直接使用ResultType定义返回在的类型。
但是如果我们查询的结果返回在的JavaBean中,又包含一个javaBean,或者包含一个javaBean对象的集合。
那么这个时候,只能使用ResultMap来自定义返回的结果。
8.2一对一 级联属性 使用
创建KeyMapper接口
public interface KeyMapper {
public Key queryKeyByIdForSample(int id);
}
创建KeyMapper.xml配置文件:
<?xml version=*"1.0"* encoding=*"UTF-8"* ?><mapper namespace=“com.atguigu.dao.KeyMapper”>
<!-- resultMap标签可以自定义结果集。定义成你需要的bean对象的结果
type属性表示当前这个ResultMap会封装什么对象返回
id 属性定义一个唯一的标识,方便别人使用。
-->
<resultMap type=“com.atguigu.pojo.Key” id=“queryKeyByIdForSample_resultMap”>
<!–
id专门用来映射id主键列
-->
<id column=“id” property=“id”/>
<!–
result标签映射非主键列
-->
<result column=“name” property=“name”/>
<result column=“lock_id” property=“lock.id”/>
<result column=“lock_name” property=“lock.name”/>
<!–
当前select查询,结果是 resultMap所指向的id对应的resultMap集合
-->
<select id=“queryKeyByIdForSample” resultMap=“queryKeyByIdForSample_resultMap”>
select
t_key.*,t_lock.name lock_name
from
t_key left join t_lock
on
t_key.lock_id = t_lock.id
where
t_key.id = #{id}
8.3 嵌套结果集映射配置
<resultMap type=“com.atguigu.pojo.Key” id=“queryKeyByIdForSample_resultMap2”>
<!–
id专门用来映射id主键列
-->
<id column=“id” property=“id”/>
<!–
result标签映射非主键列
-->
<result column=“name” property=“name”/>
<!-- association 标签专门 映射Bean对象中的子对象(一个Bean)
专门用来配置一对一标签
-->
<association property=“lock” javaType=“com.atguigu.pojo.Lock”>
<id column=“lock_id” property=“id”/>
<result column=“lock_name” property=“name”/>
8.4** 定义分步查询**
在KeyMapper接口中创建一个分步查询方法:
/*
* 一开始我只需要使用key表的信息,所以我只查key表的信息。
*
* 当我们使用时候需要用到key对象对应的Lock对象的信息的时候。我再查Lock的信息
*
*/
public Key queryKeyByIdForTwoStep(int id);
创建LockMapper接口
public interface LocKMapper {
public Lock queryLockById(int lockId);
}
在keyMapper.xml配置文件中:
<resultMap type=“com.atguigu.pojo.Key” id=“queryKeyByIdForTwoStep_resultMap”>
<id column=“id” property=“id”/>
<result column=“name” property=“name”/>
<!–
association 标签是推荐用来映射一对一关联
property是你要映射的子对象的变量名
javaType 表示你要映射的这个子对象的具体类型
select 属性表示你要执行的查询语句
column 属性设置你要传递给select设置的查询语句用的参数列
-->
<association property=“lock” javaType=“com.atguigu.pojo.Lock”
select=“com.atguigu.dao.LocKMapper.queryLockById” column=“lock_id”
/>
<select id=“queryKeyByIdForTwoStep” resultMap=“queryKeyByIdForTwoStep_resultMap”>
select id,name,lock_id from t_key where id = #{id}
创建LockMapper.xml配置文件内容如下:
<select id=“queryLockById” resultType=“com.atguigu.pojo.Lock”>
select id,name from t_lock where id = #{id}
8.5 延迟加载
延迟加载在一定程序上可以减少很多没有必要的查询。给数据库服务器提升性能上的优化。
要启用延迟加载,需要在mybatis-config.xml配置文件中,添加如下两个全局的settings配置。
<setting name=“lazyLoadingEnabled” value=“true” />
<setting name=“aggressiveLazyLoading” value=“false”/>
懒加载功能,mybatis3.2.8版本,需要同时引入两个jar包
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zPRCErFV-1573718292252)(file:///C:\Users\尚硅谷\AppData\Local\Temp\ksohtml61712\wps3.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y8S1qwot-1573718292252)(file:///C:\Users\尚硅谷\AppData\Local\Temp\ksohtml61712\wps4.png)]
8.6多对一、一对多的使用示例
一对多,立即加载
创建ClazzMapper接口
public interface ClazzMapper {
public Clazz queryClazzByIdForSample(int id);
}
编写ClazzMapper.xml配置文件:
<resultMap type=“com.atguigu.pojo.Clazz” id=“queryClazzByIdForSample_resultMap”>
<id column=“id” property=“id”/>
<result column=“name” property=“name”/>
<!–
collection 标签专门用来映射集合属性
property 表示你要映射的集合属性名是什么
-->
<collection property=“stuList” ofType=“com.atguigu.pojo.Student”>
<id column=“stu_id” property=“id”/>
<result column=“stu_name” property=“name”/>
<select id=“queryClazzByIdForSample” resultMap=“queryClazzByIdForSample_resultMap”>
select
t_clazz.*,t_student.id stu_id,t_student.name stu_name
from
t_clazz left join t_student
on
t_clazz.id = t_student.clazz_id
where
t_clazz.id = #{id}
一对多,懒加载
再创建一个StudentMapper接口
public interface StudentMapper {
public List queryStudentsByClazzId(int clazzId);
}
创建StudentMapper.xml配置文件:
<select id=“queryStudentsByClazzId” resultType=“com.atguigu.pojo.Student”>
select id,name from t_student where clazz_id = #{clazzid}
在ClazzMapper接口中添加一个方法实现懒加载
/**
* 我要分两次查询,
* 一次只查常用数据,班级信息
* 当我需要使用学生信息的时候。再查询一次
* 还要用到懒加载
*/
public Clazz queryClazzByIdForTwoStepLazy(int id);
在ClazzMapper.xml中进行配置:
<resultMap type=“com.atguigu.pojo.Clazz” id=“queryClazzByIdForTwoStepLazy_resultMap”>
<id column=“id” property=“id”/>
<result column=“name” property=“name”/>
<!–
collection 是专门映射集合的标签
property 属性设置你要设置和集合的属性名
ofType是 这个集合中每个元素的具体类型
select 是你要查询的语句
column 属性设置你要执行的select对应的查询语句需要的参数列
-->
<collection property=“stuList” ofType=“com.atguigu.pojo.Student”
select=“com.atguigu.dao.StudentMapper.queryStudentsByClazzId”
column=“id”
/>
<select id=“queryClazzByIdForTwoStepLazy” resultMap=“queryClazzByIdForTwoStepLazy_resultMap”>
select id,name from t_clazz where id = #{id}
双向关联
在StudentMapper接口中添加一个懒加载的方法:
public List queryStudentByClazzIdForLazy(int clazzId);
然后在StudentMapper.xml配置文件中
<resultMap type=“com.atguigu.pojo.Student” id=“queryStudentByClazzIdForLazy_resultMap”>
<id column=“id” property=“id”/>
<result column=“name” property=“name”/>
<association property=“clazz” javaType=“com.atguigu.pojo.Clazz”
select=“com.atguigu.dao.ClazzMapper.queryClazzByIdForTwoStepLazy”
column=“clazz_id”
/>
<select id=“queryStudentByClazzIdForLazy” resultMap=“queryStudentByClazzIdForLazy_resultMap”>
select id,name,clazz_id from t_student where clazz_id = #{clazzId}
还需要修改原来懒加载查询班级里,懒加载学生的select属性
<resultMap type=“com.atguigu.pojo.Clazz” id=“queryClazzByIdForTwoStepLazy_resultMap”>
<id column=“id” property=“id”/>
<result column=“name” property=“name”/>
<!–
collection 是专门映射集合的标签
property 属性设置你要设置和集合的属性名
ofType是 这个集合中每个元素的具体类型
select 是你要查询的语句
column 属性设置你要执行的select对应的查询语句需要的参数列
-->
<collection property=“stuList” ofType=“com.atguigu.pojo.Student”
select=“com.atguigu.dao.StudentMapper.queryStudentByClazzIdForLazy”
column=“id”
/>
8.7 双向关联
双向关联会有死循环出现!
如何防止双向关联呢?
1、不要调用toString方法
2、在你需要终止关联的时候,最后一次查询使用resultType
9.动态sql标签语句
9.1 if标签语句
说明: if语句,可以动态的根据你的值来决定,是否需要动态的添加查询条件。
代码:
public List queryUsersByNameAndSex(String name, int sex);
配置:
<select id=“queryUsersByNameAndSex” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user
where
<if test=“param1 != null”>
last_name like concat(’%’,#{param1},’%’)
<if test=“param2 == 1 || param2 == 0”>
and sex = #{param2}
9.2 where标签语句
说明: where语句,可以帮我们在多个动态语句中,有效的去掉前面的多余的and 或 or 之类的多余关键字
where标签,还只可以动态的判断中间是否包含查询条件。如果没有连where关键字也不会出现。
<select id=“queryUsersByNameAndSex” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user
<if test=“param1 != null”>
last_name like concat(’%’,#{param1},’%’)
<if test=“param2 == 1 || param2 == 0”>
and sex = #{param2}
9.3 trim标签语句
说明: trim 可以动态在包含的语句前面和后面添加内容。也可以去掉前面或者后面给定的内容
prefix 前面添加内容
suffix 后面添加内容
suffixOverrides 去掉的后面内容
prefixOverrides 去掉的前面内容
<select id=“queryUsersByNameAndSexTrim” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user
<!–
prefix 前面添加内容
suffix 后面添加内容
suffixOverrides 去掉的后面内容
prefixOverrides 去掉的前面内容
-->
<trim prefixOverrides=“and” suffixOverrides=“and”>
<if test=“param1 != null”>
last_name like concat(’%’,#{param1},’%’) and
<if test=“param2 == 1 || param2 == 0”>
sex = #{param2}
9.4 choose标签语句( when , otherwise )
说明:choose when otherwise 可以执行多路选择判断,但是只会有一个分支会被执行。
类似switch case 语句
方法代码:
public List queryUsersByNameAndSexChoose(String name, int sex);
xml中的配置:
<select id=“queryUsersByNameAndSexChoose” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user
<!-- 我们希望,如果name的值非空,只查询name
如果name的值非法,而sex的值合法。只查询sex
如果两个都不合法,都不要(或者你可以自己加一些查询条件)
-->
<when test=“param1 != null”>
last_name like concat(’%’,#{param1},’%’)
<when test=“param2 == 1 || param2 == 0”>
sex = #{param2}
sex = 0
9.5 set语句
删除条件后的逗号
代码:
public int updateUser(User user);
xml中的配置:
<update id=“updateUser” parameterType=“com.atguigu.pojo.User”>
update t_user
last_name = #{lastName} ,
<if test=“sex == 1 || sex == 0”>
sex = #{sex}
where id = #{id}
9.5 foreach语句
代码:
/**
* select * from t_user where id in(1,2,3,4,5)
*/
public List queryUsersByIds(List ids);
xml中的配置:
<select id=“queryUsersByIds” resultType=“com.atguigu.pojo.User”>
select id,last_name lastName,sex from t_user
id in
<!–
foreach标签用来遍历集合
collection遍历的数据源
open属性设置遍历的开始内容
close属性设置遍历的结束内容
item属性是当前遍历到的数据
separator属性设置遍历的每个元素之间的间隔符
-->
<foreach collection=“list” open="(" close=")" item=“i” separator=",">
#{i}
10 mybatis的逆向工程
10.1介绍逆向工程
MyBatis逆向工程,简称MBG。是一个专门为MyBatis框架使用者定制的代码生成器。可以快速的根据表生成对应的映射文件,接口,以及Bean类对象。
在Mybatis中,有一个可以自动对单表生成的增,删,改,查代码的插件。
叫 mybatis-generator-core-1.3.2。
它可以帮我们对比数据库表之后,生成大量的这个基础代码。
这些基础代码有:
数据库表对应的javaBean对象
这些javaBean对象对应的Mapper接口
这些Mapper接口对应的配置文件
10.2****创建一个Java工程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-INOwwBvN-1573718292253)(file:///C:\Users\尚硅谷\AppData\Local\Temp\ksohtml61712\wps5.jpg)]
导入以下jar包,逆向工程必须配合mybatis的jar包使用
log4j-1.2.17.jar
mybatis-3.4.1.jar
mybatis-generator-core-1.3.2.jar
mysql-connector-java-5.1.7-bin.jar
10.3准备 mybatis-generator-core 的配置文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GdX7rEfa-1573718292254)(file:///C:\Users\尚硅谷\AppData\Local\Temp\ksohtml61712\wps6.jpg)]
配置环境核心文件
<?xml version=*"1.0"* encoding=*"UTF-8"*?><context id=“DB2Tables” targetRuntime=“MyBatis3”>
<!-- 去掉全部的注释 -->
<property name=“suppressAllComments” value=“true” />
<!--
jdbcConnection 为数据库连接的四要素信息。
请修改成为你自己的内容
-->
<jdbcConnection driverClass=“com.mysql.jdbc.Driver”
connectionURL=“jdbc:mysql://localhost:3306/mbg”
userId=“root”
password=“root”>
<property name=“forceBigDecimals” value=“false” />
<!–
javaModelGenerator 生成表对应的javaBean
targetPackage 属性设置生成的类的包名
targetProject 属性设置生成的工程的路径 一般生成为当前工程。写为 .\
-->
<javaModelGenerator targetPackage=“com.atguigu.bean” targetProject=".\src">
<property name=“enableSubPackages” value=“true” />
<property name=“trimStrings” value=“true” />
<!–
sqlMapGenerator 生成表对应的sql的xml配置文件
targetPackage 属性设置生成的sql配置文件的包名
targetProject 属性设置生成的工程的路径 一般生成为当前工程。写为 .\
-->
<sqlMapGenerator targetPackage=“com.atguigu.mapper” targetProject=".\src">
<property name=“enableSubPackages” value=“true” />
<!–
javaClientGenerator 生成mybatis客户端的代码 ===dao或mapper之类
targetPackage 属性设置生成的mybatis的调用代码,比如mapper之类的接口
targetProject 属性设置生成的工程的路径 一般生成为当前工程。写为 .\
-->
<javaClientGenerator type=“XMLMAPPER” targetPackage="*com.atguigu.mapper" targetProject=".\src"*>
<property name=“enableSubPackages” value=“true” />
<!–
table 配置哪些表需要我们映射生成java代码
tableName 是表名
domainObjectName 是javaBean名
-->
<table tableName="t_user" domainObjectName="User"></table>
<table tableName="t_book" domainObjectName="Book"></table>
10.4用于生成的java代码
使用运行以下代码,生成所需要的文件
public static void main(String[] args) throws Exception, Exception {
List warnings = new ArrayList();
boolean overwrite = true;
// 配置文件的名称 mbg_config.xml
File configFile = new File(“mbg_config.xml”);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
rgetProject=".\src">
<property name=“enableSubPackages” value=“true” />
<!–
javaClientGenerator 生成mybatis客户端的代码 ===dao或mapper之类
targetPackage 属性设置生成的mybatis的调用代码,比如mapper之类的接口
targetProject 属性设置生成的工程的路径 一般生成为当前工程。写为 .\
-->
<javaClientGenerator type=“XMLMAPPER” targetPackage="*com.atguigu.mapper" targetProject=".\src"*>
<property name=“enableSubPackages” value=“true” />
<!–
table 配置哪些表需要我们映射生成java代码
tableName 是表名
domainObjectName 是javaBean名
-->
<table tableName="t_user" domainObjectName="User"></table>
<table tableName="t_book" domainObjectName="Book"></table>
10.4用于生成的java代码
使用运行以下代码,生成所需要的文件
public static void main(String[] args) throws Exception, Exception {
List warnings = new ArrayList();
boolean overwrite = true;
// 配置文件的名称 mbg_config.xml
File configFile = new File(“mbg_config.xml”);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}