Mybatis -- Mybatis-Generator自动生成Dao、Model、Mapping文件及其使用

Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件Model,Mapping以及Dao层相关文件。 

1、相关文件

关于Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases

由于我使用的是Mysql数据库,这里需要在准备一个连接mysql数据库的驱动jar包

以下是相关文件截图:

 

需要一个配置文件(src下面建):

generatorConfig.xml

[html]  view plain   copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >  
  3. <generatorConfiguration>  
  4.     <!-- 引入配置文件 -->  
  5.     <properties resource="jdbc.properties"/>  
  6.       
  7.     <!-- 指定数据连接驱动jar地址 -->  
  8.     <classPathEntry location="${classPath}" />  
  9.       
  10.     <!-- 一个数据库一个context -->  
  11.     <context id="infoGuardian">  
  12.         <!-- 注释 -->  
  13.         <commentGenerator >  
  14.             <property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->  
  15.             <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->  
  16.         </commentGenerator>  
  17.           
  18.         <!-- jdbc连接 -->  
  19.         <jdbcConnection driverClass="${jdbc_driver}"  
  20.             connectionURL="${jdbc_url}" userId="${jdbc_user}"  
  21.             password="${jdbc_password}" />  
  22.           
  23.         <!-- 类型转换 -->  
  24.         <javaTypeResolver>  
  25.             <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->  
  26.             <property name="forceBigDecimals" value="false"/>  
  27.         </javaTypeResolver>  
  28.           
  29.         <!-- 生成实体类地址 -->    
  30.         <javaModelGenerator targetPackage="com.oop.eksp.user.model"  //包+目录
  31.             targetProject="${project}" >  //实际项目所在磁盘的目录 至src下即可
  32.             <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->  
  33.             <property name="enableSubPackages" value="false"/>  
  34.             <!-- 是否针对string类型的字段在set的时候进行trim调用 -->  
  35.             <property name="trimStrings" value="true"/>  
  36.         </javaModelGenerator>  
  37.           
  38.         <!-- 生成mapxml文件 -->  
  39.         <sqlMapGenerator targetPackage="com.oop.eksp.user.data"  
  40.             targetProject="${project}" >  
  41.             <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->  
  42.             <property name="enableSubPackages" value="false" />  
  43.         </sqlMapGenerator>  
  44.           
  45.         <!-- 生成mapxml对应client,也就是接口dao -->      
  46.         <javaClientGenerator targetPackage="com.oop.eksp.user.data"  
  47.             targetProject="${project}" type="XMLMAPPER" >  
  48.             <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->  
  49.             <property name="enableSubPackages" value="false" />  
  50.         </javaClientGenerator>  
  51.           
  52.         <!-- 配置表信息 -->      
  53.         <table schema="${jdbc_user}" tableName="s_user"  
  54.             domainObjectName="UserEntity" enableCountByExample="false"   //生成的实体类的名字
  55.             enableDeleteByExample="false" enableSelectByExample="false"  
  56.             enableUpdateByExample="false">  
  57.             <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample   
  58.                 是否生成 example类   -->  
  59.               
  60.             <!-- 忽略列,不生成bean 字段 -->  
  61.             <ignoreColumn column="FRED" />  
  62.             <!-- 指定列的java数据类型 -->  
  63.             <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />  
  64.         </table>  
  65.   
  66.     </context>  
  67. </generatorConfiguration> 

需要修改文件配置的地方我都已经把注释标注出来了,这里的相关路径(如数据库驱动包,生成对应的相关文件位置可以自定义)不能带有中文。

上面配置文件中的:

<table tableName="message" domainObjectName="Messgae" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

tableName和domainObjectName为必选项,分别代表数据库表名和生成的实力类名,其余的可以自定义去选择(一般情况下均为false)。

2.生成文件结构及方法:

生成的文件包含三类:

1.Model 实体文件,一个数据库表生成一个 Model 实体;

2.ModelExample 文件,此文件和实体文件在同一目录下,主要用于查询条件构造;

3.Mapper 接口文件,数据数操作方法都在此接口中定义;

4.Mapper XML 配置文件;

生成文件方法:可以在命令行生成也可以在main方法

1.建一个MBGenerator类:

public class MBGenerator {
public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException,
SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src/MybatisGenerator.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);
}
}

2、使用

如果多个包下需要生成这些文件,则在MybatisGenerator.xml配置文件中要修改生成的路径,数据源,数据库表名等信息

