springboot-mybatis annotation

    MyBatis is an open source project of apache, iBatis . In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis. Migrated to Github in November 2013  .

    MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) to records in the database

Create maven project




Create the following structure:



Introduce the mybatis dependency package in 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.springboot</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
        <mybatis-spring.version>1.3.2</mybatis-spring.version>
    </properties>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--引入数据库连接-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.0</version>
        </dependency>
    </dependencies>

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

</project>

Add database configuration in application.properties

#服务端口
#server.port=8088
#server.context-path=/springboot

#mysql数据连接
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=20


编写实体类

package com.example.springboot.mybatis.entity;

public class User {
   private String id;

   private String username;

   private String password;

   private String email;

   /**
    * 是否可用(0禁用,1可用)
    */
   private Integer useable;

   /**
    * 创建时间
    */
   private String addtime;

   /**
    * 登陆时间
    */
   private String logintime;

   /**
    * 登陆IP
    */
   private String loginip;
}

编写dao数据库操作类

 
 
package com.example.springboot.mybatis.dao;

import com.example.springboot.mybatis.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;


/**
 * 基于注解方式编写sql语句,开发中不适用,维护成本太高
 */
public interface UserDaoMapper {

   @Select("select id,username as username,password from t_user where id=#{id}")
   public User getUserById(Integer id);

   
   @Select("select id,username as username,password from t_user where username=#{name}")
   public List<User> getUserByPage(String name);
// 自增长id,使用options配置返回id值
// @Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
   @Insert("insert into t_user(id,username,password) values(#{id},#{username},#{password})")
   public void saveUser(User user);
}

编写service类

package com.example.springboot.mybatis.service;

import com.example.springboot.mybatis.dao.UserDaoMapper;
import com.example.springboot.mybatis.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
* @desc 通过注解方式查询数据库
* @Author wangsh
* @date 2018/5/5 23:12
* @return 
*/
@Service
public class UserService {

   @Autowired
   private UserDaoMapper userDaoMapper;

   public User getUserById(Integer id) {
      return userDaoMapper.getUserById(id);
   }

   public List<User> getUserByPage(String name) {
      return userDaoMapper.getUserByPage(name);
   }

   public void saveUser(User user) {
      userDaoMapper.saveUser(user);
   }
}

编写controller类

package com.example.springboot.mybatis.web;

import com.example.springboot.mybatis.entity.User;
import com.example.springboot.mybatis.service.UserService;
import com.example.springboot.mybatis.service.UserService2;
import com.example.springboot.mybatis.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * @desc mybatis 操作数据库查询示例
 * @Author wangsh
 * @date 2018/5/5 23:18
 * @return
 */
@RestController
@RequestMapping("/user")
public class UserController {

   /**
    * 通过注解方式查询数据库
    */
   @Autowired
   private UserService userService;

   @RequestMapping("/getUserById")
   @ResponseBody
   public User getUserById(Integer id) {
      User User = userService.getUserById(id);
      return User;
   }

   @RequestMapping("/getUserByPage")
   @ResponseBody
   public List<User> getUserByPage(String name) {
      // 设置分页
      PageHelper.startPage(1, 2);
      List<User> users = userService.getUserByPage(name);
      return users;
   }

   @RequestMapping("/save")
   @ResponseBody
   public User save() {
      User user = new User();
      user.setId(UUIDUtil.getUUID());
      user.setUsername("lisi");
      user.setPassword("lisi");
      userService.saveUser(user);
      return user;
   }
}

编写启动服务类

启动完成如下:


数据库表:


通过浏览器访问: http://localhost:8080//user/getUserById?id=8376,返回结果表示操作数据库成功






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325577017&siteId=291194637