Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件Model,Mapping以及Dao层相关文件。
1、相关文件
关于Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases
由于我使用的是Mysql数据库,这里需要在准备一个连接mysql数据库的驱动jar包
以下是相关文件截图:
需要一个配置文件(src下面建):
generatorConfig.xml
需要修改文件配置的地方我都已经把注释标注出来了,这里的相关路径(如数据库驱动包,生成对应的相关文件位置可以自定义)不能带有中文。
上面配置文件中的:
<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>
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 方法。
更新、添加、删除方法调用方法类似,具体可查看相关文档介绍。
②排序
分页
实现 a=x and (b=xx or b=xxx)这样的查询条件
虽然自动生成代码很方便,但凡事有利即有弊,mybatis generator 没有办法生成表联查(join)功能,只能手动添加。如下实现了a=x and (b=xx or b=xxx)这样的条件拼接。
mybatis中的mapper接口文件以及example类的实例函数讲解:
- 1)mybatis中mapper的实例函数:
- int countByExample(UserExample example) thorws SQLException:按条件计数。
- int deleteByPrimaryKey(Integer id) thorws SQLException:按主键删除。
- int deleteByExample(UserExample example) thorws SQLException:按条件删除。
- String/Integer insert(User record) thorws SQLException:插入(返回值为id值)
- User selectByPrimaryKey(Integer id) thorws SQLException:按主键查询。
- List<?>selectByExample(UserExample example) thorws SQLException:按条件查询
- List<?>selectByExampleWithBLOGs(UserExample example) thorws SQLException:按
- 2)更新操作(update)详解 :
- 第一种:使用example构建查询
- 所有字段都需要更新
- int updateByExample(User record, UserExample example) thorws SQLException:
- 其中User类型包括更改后的字段,example包含待更新表的主键
- 有的字段需更新
- int updateByExampleSelective(User record, UserExample example) thorws
- 第二种 :根据表的主键与实体类:
- 所有字段更新
- int updateByPrimaryKey(User record) thorws SQLException:按主键更新
- 部分字段更新
- int updateByPrimaryKeySelective(User record) thorws SQLException:按主键更新
- 3)查询select详解:
- mybatis中mapper的实例函数详解:
- ① selectByPrimaryKey()
- User user = ##Mapper.selectByPrimaryKey(100); 相当于select * from user where
- id = 100
- ② selectByExample() 和 selectByExampleWithBLOGs()
- UserExample example = new UserExample();
- Criteria criteria = example.createCriteria();
- criteria.andUsernameEqualTo("joe");
- criteria.andUsernameIsNull();
- example.setOrderByClause("username asc,email desc");
- List<?>list = ##Mapper.selectByExample(example);
- 相当于:select * from user where username = 'joe' and username is null order
- by username asc,email desc
- 注:在iBator 生成的文件UserExample.java中包含一个static 的内部类 Criteria ,
- 在Criteria中有很多方法,主要是定义SQL 语句where后的查询条件。
- 4):插入 insert详解:
- User user = new User();
- user.setId(101);
- user.setUsername("test");
- user.setPassword("123")
- user.setEmail("joe@163.com");
- ##Mapper.insert(user);
- 相当于:insert into user(ID,username,password,email) values
- (101,'test','123','joe@163.com');
- ④ updateByPrimaryKey() 和 updateByPrimaryKeySelective()
- User user =new User();
- user.setId(101);
- user.setUsername("joe");
- user.setPassword("joe");
- user.setEmail("joe@163.com");
- ##Mapper.updateByPrimaryKey(user);
- 相当于:update user set username='joe',password='joe',email='joe@163.com'
- where id=101
- User user = new User();
- user.setId(101);
- user.setPassword("joe");
- ##Mapper.updateByPrimaryKeySelective(user);
- 相当于:update user set password='joe' where id=101
- ⑤ updateByExample() 和 updateByExampleSelective()
- UserExample example = new UserExample();
- Criteria criteria = example.createCriteria();
- criteria.andUsernameEqualTo("joe");
- User user = new User();
- user.setPassword("123");
- ##Mapper.updateByPrimaryKeySelective(user,example);
- 相当于:update user set password='123' where username='joe'
- ⑥ deleteByPrimaryKey()
- ##Mapper.deleteByPrimaryKey(101); 相当于:delete from user where id=101
- ⑦ deleteByExample()
- UserExample example = new UserExample();
- Criteria criteria = example.createCriteria();
- criteria.andUsernameEqualTo("joe");
- ##Mapper.deleteByExample(example);
- 相当于:delete from user where username='joe'
- ⑧ countByExample()
- UserExample example = new UserExample();
- Criteria criteria = example.createCriteria();
- criteria.andUsernameEqualTo("joe");
- int count = ##Mapper.countByExample(example);
- 相当于:select count(*) from user where username='joe'