复习:全面使用注解,Mybatis自动生成代码。
1.maven里面的重要依赖库
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
2. 从main执行代码生成
public static void main(String[] args) {
//
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//GenMain.class.getResource("generatorConfig.xml").getFile()
File configFile = new File(GenerateMybatisCode.class.getResource("/generatorConfig.xml").getFile());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config;
try {
config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (IOException | XMLParserException | InvalidConfigurationException | SQLException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("========================generate the code sucess.==================");
}
Mybatis的generatorConfig.xml配置文件请参考官方github。
自动生成完的代码,比如Mapper:
@Mapper
public interface ProductMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table product
*
* @mbg.generated Thu Aug 01 11:10:53 CST 2019
*/
@Delete({
"delete from product",
"where id = #{id,jdbcType=INTEGER}"
})
int deleteByPrimaryKey(Integer id);
@Insert({
"insert into product (product_type, ",
"name, retail_price, ",
"cost_price, create_time)",
"values (#{productType,jdbcType=INTEGER}, ",
"#{name,jdbcType=VARCHAR}, #{retailPrice,jdbcType=NUMERIC}, ",
"#{costPrice,jdbcType=NUMERIC}, #{createTime,jdbcType=TIMESTAMP})"
})
int insert(Product record);
省略若干代码。
网友评论