springboot 学习笔记(四)

2019-01-15 07:04:02来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 

(四)springboot整合mybatis

    1、以mysql为例,在pom文件中添加如下依赖,依次为mybatis、jdbc、db pool依赖

        <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>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>    

    2、在application.properties 文件中进行配置,springboot2.0会自动匹配jdbc连接,也可以通过spring.datasource.driver-class-name =com.mysql.jdbc.Driver 进行设置

#数据库url
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
#用户名、密码
spring.datasource.username =root
spring.datasource.password =root
#如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource),配置为阿里数据源
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#输出log到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

    3、设置好之后,我们在数据库中创建一个user表

CREATE TABLE `user` (
              `id` int(15) unsigned NOT NULL AUTO_INCREMENT,
              `name` varchar(80) DEFAULT NULL COMMENT '用户姓名',
              `phone` varchar(16) DEFAULT NULL COMMENT '用户手机号',
              `createTime` datetime DEFAULT NULL COMMENT '创建时间',
              `age` int(4) DEFAULT NULL COMMENT '年龄',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

    4、写一个domain对象用于dao层操作user表

package com.zc.mybatis.domain;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;

public class User {

    private int id;

    private String name;

    private String phone;

    private int age;
    //设置日期格式
    @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
    private Date createTime;

    ......省略get、set方法

    5、创建接口类,用注解方式操作数据库

/**
 * 
 */
package com.zc.mybatis.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.zc.mybatis.domain.User;

public interface UserMapper {

    //添加用户

     @Insert("INSERT INTO user(name,phone,createTime,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
     @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //主键自增,生成的值将注入对象中  
     void insertUser(User user) throws Exception;

    //查询用户
    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(int id);
    //查询所有用户
    List<User> getUsers();
    //更新用户
    @Update("UPDATE user SET name=#{name},phone=#{phone},createTime=#{createTime},age=#{age} WHERE id =#{id}")
    void updateUser(User user);
    //删除用户
    @Delete("DELETE FROM user where id = #{id}")
    void deleteUserById(int id);    
}

    6、创建对应的servce层,对应增删改查对应写出方法就可以了,我这里只写接口实现,其中需要注意的是,userMapper需要通过IOC注入进行使用

    @Autowired
    private UserMapper userMapper;
  //增  
    @Override
    public int add(User user) {
        try {
            userMapper.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int id = user.getId();
        return id;
    }

  //查询    
    @Override
    public User getUserById(int id) {

        User user = userMapper.getUserById(id);
        return user;
    }
  //查询所有
    @Override
    public List<User> getUsers() {
        List<User> users = userMapper.getUsers();
        return users;
    }

   //删除
    @Override
    public void deleteUserById(Long id) {
        userMapper.deleteUserById(id);

    }
    //改
    @Override
    public void updateUser(User user) {
        
        userMapper.updateUser(user);

    }

    7、写对应controller,然后返回json格式,就可以从页面查看了,通过localhost:8080/user/add新增数据到数据库,然后访问localhost:8080/user/getUsers

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("add")
    public int add() {
        User user = new User();
        user.setAge(12);
        user.setName("张三");
        user.setPhone("888888888");
        user.setCreateTime(new Date());
        int id = userService.add(user);
        return id;
    }

    @GetMapping("getUserById")
    public User getUser(int id) {
        User user = userService.getUserById(id);
        System.out.println(user.getCreateTime().toString());
        return user;
    }

    @GetMapping("getUsers")
    public List<User> getUsers() {
        List<User> users = userService.getUsers();
        User user = null;
        for (int i = 0; i < users.size(); i++) {
            user = users.get(i);
            System.out.println("用户id:" + user.getId() + "姓名" + user.getName());
        }
        return users;

    }

    @GetMapping("deleteUserById")
    public void deleteUserById(Long id) {
        User user = null;
        
        int userId = Integer.parseInt(id.toString());

        user = userService.getUserById(userId);

        userService.deleteUserById(id);
        System.out.println("删除用户的用户名为:" + user.getName());

    }
    @GetMapping("addAcount")
    public void addAcount() {
        int id = userService.addAcount();
    
    }

}

 

 

 


原文链接:https://www.cnblogs.com/codingstudy/p/10265467.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java中的json使用

下一篇:01 HelloWorld