springboot(二)mybatis使用

x33g5p2x  于2021-12-17 转载在 其他  
字(9.0k)|赞(0)|评价(0)|浏览(420)

新建项目:sprinboot-mybatis ,springboot版本2.1

首先我们新建数据库test,添加一张user表,插入两条数据

CREATE TABLE `user` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL DEFAULT '',
  `password` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`uid`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=1518867 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`uid`,`username`,`password`) values (1,'zhangsan','123456'),(2,'lisi','123456');

接下来我们在pom.xml文件中加入我们的mybatis、mysql依赖,这里我们使用druid作为数据源,因为我本地的数据库是5的版本,所以mysql依赖也使用的5的版本

<!--mybatis 依赖-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!--mysql-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.44</version>
		</dependency>
		<!--druid-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
		<!--web依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--分页插件-->
		<dependency>
			<groupId>Maven.com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>4.1.6</version>
		</dependency>

接下来打开配置文件 src/main/resources/application.propreties 加入以下配置

#项目端口
server.port=8081
#数据配置
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

接下来我们使用 mybatis-generator 自动生成代码插件生成我们的实体以及mapper.xml文件

在pom.xml中加入依赖

<!--配置文件生成插件-->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.3.5</version>
    <configuration>
	<!--配置文件的位置-->
	<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
		<verbose>true</verbose>
		<overwrite>true</overwrite>
	</configuration>
</plugin>

注意哦,这里我们是加载build节点下的plugins 下

接下来在src/main/resouces目录下新增generatorConfig.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>
    <!--mysql 连接数据库jar 这里选择自己本地位置-->
    <classPathEntry location="F:\work\Repositories\Maven\mysql\mysql-connector-java\5.1.42\mysql-connector-java-5.1.42.jar" />

    <!--mybatis.mysql.springboot-mybatis-druid -->
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="123456">
        </jdbcConnection>
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
           NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.example.springbootmybatis.model" targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置
           如果maven工程只是单独的一个工程,targetProject="src/main/java"
           若果maven工程是分模块的工程,targetProject="所属模块的名称",例如:
           targetProject="ecps-manager-mapper",下同-->
        <sqlMapGenerator targetPackage="mysql" targetProject="src/main/resources/mybatis">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.springbootmybatis.mapper" targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 生成的表名 -->
        <table schema="" tableName="user"></table>

    </context>

</generatorConfiguration>

保证配置无误后点击 :mybatis-generator:generte

看到这个就代表成功啦!

   

在我们的启动文件上加上@MapperScan("com.example.springbootmybatis.mapper")注解,里面是你mapper.java文件所在的包名因为如果不加的话mapper.java类就扫描不了哦,当让你也可以在每个mapper.java类上夹@mapper注解 ,但是那样太麻烦了!

接下来我们在src/main/resources目录下新建mybatis的配置文件mybatis-config.xml,内容如下

<?xml version="1.0" encoding="UTF-8" ?>
<!--
       Copyright 2015-2016 the original author or authors.
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
-->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>

接下来我们编写编写mybatis的配置代码 ,在com.example.springbootmybatis新建config包,增加MyBatisConfig.java类,内容如下

@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
	@Resource
    DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource((DataSource) dataSource);
        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties props = new Properties();
        props.setProperty("reasonable", "true");
        props.setProperty("supportMethodsArguments", "true");
        props.setProperty("returnPageInfo", "check");
        props.setProperty("params", "count=countSql");
        pageHelper.setProperties(props);
        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});
       //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //mybatis配置文件位置
        	bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
        	//mapper.xml位置
            bean.setMapperLocations(resolver.getResources("classpath:mybatis/mysql/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Override
    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建了一个SqlSessionFactory和一个SqlSessionTemplate,为了支持注解事务,
     * 增加了@EnableTransactionManagement注解,
     * 并且反回了一个PlatformTransactionManagerBean
     */
}

接下来我们编写代码实现简单的增删查改

public interface UserService {
    List<User> getList();
    void add(User user);
    void del(int id);
    void update(User user);

}
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper mapper;

    @Override
    public List<User> getList() {
        UserExample example = new UserExample();
        return mapper.selectByExample(example);
    }

    @Override
    public void add(User user) {
        mapper.insertSelective(user);
    }

    @Override
    public void del(int id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(User user) {
        mapper.updateByPrimaryKey(user);
    }
}
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/list")
    public List<User> getList() {
        return userService.getList();
    }

    @PostMapping("/add")
    public String add(User user) {
        try {
            userService.add(user);
            return "add success";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @PutMapping("/update")
    public String update(User user) {
        try {
            userService.update(user);
            return "update success";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @DeleteMapping("/del")
    public String del(@RequestParam("id") Integer id) {
        try {
            userService.del(id);
            return "del success";
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

现在的项目的整体目录如下

到此,我们的mybatis整合实战就结束了,大家测试时别忘了请求方式哦!

源码地址:https://gitee.com/xu0123/springboot2    

相关文章