springboot整合mybatis实现增删改查小案例

一、springboot简单hello world

1.1 使用springboot项目前提是必须学会使用maven,maven這里就不多说了 网上招一大堆教程

1.2 创建一个war包的maven项目,创建后在pox.xml添加如下jar

 

<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/maven-v4_0_0.xsd">

 

  <parent>

      <groupId>org.springframework.boot</groupId>

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

      <version>1.5.2.RELEASE</version>

  </parent>

 

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ibigsea</groupId>

  <artifactId>bootdao</artifactId>

  <packaging>war</packaging>

  <version>0.0.1-SNAPSHOT</version>

 

    <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.1.1</version> 

        </dependency> 

        <!-- Springboot 热部署 在运行的时候,修改了代码能自动更新-->

        <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-devtools</artifactId>

          <optional>true</optional>

        </dependency>

 

        <dependency> 

            <groupId>org.springframework.boot</groupId> 

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

            <scope>test</scope> 

        </dependency> 

    </dependencies> 

 

    <build> 

        <plugins> 

            <plugin> 

                <groupId>org.springframework.boot</groupId> 

                <artifactId>spring-boot-maven-plugin</artifactId> 

            </plugin> 

        </plugins> 

    </build> 

</project>

 

 

1.3 创建一个springboot的程序入口启动类:如下

package com.ibigsea.bootdao; 

 

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.transaction.annotation.EnableTransactionManagement; 

 

 

@SpringBootApplication

public class UserApplication { 

    public static void main(String[] args) { 

       SpringApplication.run(UserApplication.class, args);

    } 

}

 

1.4 创建一个controller类测试,如下

 

package com.ibigsea.bootdao.controller;

 

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

@RequestMapping("users")

public class UserController {

   

       @RequestMapping("hello")

       public String hello(){

              return "Hello World";

       }

}

 

浏览器访问结果如下:

访问地址:http://localhost:8086/users/hello

 

至此一个简单的springboot的应用已完成,下面整合mybatis实现简单的增删改查案例

 

 

二、springboot整合mybatis案例

 2.1 首先需要在pox.xml导入jar  在hello world案例之上添加如下几个jar包

<!-- 数据库连接池 --> 

        <dependency> 

            <groupId>com.alibaba</groupId> 

            <artifactId>druid</artifactId> 

            <version>1.0.5</version> 

        </dependency> 

<!-- mysql 驱动 --> 

        <dependency> 

            <groupId>mysql</groupId> 

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

        </dependency> 

2.2 在src/main/resources目录下创建一个application.properties文件,内容如下

//端口设置

server.port=8086

server.servlet-path=/

logging.level.org.springframework=DEBUG

 

//数据库配置

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.url = jdbc:mysql://127.0.0.1:3306/taotao?useUnicode=true&characterEncoding=utf-8

spring.datasource.username = root

spring.datasource.password = 12345

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.initialSize=5

spring.datasource.minIdle=5

spring.datasource.maxActive=20

spring.datasource.maxWait=60000

spring.datasource.timeBetweenEvictionRunsMillis=60000

spring.datasource.minEvictableIdleTimeMillis=300000

spring.datasource.validationQuery=SELECT 1 FROM DUAL

spring.datasource.testWhileIdle=true

spring.datasource.testOnBorrow=false

spring.datasource.testOnReturn=false

spring.datasource.poolPreparedStatements=true

spring.datasource.maxPoolPreparedStatementPerConnectionSize=20

spring.datasource.filters=stat,wall,log4j

spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

 

 

 

//mybatis配置

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

mybatis.type-aliases-package=com.ibigsea.bootdao.entity

2.3 entity类

package com.ibigsea.bootdao.entity; 

 

import java.io.Serializable; 

 

public class User implements Serializable { 

 

    private static final long serialVersionUID = 8809101560720973267L; 

     

    private Integer id; 

     

    private String userName; 

     

    private Integer age; 

 

    public User() {

      // TODO Auto-generated constructor stub

   }

   

 

   public User(String userName, Integer age) {

      super();

      this.userName = userName;

      this.age = age;

   }

 

 

 

   public Integer getId() { 

        return id; 

    } 

 

    public void setId(Integer id) { 

        this.id = id; 

    } 

 

    public String getUserName() { 

        return userName; 

    } 

 

    public void setUserName(String userName) { 

        this.userName = userName; 

    } 

 

    public Integer getAge() { 

        return age; 

    } 

 

    public void setAge(Integer age) { 

        this.age = age; 

    } 

 

    @Override 

    public String toString() { 

        return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]"; 

    } 

     

     

2.4 mapper接口类

可以在类加上@Mapper注解  也可以在springboot应用的程序入口类@MapperScan(“com.ibigsea.bootdao.mapper”)

  

package com.ibigsea.bootdao.mapper; 

import java.util.List; 

