一.配置
mybatis generator用于自动生成相关表所对应的java文件,包括:javabean,dao接口,映射文件,如下所示:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 6 <generatorConfiguration> 7 8 <context id="DB2Tables" targetRuntime="MyBatis3"> 9 <!-- 不生成注释 --> 10 <commentGenerator> 11 <property name="suppressAllComments" value="true" /> 12 </commentGenerator> 13 <!-- 配置数据库连接信息 --> 14 <jdbcConnection 15 driverClass="com.mysql.jdbc.Driver" 16 connectionURL="jdbc:mysql://localhost:3306/******" 17 userId="******" 18 password="******"> 19 </jdbcConnection> 20 21 <javaTypeResolver > 22 <property name="forceBigDecimals" value="false" /> 23 </javaTypeResolver> 24 25 <!-- 指定javabean生成的位置 --> 26 <javaModelGenerator 27 targetPackage="com.cnblogs.xie.bean" 28 targetProject=".\src\main\java"> 29 <property name="enableSubPackages" value="true" /> 30 <property name="trimStrings" value="true" /> 31 </javaModelGenerator> 32 33 <!-- 指定sql映射文件生成的位置 --> 34 <sqlMapGenerator 35 targetPackage="mapper" 36 targetProject=".\src\main\resources"> 37 <property name="enableSubPackages" value="true" /> 38 </sqlMapGenerator> 39 40 <!-- 指定dao接口生成的位置,mapper接口 --> 41 <javaClientGenerator type="XMLMAPPER" 42 targetPackage="com.cnblogs.xie.dao" 43 targetProject=".\src\main\java"> 44 <property name="enableSubPackages" value="true" /> 45 </javaClientGenerator> 46 47 <!-- 指定每个表的生成策略 --> 48 <table tableName="students" domainObjectName="Student"/> 49 </context> 50 </generatorConfiguration>
其中tableName为表名,domainObjectName为javabean类名。
二:使用
1.试例:
可以通过Service类调用其中方法,如下:
public List<Loophole> getAll(){ StudentExample example = new StudentExample(); List<Student> list = studentMapper.selectByExample(example); return list; }
以上代码作用为查询students表中的所有信息,与以下sql作用相同:
select * from students;
2.XXXExample类:
如上例中的StudentExample类,它实例化的对象example负责对sql添加各种限制条件
(1)example.isDistinct();
select distinct * from students;
(2)example.setOrderByClause("stu_id desc");
select * from student order by stu_id desc;
3.sql中的where子句:
sql中的where子句又该如何添加呢?如下所示:
StudentExample example = new example(); StudentExample.Criteria criteria = studentExample.createCriteria(); criteria.andStuAgeEqualTo(20); List<Student> students = studnetMapper.selectByExample(example);
它的作用等同于:
select * from students where stu_age = 20;
criteria还有很多方法,如下:
andXXXEqualTo(xx) Between(xx,xx) In(List<xx>) GreaterThan(xx) LessThan(xx) Like(xx) IsNull() IsNotNull() ......
4.sql中的or
StudentExample example = new example(); example.or().andStuIdEqualTo(xx) example.or().andStuAgeBetween(aa,bb); List<Student> students = studnetMapper.selectByExample(example);
它的作用等同于:
select * from student where stu_id = xx or stu_age between aa and bb
原文地址:https://www.cnblogs.com/xiehuazhen/p/9483343.html
时间: 2024-10-09 16:26:42