美文网首页
Spring boot + Mybatis 整合(Intelli

Spring boot + Mybatis 整合(Intelli

作者: Scorpio_cc | 来源:发表于2018-07-02 15:36 被阅读0次
SpringBoot实战

Spring boot + Mybatis 整合

Spring boot+Mybatis,相对于原来的Spring+SpringMVC+Mybatis简单好多

一、java web开发环境搭建

参考教程:https://www.jianshu.com/p/39dec5a0ab55

二、Spring boot搭建

1、Intellij idea菜单栏File->new->project

创建新项目

2、选择左侧栏中spring initializr,右侧选择jdk版本,以及默认的Service URL,点击next。

选择JDK和默认URL

3、然后填写项目的Group、Artifact等信息,helloworld阶段选默认就可以了,点击next。

自定义包名

4、左侧点击Web选择web,SQL选择Mybatis、MYSQL(数据库用的是mysql,大家可以选择其他DB),点击next。

选择组件

5、填写Project name 等信息,然后点击Finish。

选择项目名称和地址

6、一个maven web项目就创建好了,目录结构如下:

项目创建完成

Spring boot就搭建好了,pom.xml里已经有了Spring boot的jar包,包括我们的mysql数据连接的jar包。Spring boot内置了类似tomcat这样的中间件,所以,只要运行DemoApplication中的main方法就可以启动项目了。

在src/main/java下新建目录com/demo/entity/User

package com.example.demo.entity;

public class User {
    private  String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

相同demo目录下新建controller/TestBootController

package com.example.demo.controller;

import com.example.demo.entity.User;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@RequestMapping("/boot")
public class TestBootController {
    @RequestMapping("/user")
    public User getUser(){
        User user = new User();
        user.setName("boot_test");
        return user;
    }
}

Spring boot启动默认是要加载数据源的,所以我们在src/main/resources下新建application.yml

数据库使用的是mysql。可根据自己的需求更换数据库

#默认使用配置
spring:
  profiles:
    active: dev
    
#公共配置与profiles选择无关
mybatis:
  typeAliasesPackage: com.example.demo.entity
  mapperLocations: classpath:mapper/*.xml
  
---  #分隔线不能少

#开发配置
spring:
  profiles: dev

  datasource:
    url: jdbc:mysql://localhost:3306/test       #数据库地址+数据库名字(自定义)
    username: root                              #帐号(自定义)
    password: root                              #密码(自定义)
    driver-class-name: com.mysql.jdbc.Driver    #驱动

将pom.xml中加载数据源的jar包先注释掉也可以。

/*<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.0</version>
</dependency>*/

最终结构springboot目录如下

启动DemoApplication的main方法,访问http://localhost:8080/boot/user即可

ps:如果自定义了包名等~复制代码请注意修改对应包名

三、整合Mybatis

1、集成druid,使用连接池。pom.xml中添加:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.0</version>
</dependency>

最终的pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

到此Spring boot 就完成整合了~ 可以运行测试下能否顺利运行。

2.用MyBatis Generator自动生成代码,或者自定义编写各层

最终目录请看文章最后

public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;
    
    //省略get set方法...
}

public interface UserDao {
    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);
}

UserMapper.xml 中注意替换成自己的User对象地址 type 和parameterType

<?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" >
<mapper namespace="com.xc.dao.UserDao" ><!--修改自定义地址 -->
    <resultMap id="BaseResultMap" type="com.xc.entity.User" ><!--修改自定义地址 -->
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>
    <sql id="Base_Column_List" >
        id, user_name, password, age
    </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from user_t
        where id = #{id,jdbcType=INTEGER}
    </select>
    <insert id="insertSelective" parameterType="com.xc.entity.User" ><!--修改自定义地址 -->
        insert into user_t
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="userName != null" >
                user_name,
            </if>
            <if test="password != null" >
                password,
            </if>
            <if test="age != null" >
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="userName != null" >
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
</mapper>

3.修改DemoApplication.java,添加扫描dao层接口。

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.demo.dao") //修改成自己的dao地址
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4.添加Service/impl 和Controller层

public interface UserService {
    public User getUserById(int userId);

    boolean addUser(User record);
}
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Override
    public User getUserById(int userId) {
        return userDao.selectByPrimaryKey(userId);
    }

    @Override
    public boolean addUser(User record) {
        boolean result = false;
        try {
            userDao.insertSelective(record);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  result;
    }
}

@RestController
@EnableAutoConfiguration
@RequestMapping("/boot")
public class TestBootController {
    @Resource
    private UserService userService;
    @RequestMapping("/user")
    @ResponseBody
    public User getUser(HttpServletRequest request, Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        return user;
    }
}

5.Mysql创建测试表和插入数据

DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
  `id` int(11) NOT NULL DEFAULT '0',
  `user_name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `age` int(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES ('0', 'bb', 'bb', '11');
INSERT INTO `user_t` VALUES ('1', 'aa', 'aaa', '11');

6.浏览器访问http://localhost:8080/boot/user?id=1

最终结果展示

7.最终项目结构图

最终项目结构图

相关文章

网友评论

      本文标题:Spring boot + Mybatis 整合(Intelli

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