mybatis与spring的整合
在pom.xml 引入对应的jar包 (https://mvnrepository.com/ 官网搜即可)
<!-- 引入 mybatis 包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- druid 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<!-- 别忘了引入mybatis 核心包 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<!-- mybatis 插件 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
在application.properties中加入mybatis的相关配置
# mybatis 配置
# 映射接口包
mybatis.type-aliases-package=com.example.demo
# mapper文件地址
mybatis.mapper-locations=classpath:mapper/*.xml
# 通用 Mapper 配置
mapper.mappers=com.example.demo.utils.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
############################################################
#
# 配置数据源相关 使用阿里巴巴的 druid 数据源
#
############################################################
spring.datasource.url=jdbc:mysql://106.12.113.94:3306/jim
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true
构造配置文件
<?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>
<context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- TKmybatis提供一种通用mapper,它不需要针对每个mapper写sql语句,只需继承通用mapper调用相应的接口来完成单表的增删改查。-->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.example.demo.utils.MyMapper"/>
</plugin>
<!-- 这个地方后面配置useSSL=false,是因为mysql版本高,协议问题所以要加上 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://xxx:3306/yaobo?useSSL=false"
userId="root"
password="yaobo123">
</jdbcConnection>
<!-- 对于生成的pojo所在包 -->
<javaModelGenerator targetPackage="com.example.demo.pojo" targetProject="src/main/java"/>
<!-- 对于生成的mapper所在目录 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- 配置mapper对应的java映射 -->
<javaClientGenerator targetPackage="com.example.demo.mapper" targetProject="src/main/java"
type="XMLMAPPER"/>
<table tableName="sys_user"></table>
</context>
</generatorConfiguration>
构造主方法实现
package com.example.demo.utils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GenerateMapper {
public void generator () throws Exception {
List<String> warnings = new ArrayList<>();
boolean overwriter = true;
// 指向 逆向工程文件
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwriter);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
public static void main (String[] args) {
GenerateMapper generateMapper = new GenerateMapper();
try {
generateMapper.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用自定义的mapper
配置自己的mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- namespace 对应你自己的命名空间 -->
<mapper namespace="com.example.demo.mapper.SysUserMapperCustomer" >
<!-- 做一个自定义的简单查询 id 对应你的方法名-->
<select id="queryUserById" resultType="com.example.demo.pojo.SysUser" parameterType="java.lang.String">
select * from sys_user where id = #{id, jdbcType=VARCHAR}
</select>
</mapper>
mapper 接口
package com.example.demo.mapper;
import com.example.demo.pojo.SysUser;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface SysUserMapperCustomer{
List<SysUser> queryUserById(String id);
}
实现类
···
@Autowired
private SysUserMapperCustomer sysUserMapperCustomer;
@Override
public SysUser queryUserById(String userId) {
List<SysUser> userList = sysUserMapperCustomer.queryUserById(userId);
if (userList !=null) {
return userList.get(0);
}
return null;
}
···
特别注意一点,在控制层如果调用这个方法,不能用new 实现类, 一定也要用@Autowired
@Autowired来的spring 下的bean,则当前类必须也是spring bean才能调用它,不能用new Xxx()来获得对象,这种方式获得的对象无法调用其内的@autowired的bean
最后别忘记增加组件扫描的注解
package com.imooc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
//扫描 mybatis mapper 包路径
@MapperScan(basePackages = "com.imooc.mapper")
public class ImoocApplication {
public static void main(String[] args) {
SpringApplication.run(ImoocApplication.class, args);
}
}
网友评论