Spring Boot入门及整合mybatis

栏目: Java · 发布时间: 6年前

内容简介:Spring Boot入门及整合mybatis

Spring Boot入门

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置,使用Spring Boot可以大大的提供软件的开发效率。

特点:

1. 创建独立的Spring应用程序

2. 嵌入的Tomcat,无需部署WAR文件

3. 简化Maven配置

4. 自动配置Spring

5. 提供生产就绪型功能,如指标,健康检查和外部配置

6. 绝对没有代码生成和对XML没有要求配置

Spring Boot实例

首先依次选择New->Spring starter project创建spring boot 项目。

Spring Boot入门及整合mybatis

点击Next,选择spring boot的版本,这里选择1.5.9 版本,选择starter,通过搜索找到web 并勾选,点击完成即可。

Spring Boot入门及整合mybatis

项目结构说明

创建好的项目,结构如下:

Spring Boot入门及整合mybatis
  • Src/main/java。编写代码存放的目录,自动生成了程序入口代码 SpringBootDemo1Application.java。
  • Src/main/resources。资源文件存放目录,自动生成了配置文件 application.properties
  • Src/test/java。测试代码存放目录,自动生成了测试代码SpringBootDemo1ApplicationTests.java

pom文件简介

spring boot项目默认使用maven来构建,其中spring boot依赖的部分配置如下:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>

引入web依赖

Web starter依赖引入,会增加web容器、springweb、springmvc、jackson-databind等相关的依赖。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

它们的依赖层级关系如图:

Spring Boot入门及整合mybatis

引入测试依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

启动程序入口说明

创建SpringBoot项目时,系统会默认生成一个启动程序,该类使用main函数来启动spring boot程序。例如:SpringBootDemoApplication代码

@SpringBootApplication
public class SpringBootDemoApplication {

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

增加controller

然后在与SpringBootDemoApplication同级的包下新建一个controller。

public class DemoController {
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
}

启动SpringBootDemoApplication

在SpringBootDemoApplication文件上右键选择run as->Spring Boot App即可启动项目。

Spring Boot入门及整合mybatis

在浏览器中输入: http://localhost:8080/ 即可访问。

application.properties

打开项目src目录下的resources文件,会发现一个application.properties文件,该文件是spring boot系统配置文件。例如:

server:
  port: 8080
  context-path: /


spring:
   datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/db_demo
      username: root
      password: xxxx
   jpa:
     hibernate.ddl-auto: update
     show-sql: true
   thymeleaf:
    cache: false

整合mybatis

其实使用IDE工具可以直接添加mybatis相关的依赖,此次使用pom文件的方式来实现。打开pom文件,在pom.xml中添加如下依赖:

<!-- mybatisjar -->

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

<!-- mysql连接jar -->

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>

在application.properties 文件下 添加 mysql 的连接配置(切记不要在行尾留有空格,否则报com.mysql.jdbc.Driver Class Not Found error,其实只是含有空格导致找不到类)。

然后,在项目的src目录下新建一个User类.

public class User {
    private Integer id;
    private String name;
    private Integer age;
    //省略get和set
}

添加UserMapper接口:

@Mapper
public interface UserMapper {
    // 通过Parameter新增
    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insertByParameter(@Param("name") String name, @Param("age") Integer age);

    // 通过Map新增
    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
    int insertByMap(Map<String, Object> map);  

    // 通过Object新增
    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insertByObject(User user);

    // Delete By Id
    @Delete("DELETE FROM user WHERE id =#{id}")
    void delete(Long id);

    // Update
    @Update("UPDATE user SET age=#{age} WHERE name=#{name}")
    void update(User user);

    // Find by Parameter
    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    // 通过@Results,绑定返回值
    @Results({
        @Result(property = "name", column = "name"),
        @Result(property = "age", column = "age")
    })
    @Select("SELECT name, age FROM user")
    List<User> findAll();  
}

最后是协议个测试文件:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void add() throws Exception {
        // insert by parameter
        userMapper.insertByParameter("zhangShan", 20);

        // insert by object
        User user = new User();
        user.setAge(21);
        user.setName("LiSi");
        userMapper.insertByObject(user);

        // insert by map
        Map<String, Object> map = new HashMap<>();
        map.put("name", "huangwu");
        map.put("age", 22);
        userMapper.insertByMap(map);

        User zhangShan = userMapper.findByName("zhangShan");
        Assert.assertEquals(20, zhangShan.getAge().intValue());
        User LiSi = userMapper.findByName("LiSi");
        Assert.assertEquals(21, LiSi.getAge().intValue());
        User huangwu = userMapper.findByName("huangwu");
        Assert.assertEquals(22, huangwu.getAge().intValue());
    }

    @Test
    public void udpate() throws Exception {
        User user = userMapper.findByName("zhangShan");
        user.setAge(50);
        userMapper.update(user);

        user = userMapper.findByName("zhangShan");
        Assert.assertEquals(50, user.getAge().intValue());

        userMapper.delete(user.getId());
    }

    @Test
    public void findAll() throws Exception {
        List<User> users = userMapper.findAll();
        Assert.assertNotNull(users);
    }

}

以上所述就是小编给大家介绍的《Spring Boot入门及整合mybatis》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Information

The Information

James Gleick / Vintage / 2012-3-6 / USD 16.95

James Gleick, the author of the best sellers Chaos and Genius, now brings us a work just as astonishing and masterly: a revelatory chronicle and meditation that shows how information has become th......一起来看看 《The Information》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具