import org.apache.ibatis.annotations.Mapper; 

import com.ibigsea.bootdao.entity.User; 

public interface UserMapper { 

   

       /**

        * 新增

        * @param user

        * @return

        */

    int save(User user); 

   

    /**

        * 根据Id查询

        * @param user

        * @return

        */

    User selectById(Integer id); 

   

    /**

        * 根据Id修改

        * @param user

        * @return

        */

    int updateById(User user); 

   

    /**

        * 删除

        * @param user

        * @return

        */

    int deleteById(Integer id); 

   

    /**

        * 查询所有

        * @param user

        * @return

        */

    List<User> queryAll(); 

   

   

    /**

     * 根据username查询

     */

    User findByName(String username);

2.5 UserMapper.xml

<?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.ibigsea.bootdao.mapper.UserMapper"

     

    <insert id="save" parameterType="com.ibigsea.bootdao.entity.User"

        insert into user(username,age) values(#{userName,jdbcType=VARCHAR},#{age,jdbcType=NUMERIC}) 

    </insert> 

     

    <select id="selectById" resultType="com.ibigsea.bootdao.entity.User"

        select * from user where id = #{id,jdbcType=NUMERIC} 

    </select> 

     

    <update id="updateById" parameterType="com.ibigsea.bootdao.entity.User"

        update user set   

        username = #{userName,jdbcType=VARCHAR} , 

        age = #{age,jdbcType=NUMERIC} 

        where id = #{id,jdbcType=NUMERIC} 

    </update> 

     

    <delete id="deleteById"

        delete from user where id = #{id,jdbcType=NUMERIC} 

    </delete> 

     

    <select id="queryAll" resultType="com.ibigsea.bootdao.entity.User"

        select * from user 

    </select> 

   

    <select id="findByName" resultType="com.ibigsea.bootdao.entity.User"

        select * from user where username=#{userName} 

    </select> 

   

</mapper>

2.6 业务接口类

  与2.4的mapper接口类内容一致

2.7 业务接口类的实现

package com.ibigsea.bootdao.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import com.ibigsea.bootdao.entity.User;

import com.ibigsea.bootdao.mapper.UserMapper;

import com.ibigsea.bootdao.service.UserService;

@Transactional

@Service

public class UserServiceImpl implements UserService{

   

       @Autowired

       private UserMapper userMapper;

      

       @Override

       public int save(User user) {

              int myuser= userMapper.save(user);

              //测试事务管理

              //int i =1/0;

              return myuser;

       }

       @Override

       public User selectById(Integer id) {

              return userMapper.selectById(id);

       }

   

       @Override

       public int updateById(User user) {

              return userMapper.updateById(user);

       }

   

       @Override

       public int deleteById(Integer id) {

              return userMapper.deleteById(id);

       }

       @Override

       public List<User> queryAll() {

              return userMapper.queryAll();

       }

       @Override

       public User findByName(String username) {

              return userMapper.findByName(username);

       }

}

此处配置了事物管理 需要在springboot入口类添加@EnableTransactionManagement 开启事物管理

2.8 控制层

package com.ibigsea.bootdao.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.ibigsea.bootdao.entity.User;

import com.ibigsea.bootdao.service.UserService;

@RestController

@RequestMapping("users")

public class UserController {

   

       @Autowired

       private UserService userService;

      

       @RequestMapping("hello")

       public String hello(){

              return "Hello World";

       }

      

       @RequestMapping("/add/{name}/{age}")

       public User insert(@PathVariable("name")String name,@PathVariable Integer age){

              userService.save(new User(name,age));

              return userService.findByName(name);

       }

      

       @RequestMapping("/findById/{id}")

       public User findById(@PathVariable("id") Integer id){

              return userService.selectById(id);

       }

      

       @RequestMapping("/deleteById/{id}")

       public void deleteById(@PathVariable("id") Integer id){

              userService.deleteById(id);

       }

      

       @RequestMapping("/updateById/{id}")

       public void updateById(@PathVariable("id") Integer id){

              User user = new User();

              user.setId(id);

              user.setAge(100);

              user.setUserName("xiaoguo");

              userService.updateById(user);

       }

      

       @RequestMapping("getUserList")

       public List<User> getUserList(){

              return userService.queryAll();

       }

}

2.9 spring boot 程序入口启动类

package com.ibigsea.bootdao; 

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.transaction.annotation.EnableTransactionManagement; 

@SpringBootApplication

@EnableTransactionManagement

@MapperScan("com.ibigsea.bootdao.mapper")

public class UserApplication { 

    public static void main(String[] args) { 

       SpringApplication.run(UserApplication.class, args);

    } 

}

至此springboot整合mybatis整合完成,项目的目录结构如下:

 

运行结果如下:

原文地址:https://www.cnblogs.com/guohuide/p/7403291.html