生成相关代码:

Message.java (Model下)

 1 package lcw.model;
 2 
 3 public class Messgae {
 4     private Integer id;
 5 
 6     private String title;
 7 
 8     private String describe;
 9 
10     private String content;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getTitle() {
21         return title;
22     }
23 
24     public void setTitle(String title) {
25         this.title = title == null ? null : title.trim();
26     }
27 
28     public String getDescribe() {
29         return describe;
30     }
31 
32     public void setDescribe(String describe) {
33         this.describe = describe == null ? null : describe.trim();
34     }
35 
36     public String getContent() {
37         return content;
38     }
39 
40     public void setContent(String content) {
41         this.content = content == null ? null : content.trim();
42     }
43 }
复制代码
复制代码

MessgaeMapper.xml(mapper下)

复制代码
复制代码
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="lcw.dao.MessgaeMapper" >
 4   <resultMap id="BaseResultMap" type="lcw.model.Messgae" >
 5     <id column="id" property="id" jdbcType="INTEGER" />
 6     <result column="title" property="title" jdbcType="VARCHAR" />
 7     <result column="describe" property="describe" jdbcType="VARCHAR" />
 8     <result column="content" property="content" jdbcType="VARCHAR" />
 9   </resultMap>
10   <sql id="Base_Column_List" >
11     id, title, describe, content
12   </sql>
13   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
14     select 
15     <include refid="Base_Column_List" />
16     from message
17     where id = #{id,jdbcType=INTEGER}
18   </select>
19   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
20     delete from message
21     where id = #{id,jdbcType=INTEGER}
22   </delete>
23   <insert id="insert" parameterType="lcw.model.Messgae" >
24     insert into message (id, title, describe, 
25       content)
26     values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{describe,jdbcType=VARCHAR}, 
27       #{content,jdbcType=VARCHAR})
28   </insert>
29   <insert id="insertSelective" parameterType="lcw.model.Messgae" >
30     insert into message
31     <trim prefix="(" suffix=")" suffixOverrides="," >
32       <if test="id != null" >
33         id,
34       </if>
35       <if test="title != null" >
36         title,
37       </if>
38       <if test="describe != null" >
39         describe,
40       </if>
41       <if test="content != null" >
42         content,
43       </if>
44     </trim>
45     <trim prefix="values (" suffix=")" suffixOverrides="," >
46       <if test="id != null" >
47         #{id,jdbcType=INTEGER},
48       </if>
49       <if test="title != null" >
50         #{title,jdbcType=VARCHAR},
51       </if>
52       <if test="describe != null" >
53         #{describe,jdbcType=VARCHAR},
54       </if>
55       <if test="content != null" >
56         #{content,jdbcType=VARCHAR},
57       </if>
58     </trim>
59   </insert>
60   <update id="updateByPrimaryKeySelective" parameterType="lcw.model.Messgae" >
61     update message
62     <set >
63       <if test="title != null" >
64         title = #{title,jdbcType=VARCHAR},
65       </if>
66       <if test="describe != null" >
67         describe = #{describe,jdbcType=VARCHAR},
68       </if>
69       <if test="content != null" >
70         content = #{content,jdbcType=VARCHAR},
71       </if>
72     </set>
73     where id = #{id,jdbcType=INTEGER}
74   </update>
75   <update id="updateByPrimaryKey" parameterType="lcw.model.Messgae" >
76     update message
77     set title = #{title,jdbcType=VARCHAR},
78       describe = #{describe,jdbcType=VARCHAR},
79       content = #{content,jdbcType=VARCHAR}
80     where id = #{id,jdbcType=INTEGER}
81   </update>
82 </mapper>
复制代码
&lt; < 小于号
&gt; > 大于号
&amp; &
&apos; ' 单引号
  &quot;
" 双引号
上面是方法一,也可以使用 <![CDATA[ ]]>符号进行说明,将此类符号不进行解析,例如:
[html]  view plain   copy
  1. <select id="selectMonthAdvertise" resultMap="ResultMap">  
  2.    select * from ad_n_advertise_t where user_id in  
  3.   <foreach item="item" index="index" collection="userIdList" open="(" separator="," close=")">  
  4.   #{item}  
  5.   </foreach>   
  6.   and isdelete=#{isdelete,jdbcType=TINYINT}    
  7.   and <![CDATA[</span>date_sub(curdate(), INTERVAL 30 DAY) <= date(crt_time)]]>   
  8.   order by crt_time desc  
  9. </select>  

