對於常用的基本的數據庫操縱和數據查詢,無需再手動去編寫sql,使用程序生成,開發效率更高,當然要會用啦!
主要有兩種方法:
1、使用java命令生成;
2、使用java程序生成
下面介紹第一種方法:
使用java命令生成Mapper.java、xml文件
1、編寫Mybatis生成文件的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--數據庫驅動 -->
<classPathEntry location="C:\\Users\\11985\\.m2\\repository\\mysql\\mysql-connector-java\\8.0.19\\mysql-connector-java-8.0.19.jar" />
<context id="myContext" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--數據庫鏈接地址賬號密碼 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"
userId="root" password="root">
<!--使用Connector / J的8.x版,需要加這個屬性,否則會生成xxxKey,xxxWithBlobs等文件-->
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--生成實體類類存放位置 -->
<javaModelGenerator targetPackage="com.boot.mybatis.po"
targetProject="src/main/java/">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--生成映射文件存放位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources/">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--生成Dao類存放位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.boot.mybatis.dao" targetProject="src/main/java/">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--生成對應表及類名-->
<table tableName="user" domainObjectName="User"></table>
</context>
</generatorConfiguration>
2、輸入如下指令(參考:MyBatis Generator Quick Start Guide)
java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml -overwrite
我測試成功的例子是:
java -jar C:\Users\11985\.m2\repository\org\mybatis\generator\mybatis-generator-core\1.3.5\mybatis-generator-core-1.3.5.jar -configfile D:\java\idea-work
space\mybatis\src\main\resources\generatorConfig.xml -overwrite
使用命令的好處:
mybatis-generator-core-x.x.x.jar包和generatorConfig.xml可以不在項目中,和項目分離單獨使用。這樣可以避免項目後期開發中的意外導致重要文件被覆蓋!
使用java程序生成Mapper.java、xml文件
1、添加依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
2、使用MyBatisGenerator生成文件
public class MyBatisGeneratorTest {
public static void main(String[] args) {
try {
List<String> warnings = new ArrayList<>();
File configFile = new File("D:\\java\\idea-workspace\\mybatis\\src\\main\\resources\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
下面是由java程序生成的文件的使用(Example)
Mapper.java文件源碼如下:
public interface UserMapper {
/**
* 根據example查詢符合條件的記錄數
*/
long countByExample(UserExample example);
/**
* 根據example刪除符合條件的記錄
*/
int deleteByExample(UserExample example);
/**
* 根據主鍵刪除記錄
*/
int deleteByPrimaryKey(Integer id);
/**
* 插入
*/
int insert(User record);
/**
* 選擇性插入
*/
int insertSelective(User record);
/**
* 根據example查詢符合條件的記錄
*/
List<User> selectByExample(UserExample example);
/**
* 根據主鍵查詢記錄
*/
User selectByPrimaryKey(Integer id);
/**
* 根據example選擇性更新記錄
*/
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
/**
* 根據example更新記錄
*/
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
/**
* 根據主鍵選擇性更新記錄
*/
int updateByPrimaryKeySelective(User record);
/**
* 根據主鍵更新記錄
*/
int updateByPrimaryKey(User record);
}
關於選擇性的意思,我在下面的測試類中的註釋有介紹。
測試類如下:
import com.boot.mybatis.po.User;
import com.boot.mybatis.po.UserExample;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author river
* 2020/2/10
*/
@SpringBootTest
class UserMapperTest {
@Resource
UserMapper userMapper;
@Test
void countByExample() {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUserNameLike("river%");
long count = userMapper.countByExample(userExample);
assertNotEquals(count, 0);
}
@Test
void deleteByExample() {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUserNameEqualTo("river4");
int influenceLine = userMapper.deleteByExample(userExample);
assertNotEquals(influenceLine, 0);
}
@Test
void deleteByPrimaryKey() {
int influenceLineNum = userMapper.deleteByPrimaryKey(4);
assertNotEquals(influenceLineNum, 0);
}
@Test
void insert() {
User user = new User();
user.setUserName("river6");
user.setPassword("121212");
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
int influenceLineNum = userMapper.insert(user);//不能爲null的值,必須設置值,數據庫默認值不起作用
assertNotEquals(influenceLineNum, 0);
}
@Test
void insertSelective() {
User user = new User();
user.setUserName("river66");
user.setPassword("123123");
int influenceLineNum = userMapper.insertSelective(user);//爲null值的字段,數據庫會該字段設爲默認值
assertNotEquals(influenceLineNum, 0);
}
@Test
void selectByExample() {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUserNameLike("river%");
List<User> users = userMapper.selectByExample(userExample);
assertNotEquals(users.size(),0);
}
@Test
void selectByPrimaryKey() {
User user = userMapper.selectByPrimaryKey(1);
assertEquals(user.getId(),1);
}
@Test
void updateByExampleSelective() {
User user = new User();
user.setPassword("666");
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUserNameEqualTo("river66");
int influenceLineNum = userMapper.updateByExampleSelective(user, userExample);//選擇性更新,將river66的記錄對應的password更新爲666
assertNotEquals(influenceLineNum, 0);
}
@Test
void updateByExample() {
User user = userMapper.selectByPrimaryKey(1);
user.setPassword("666666");
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andIdEqualTo(user.getId());
int influenceLineNum = userMapper.updateByExample(user, userExample);//user中的所有信息所有更新到數據庫,包括值爲null的字段
assertNotEquals(influenceLineNum, 0);
}
@Test
void updateByPrimaryKeySelective() {
User user = new User();
user.setId(1);
user.setPassword("168168");
int influenceLineNum = userMapper.updateByPrimaryKeySelective(user);//根據主鍵選擇性更新,null值字段不會更新到數據庫
assertNotEquals(influenceLineNum, 0);
}
@Test
void updateByPrimaryKey() {
User user = userMapper.selectByPrimaryKey(1);
user.setPassword("168666");
int influenceLineNum = userMapper.updateByPrimaryKey(user);//根據主鍵選擇性更新,null值字段不會更新到數據庫
assertNotEquals(influenceLineNum, 0);
}
}
最後附上數據庫sql和application.yml文件,以及github地址:https://github.com/bigBigRiver/MybatisGenerator.git
/*
Navicat MySQL Data Transfer
Source Server : superMeSql
Source Server Version : 80019
Source Host : localhost:3306
Source Database : mybatis_test
Target Server Type : MYSQL
Target Server Version : 80019
File Encoding : 65001
Date: 2020-02-10 20:13:49
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`user_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'river', '666666', '2020-01-21 12:33:20', '2020-02-10 18:34:04');
INSERT INTO `user` VALUES ('2', 'river1', '123456', '2020-01-21 12:35:49', '2020-01-21 12:35:49');
INSERT INTO `user` VALUES ('3', 'river2', '123456', '2020-01-21 12:36:22', '2020-01-21 12:36:22');
INSERT INTO `user` VALUES ('6', 'river66', '666', '2020-02-10 18:06:32', '2020-02-10 18:32:18');
INSERT INTO `user` VALUES ('7', 'river6', '121212', '2020-02-10 18:09:15', '2020-02-10 18:09:15');
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.boot.mybatis.po