[java]springboot集成mybatis

mybatis: MBG工具使用

创建user表

CREATE TABLE `user` (
  `id` int(11) primary key AUTO_INCREMENT,
  `name` varchar(20),
  `age` int(11)
)

根据user表生成dao层: mbg配置文件

resources/generator.properties

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.userId=root
jdbc.password=root

tspringboot/GeneratorMapper.xml

<?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>
    <!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 -->
    <classPathEntry location="/Users/xiaolangma/apache-maven-3.6.3/repository/mysql/mysql-connector-java/5.1.41/mysql-connector-java-5.1.41.jar"/>
    <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 -->
    <context id="tables" targetRuntime="MyBatis3">
        <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- 配置数据库连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <!-- 生成 model 类,targetPackage 指定 model 类的包名, targetProject 指定
        生成的 model 放在 eclipse 的哪个工程下面-->
        <javaModelGenerator targetPackage="com.example.tspringboot.model"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>
        <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的
        包名, targetProject 指定生成的 mapper.xml 放在 eclipse 的哪个工程下面 -->
        <sqlMapGenerator targetPackage="com.example.tspringboot.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包
        名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.example.tspringboot.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 数据库表名及对应的 Java 模型类名 -->
        <table tableName="user" domainObjectName="User"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

配置mvn插件: pom.xml

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <!--mybatis generator插件配置文件位置,默认值${basedir}/src/main/resources/generatorConfig.xml-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>

展开maven依赖, 插件列表点mybatis生成,即可执行脚本.

生成后的目录

model/     # dao
    User.java
mapper/    # bean/pojo
    UserMapper.java
    UserMapper.xml

UserMapper.java

public interface UserMapper {
    int deleteByPrimaryKey(Integer id); //通过id删除

    int insert(User record);            //插入

    int insertSelective(User record);   //提供部分字段插入

    User selectByPrimaryKey(Integer id);//通过id查询

    int updateByPrimaryKeySelective(User record); //更新全部字段(详情可以看下xml)

    int updateByPrimaryKey(User record);          //更新部分字段
}

完成代码controller/service层

pom.xml

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

UserController.java

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/test01")
    @ResponseBody
    public User test01(Integer id) {
        return userService.getUserById(id);
    }
}

UserService.java

public interface UserService {
    public User getUserById(Integer id);
}

impl/UserServiceImpl.java

@Service
public class UserSerivceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
}

resources/application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root

mapper配置文件

方式1:

UserMapper.java

@Mapper
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

pom.xml

        <!--手动指定文件夹为resources-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

因为java目录下放xml,默认编译不会管xml文件. 做这个为了让xml编译后也被拷贝过去.

方式2

不用每个UserMapper.java 都指定@Mapper了
直接在全局指定即可.

@SpringBootApplication
@MapperScan("com.example.tspringboot.mapper")
public class TspringbootApplication {

方式3: mapper.xml放在resources/mapper/UserMapper.xml下

外加直接在全局指定即可

@SpringBootApplication
@MapperScan("com.example.tspringboot.mapper")

外加

mybatis.mapper-locations=classpath:mapper/*.xml

注: 测试时, 增删pom.xml记得刷新maven 测试前可以先mvn clean

小结:

1.mybatis需要开启自动扫描来创建dao对象到容器
2.java目录下xml编译后默认不会被拷贝
    解决方案:
        方法1.pom.xml配置让去拷贝
        方法2.直接把mapper放在resources下,并告诉springboot xml在这里(通过全局配置文件方式)

猜你喜欢

转载自www.cnblogs.com/iiiiiher/p/12924351.html