MessgaeMapper.java(dao下)

复制代码
复制代码
 1 package lcw.dao;
 2 
 3 import lcw.model.Messgae;
 4 
 5 public interface MessgaeMapper {
 6     int deleteByPrimaryKey(Integer id);
 7 
 8     int insert(Messgae record);
 9 
10     int insertSelective(Messgae record);
11 
12     Messgae selectByPrimaryKey(Integer id);
13 
14     int updateByPrimaryKeySelective(Messgae record);
15 
16     int updateByPrimaryKey(Messgae record);
17 }
 
  
   还有一个是MessageExample类,是在Model下生成的,这个类对于单表查询十分方便,只需要拼接需要的字段即可,凡是mapper可以点出来的方法均不用在.xml配置文件中进行方法声明。如果涉及到复杂的sql语句或者多表查询则要在mapping层的.xml文件中书写sql语句。
关于使用Example类进行简单增删改查的方法:
①.在service层生成
Criteria类,然后构建字段,升降序以及查询条件。 
@Service(value="loginServiceImp")
public class LoginServiceImp implements LoginService{
	@Autowired
	private UserMapper userMapper;


	public  List<User>  login(User user) {
		System.out.println("进入service类");
		
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andLoginNameEqualTo(user.getLoginName());
		criteria.andPasswordEqualTo(user.getPassword());
		
		return userMapper.selectOne(example);
	}


}
②.以下是关于
criteria类如何构建sql语句:

①查询是最常用功能,如下方法是查询 IP 为某值的记录,如果知道主键的话,可以用 selectByPrimaryKey 方法。

?
1
2
3
4
5
6
7
8
9
public BlackListIP get(String ip){
BlackListIPExample example = new BlackListIPExample();
Criteria criteria = example.createCriteria()
criteria .andIpEqualTo(ip);
List<BlackListIP> blackListIPList = blackListipMapper.selectByExample(example);
if (blackListIPList!= null && blackListIPList.size()> 0 ){
return blackListIPList.get( 0 );
}
return null ;
}

更新、添加、删除方法调用方法类似,具体可查看相关文档介绍。  

②排序

?
1
2
3
4
5
6
7
8
9
10
public BlackListIP get(String ip){
BlackListIPExample example = new BlackListIPExample();
example.setOrderByClause( "CREATE_TIME desc" ); //按创建时间排序
example.createCriteria().andIpEqualTo(ip);
List<BlackListIP> blackListIPList = blackListipMapper.selectByExample(example);
if (blackListIPList!= null && blackListIPList.size()> 0 ){
return blackListIPList.get( 0 );
}
return null ;
}

分页

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public PageInfo list(Account account, PageInfo pageInfo,String startTime,String endTime) {
account.setIsDel(SysParamDetailConstant.IS_DEL_FALSE);
AccountExample example = getCondition(account,startTime,endTime);
if ( null != pageInfo && null != pageInfo.getPageStart()) {
example.setLimitClauseStart(pageInfo.getPageStart());
example.setLimitClauseCount(pageInfo.getPageCount());
}
example.setOrderByClause( " CREATE_TIME desc " );
List<Account> list = accountMapper.selectByExample(example);
int totalCount = accountMapper.countByExample(example);
pageInfo.setList(list);
pageInfo.setTotalCount(totalCount);
return pageInfo;
}

实现 a=x and (b=xx or b=xxx)这样的查询条件  

