美文网首页
springboot项目与mysql整合,并使用mybatis框

springboot项目与mysql整合,并使用mybatis框

作者: 高疯疯疯 | 来源:发表于2019-01-11 17:03 被阅读0次

    1. 安装mysql数据库

      mac上可以通过brew命令安装mysql

    2. 安装好数据库后,让项目与数据库建立连接需要引入依赖

    ```

            <!-- 连接数据库所需包-->

            <dependency>

                <groupId>mysql</groupId>

                <artifactId>mysql-connector-java</artifactId>

                <version>5.1.6</version>

            </dependency>

    ```

    3. 资源文件的创建。资源配置文件都是放在resources文件夹下的。资源配置文件的后缀是.properties。命名方式的话一般都是在名称后面加上-dev、-test、-prod以表示在开发环境、测试环境以及线上环境的配置文件。举例,创建一个application.properties文件,在该文件内,可以指定目前处于active状态的配置文件是哪个。比如如下内容则代表,生效的是开发环境配置资源

    ```

    spring.profiles.active=dev

    ```

    然后在dev文件中配置连接数据库的相关属性,内容如下:

    ```

    # 数据库连接

    spring.datasource.url=jdbc:mysql://localhost:3306/chat?characterEncoding=utf8&useSSL=false

    spring.datasource.username=root

    spring.datasource.password=root

    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

    spring.datasource.tomcat.max-wait=10000

    spring.datasource.tomcat.max-active=50

    spring.datasource.tomcat.max-idle=50

    spring.datasource.tomcat.test-on-borrow=true

    spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

    ```

    上述内容表示的是,连接本地的chat数据库。chat数据库的用户名以及密码分别是root、root

    4. 接下来就是项目数据如何和mysql之间进行交互。在这里不会写原始的jdbc操作语句。而是选择ORM框架mybatis

    5. 项目要使用mybatis首先也要引入依赖

    ```

            <!-- mybatis所需包依赖-->

            <dependency>

                <groupId>org.mybatis.spring.boot</groupId>

                <artifactId>mybatis-spring-boot-starter</artifactId>

                <version>1.1.1</version>

            </dependency>

    ```

    6. 项目中要使用mybatis有两种方式一种是xml文件,一种是注解。在该项目中使用后者。

    7. 首先需要建一张数据库表,用于我们练习增删改查操作。在这里我们举例建一个用户信息表,首先新建一个chat数据库

    ```sql

    CREATE DATABASE `chat`;

    ```

    选中指定字符集,防止插入中文产生乱码

    ```sql

    set names utf8;

    ```

    然后选中使用该数据库

    ```sql

    use chat

    ```

    然后输入下述语句创建一张用户信息表

    ```sql

    CREATE TABLE `user` (

      `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id',

      `userId` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '用户id',

      `username` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户名',

      `password` varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户密码',

      `salt` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '盐',

      `phone` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户手机号',

      `email` varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户邮箱',

      `portraitUrl` varchar(256) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户头像地址',

      `status` smallint(1) NOT NULL DEFAULT '0' COMMENT '用户帐号状态',

      `createTime` bigint(20) NOT NULL DEFAULT '0' COMMENT '创建时间',

      `updateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',

      `nickname` varchar(32) COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT '用户昵称',

      PRIMARY KEY (`id`),

      UNIQUE KEY `uniq_user_id` (`userId`),

      UNIQUE KEY `uniq_username` (`username`),

      UNIQUE KEY `uniq_phone` (`phone`),

      KEY `idx_user_id` (`userId`),

      KEY `idx_username` (`username`),

      KEY `idx_phone` (`phone`),

      KEY `idx_email` (`email`)

    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='用户信息表';

    ```

    8. 数据库表建好之后需要在项目中建立与其映射的实体类。在项目中新建mapper包,然后新建一个User实体类。在生成实体类时,我们可以使用Lombok框架,省去多余的get set等方法的生成,使代码看起来不会过于臃肿。

    首先导入Lombok的maven依赖

    ```

            <!-- 实体类自动生成get set toString等方法的框架-->

            <dependency>

                <groupId>org.projectlombok</groupId>

                <artifactId>lombok</artifactId>

                <version>1.16.18</version>

                <scope>provided</scope>

            </dependency>

    ```

    然后在Idea中安装Lombok插件,preference->Plugins->lombok Plugin 安装完毕后重启idea

    最后建立User实体类,记住一定要添加@Data注解。

    ```

    @Data

    public class User {

        private Long id;

        private Long userId;

        private String username;

        private String password;

        private String salt;

        private String phone;

        private String email;

        private String portraitUrl;

        private Integer status;

        private String nickname;

        private Long createTime;

        private Long updateTime;

        public User() {

            id = null;

            userId = 0L;

            username = "";

            password = "";

            salt = "";

            phone = "";

            email = "";

            portraitUrl = "";

            status = 0;

            nickname = "";

            createTime = System.currentTimeMillis() / 1000;

        }

        public static class Status {

            public final static Integer UNUSE = 0;

            public final static Integer USED = 1;

        }

    }

    ```

    9. 新建mapper接口类,需要添加@Component注解和@Mapper注解,前者是将该接口类注册进spring中,使其依赖注入,后者是该类可以使用mybatis注解的标志。

    ```

    @Component

    @Mapper

    public interface UserMapper {

        /**

        * @Author:gaofeng

        * @Date:2019/1/11

        * @Description: 保存用户

        **/

        @Insert("INSERT INTO user(userId, username, password, salt, phone, email, portraitUrl, status, createTime) values" +

                "(#{userId}, #{username}, #{password}, #{salt}, #{phone}, #{email}, #{portraitUrl}, #{status}, " +

                "#{createTime})")

        public Integer saveUser(User user);

        /**

        * @Author:gaofeng

        * @Date:2019/1/11

        * @Description: 根据手机号查找用户

        **/

        @Select("SELECT * FROM user WHERE phone=#{phone}")

        public User selectUserByPhone(String phone);

        /**

        * @Author:gaofeng

        * @Date:2019/1/11

        * @Description: 根据用户名或者手机号查找用户

        **/

        @Select("SELECT * FROM user WHERE phone=#{0} OR username=#{1}")

        public User selectUserByPhoneOrUsername(String phone, String username);

    }

    ```

    10. 上面简单写了几个操作数据库的sql语句。到这里项目与mysql连接就基本完成了,接下来我们写个简单的接口测试一下。在这里找出我们之前写的HelloWordController,将UserMapper注入,然后在hello方法中完成新建一个简单实体类,并save的操作

    ```

    @RestController

    @RequestMapping(value = "/helloworld")

    public class HelloWordController {

        private UserMapper userMapper;

        @Autowired

        public HelloWordController(UserMapper userMapper) {

            this.userMapper = userMapper;

        }

        @RequestMapping(value = "/hello")

        public String hello() {

            User user = new User();

            user.setUsername("zhangsan");

            user.setPhone("17801020000");

            user.setPassword("123456");

            userMapper.saveUser(user);

            return "hello";

        }

    }

    ```

    11. 然后在浏览器中访问http://localhost:8080/helloworld/hello,然后去数据库中查询一下user表,你会发现多了一条记录。查询语句

    ```

    select * from user\G

    ```

    相关文章

      网友评论

          本文标题:springboot项目与mysql整合,并使用mybatis框

          本文链接:https://www.haomeiwen.com/subject/cjoxdqtx.html