虽然自动生成代码很方便,但凡事有利即有弊,mybatis generator 没有办法生成表联查(join)功能,只能手动添加。如下实现了a=x and (b=xx or b=xxx)这样的条件拼接。

     
      
      
1
2
3
4
5
AccountExample accountExample = new AccountExample();
AccountExample.Criteria criteria = accountExample.createCriteria().andTypeEqualTo( "4" );
criteria.addCriterion(String.format( " (ID=%d or ID=%d) " , 34 , 35 ));
List<Account> accounts = accountMapper.selectByExample(accountExample);
return accounts;
mybatis中的mapper接口文件以及example类的实例函数讲解:

  1. 1)mybatis中mapper的实例函数:    
  2. int countByExample(UserExample example) thorws SQLException:按条件计数。    
  3. int deleteByPrimaryKey(Integer id) thorws SQLException:按主键删除。    
  4. int deleteByExample(UserExample example) thorws SQLException:按条件删除。    
  5. String/Integer insert(User record) thorws SQLException:插入(返回值为id值)    
  6. User selectByPrimaryKey(Integer id) thorws SQLException:按主键查询。    
  7. List<?>selectByExample(UserExample example) thorws SQLException:按条件查询    
  8. List<?>selectByExampleWithBLOGs(UserExample example) thorws SQLException:按    
  9. 2)更新操作(update)详解  :
  10. 第一种:使用example构建查询
  11.  所有字段都需要更新
  12. int updateByExample(User record, UserExample example) thorws SQLException:     
  13.    其中User类型包括更改后的字段,example包含待更新表的主键 
  14. 有的字段需更新  
  15. int updateByExampleSelective(User record, UserExample example) thorws      
  16.  第二种  :根据表的主键与实体类:
  17. 所有字段更新
  18. int updateByPrimaryKey(User record) thorws SQLException:按主键更新
  19. 部分字段更新
  20. int updateByPrimaryKeySelective(User record) thorws SQLException:按主键更新   
  21. 3)查询select详解: 
  22. mybatis中mapper的实例函数详解:    
  23. ① selectByPrimaryKey()    
  24.     
  25. User user = ##Mapper.selectByPrimaryKey(100); 相当于select * from user where    
  26.     
  27. id = 100    
  28.     
  29. ② selectByExample() 和 selectByExampleWithBLOGs()    
  30.     
  31. UserExample example = new UserExample();    
  32. Criteria criteria = example.createCriteria();    
  33. criteria.andUsernameEqualTo("joe");    
  34. criteria.andUsernameIsNull();    
  35. example.setOrderByClause("username asc,email desc");    
  36. List<?>list = ##Mapper.selectByExample(example);    
  37. 相当于:select * from user where username = 'joe' and username is null order    
  38.     
  39. by username asc,email desc    
  40.     
  41. 注:在iBator 生成的文件UserExample.java中包含一个static 的内部类 Criteria ,    
  42.     
  43. 在Criteria中有很多方法,主要是定义SQL 语句where后的查询条件。    
  44.     
  45. 4):插入 insert详解:    
  46.     
  47. User user = new User();    
  48. user.setId(101);    
  49. user.setUsername("test");    
  50. user.setPassword("123")    
  51. user.setEmail("[email protected]");    
  52. ##Mapper.insert(user);    
  53. 相当于:insert into user(ID,username,password,email) values    
  54.     
  55. (101,'test','123','[email protected]');    
  56.     
  57.  ④ updateByPrimaryKey() 和 updateByPrimaryKeySelective()    
  58.     
  59. User user =new User();    
  60. user.setId(101);    
  61. user.setUsername("joe");    
  62. user.setPassword("joe");    
  63. user.setEmail("[email protected]");    
  64. ##Mapper.updateByPrimaryKey(user);    
  65. 相当于:update user set username='joe',password='joe',email='[email protected]'    
  66.     
  67. where id=101    
  68.     
  69. User user = new User();    
  70. user.setId(101);    
  71. user.setPassword("joe");    
  72. ##Mapper.updateByPrimaryKeySelective(user);    
  73. 相当于:update user set password='joe' where id=101    
  74.     
  75. ⑤ updateByExample() 和 updateByExampleSelective()    
  76.     
  77. UserExample example = new UserExample();    
  78. Criteria criteria = example.createCriteria();    
  79. criteria.andUsernameEqualTo("joe");    
  80. User user = new User();    
  81. user.setPassword("123");    
  82. ##Mapper.updateByPrimaryKeySelective(user,example);    
  83. 相当于:update user set password='123' where username='joe'    
  84.     
  85. ⑥ deleteByPrimaryKey()    
  86.     
  87. ##Mapper.deleteByPrimaryKey(101);  相当于:delete from user where id=101    
  88.     
  89. ⑦ deleteByExample()    
  90.     
  91. UserExample example = new UserExample();    
  92. Criteria criteria = example.createCriteria();    
  93. criteria.andUsernameEqualTo("joe");    
  94. ##Mapper.deleteByExample(example);    
  95. 相当于:delete from user where username='joe'    
  96.     
  97. ⑧ countByExample()    
  98.     
  99. UserExample example = new UserExample();    
  100. Criteria criteria = example.createCriteria();    
  101. criteria.andUsernameEqualTo("joe");    
  102. int count = ##Mapper.countByExample(example);    
  103. 相当于:select count(*) from user where username='joe'   

猜你喜欢

转载自blog.csdn.net/happyAliceYu/article/details/65633116
今日推荐