整合Mybaties增删改查

1、填写pom.xml

  1. <!-- mybatis依赖jar包 -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>1.3.2</version>
  6. </dependency>
  7.  
  8. <!-- web项目依赖jar包 -->
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-web</artifactId>
  12. </dependency>
  13.  
  14. <!-- 热部署依赖jar包 -->
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-devtools</artifactId>
  18. <scope>runtime</scope>
  19. </dependency>
  20.  
  21. <!-- mysql连接jar包 -->
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <scope>runtime</scope>
  26. </dependency>
  27.  
  28. <!-- 阿里巴巴druid数据源 -->
  29. <dependency>
  30. <groupId>com.alibaba</groupId>
  31. <artifactId>druid</artifactId>
  32. <version>1.1.6</version>
  33. </dependency>

pom文件

2、填写application.properties

  1. #数据驱动可配也可以不配,因为系统会自动识别
  2. #spring.datasource.driver-class-name =com.mysql.jdbc.Driver
  3.  
  4. spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
  5. spring.datasource.username =root
  6. spring.datasource.password =root
  7.  
  8. #springboot有自带数据源这个也可不配置
  9. spring.datasource.type =com.alibaba.druid.pool.DruidDataSource

配置连接属性

  1. #数据驱动可配也可以不配,因为系统会自动识别
  2. #spring.datasource.driver-class-name =com.mysql.jdbc.Driver
  3.  
  4. spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
  5. spring.datasource.username =root
  6. spring.datasource.password =root
  7.  
  8. #让控制台打印SQL语句,一般用于本地开发环境
  9. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  10. #springboot有自带数据源这个也可不配置
  11. spring.datasource.type =com.alibaba.druid.pool.DruidDataSource

3、User实体

  1. import java.util.Date;
  2. //用户实体
  3. public class User {
  4.  
  5. private int id;
  6.  
  7. private String name;
  8.  
  9. private String phone;
  10.  
  11. private int age;
  12.  
  13. private Date createTime;
  14.  
  15. public int getId() {
  16. return id;
  17. }
  18.  
  19. public void setId(int id) {
  20. this.id = id;
  21. }
  22.  
  23. public String getName() {
  24. return name;
  25. }
  26.  
  27. public void setName(String name) {
  28. this.name = name;
  29. }
  30.  
  31. public String getPhone() {
  32. return phone;
  33. }
  34.  
  35. public void setPhone(String phone) {
  36. this.phone = phone;
  37. }
  38.  
  39. public int getAge() {
  40. return age;
  41. }
  42.  
  43. public void setAge(int age) {
  44. this.age = age;
  45. }
  46.  
  47. public Date getCreateTime() {
  48. return createTime;
  49. }
  50.  
  51. public void setCreateTime(Date createTime) {
  52. this.createTime = createTime;
  53. }
  54. }

User实体

4.Springboot主类

  1. import org.mybatis.spring.annotation.MapperScan;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4.  
  5. //@MapperScan会自动扫描里面的包,而且应该是可以自动给每个类装配一个Bean对象
  6. @SpringBootApplication
  7. @MapperScan("com.jincou.mapper")
  8. public class MainApplication {
  9.  
  10. public static void main(String[] args) {
  11. SpringApplication.run(MainApplication.class, args);
  12. }
  13. }

5、UserMapper

  1. import java.util.List;
  2.  
  3. import org.apache.ibatis.annotations.Delete;
  4. import org.apache.ibatis.annotations.Insert;
  5. import org.apache.ibatis.annotations.Options;
  6. import org.apache.ibatis.annotations.Result;
  7. import org.apache.ibatis.annotations.Results;
  8. import org.apache.ibatis.annotations.Select;
  9. import org.apache.ibatis.annotations.Update;
  10.  
  11. import com.jincou.model.User;
  12.  
  13. /**
  14. * 功能描述:访问数据库的接口
  15. */
  16. public interface UserMapper {
  17.  
  18. //推荐使用#{}取值,不要用${},因为存在注入的风险
  19. @Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
  20. @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java对象的属性;keyColumn表示数据库的字段
  21. int insert(User user);
  22.  
  23. //column指数据库中的列,property是指实体的属性名,如果一致就不需要写
  24. @Select("SELECT * FROM user")
  25. @Results({
  26. @Result(column = "create_time",property = "createTime")
  27. })
  28. List<User> getAll();
  29.  
  30. @Select("SELECT * FROM user WHERE id = #{id}")
  31. @Results({
  32. @Result(column = "create_time",property = "createTime")
  33. })
  34. User findById(Long id);
  35.  
  36. @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
  37. void update(User user);
  38.  
  39. @Delete("DELETE FROM user WHERE id =#{userId}")
  40. void delete(Long userId);
  41.  
  42. }

6、UserServise层

  1. import com.jincou.model.User;
  2.  
  3. public interface UserService {
  4.  
  5. //这里只写了个add方法,其它的直接在控制层调用Dao层,正常开发流程都应该写在Service层
  6. public int add(User user);
  7.  
  8. }

UserServise

7、UserServiseImpl

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.stereotype.Service;
  3.  
  4. import com.jincou.mapper.UserMapper;
  5. import com.jincou.model.User;
  6. import com.jincou.service.UserService;
  7.  
  8. @Service
  9. public class UserServiceImpl implements UserService{
  10.  
  11. //因为主类的@MapperScan方法,所以自动为UserMapper装配了一个userMapper对象
  12. @Autowired
  13. private UserMapper userMapper;
  14.  
  15. //这里你传过去的时候user的id为null,而insert之后传回回来的user会把数据库中的id值带回来,真强大
  16. @Override
  17. public int add(User user) {
  18. userMapper.insert(user);
  19. int id = user.getId();
  20. return id;
  21. }
  22. }

8.Controller类

  1. import java.util.Date;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8.  
  9. import com.jincou.mapper.UserMapper;
  10. import com.jincou.model.JsonData;
  11. import com.jincou.model.User;
  12. import com.jincou.service.UserService;
  13.  
  14. @RestController
  15. @RequestMapping("/api/v1/user")
  16. public class UserController {
  17.  
  18. //在UserServiceImpl定义了@Service实现类所以可以得到默认首字母小写的对象
  19. @Autowired
  20. private UserService userService;
  21.  
  22. @Autowired
  23. private UserMapper userMapper;
  24.  
  25. /**
  26. * 功能描述: user 保存接口
  27. */
  28. @GetMapping("add")
  29. public Object add(){
  30.  
  31. User user = new User();
  32. user.setAge(11);
  33. user.setCreateTime(new Date());
  34. user.setName("张三");
  35. user.setPhone("1880177");
  36. int id = userService.add(user);
  37.  
  38. return id;
  39. }
  40.  
  41. /**
  42. * 功能描述:查找全部用户
  43. * 这里和下面是直接调用跳过Servise层,直接到DAO层
  44. */
  45. @GetMapping("findAll")
  46. public Object findAll(){
  47.  
  48. return userMapper.getAll();
  49. }
  50.  
  51. /**
  52. * 查找单个用户
  53. */
  54. @GetMapping("find_by_id")
  55. public Object findById(long id){
  56. return userMapper.findById(id);
  57. }
  58.  
  59. /**
  60. * 删除单个用户
  61. */
  62. @GetMapping("del_by_id")
  63. public Object delById(long id){
  64. userMapper.delete(id);
  65. return "";
  66. }
  67.  
  68. /**
  69. *更新用户
  70. */
  71. @GetMapping("update")
  72. public Object update(String name,int id){
  73. User user = new User();
  74. user.setName(name);
  75. user.setId(id);
  76. userMapper.update(user);
  77. return "";
  78. }
  79. }

测试

1.准备好数据库数据:

  1. #Sql脚本
  2. CREATE TABLE `user` (
  3. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  4. `name` varchar(128) DEFAULT NULL COMMENT '名称',
  5. `phone` varchar(16) DEFAULT NULL COMMENT '用户手机号',
  6. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  7. `age` int(4) DEFAULT NULL COMMENT '年龄',
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

2测试结果

插入用户,看后台的sql语句

文献

1、开发mapper:参考语法http://www.mybatis.org/mybatis-3/zh/java-api.html

2、使用starter, maven仓库地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter

3、 相关资料:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

4、 整合问题集合:https://my.oschina.net/hxflar1314520/blog/1800035

https://blog.csdn.net/tingxuetage/article/details/80179772

想太多,做太少,中间的落差就是烦恼。想没有烦恼,要么别想,要么多做。上尉【9】

springBoot(7)---整合Mybaties增删改查的更多相关文章

  1. SpringBoot操作MongoDB实现增删改查

    本篇博客主讲如何使用SpringBoot操作MongoDB. SpringBoot操作MongoDB实现增删改查 (1)pom.xml引入依赖 <dependency> <group ...

  2. springboot整合mybatis增删改查(四):完善增删改查及整合swgger2

    接下来就是完成增删改查的功能了,首先在config包下配置Druid数据连接池,在配置之前先把相关配置在application.preperties中完善 application.preperties ...

  3. ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)

    在springmvc+spring+mybatis里整合ztree实现增删改查,上一篇已经写了demo,以下就仅仅贴出各层实现功能的代码: Jsp页面实现功能的js代码例如以下: <script ...

  4. SSHE框架整合(增删改查)

    1.前期准备:jar包(c3p0.jdbc ,各个框架) web.xml文件:spring的   转码的,和Struts2的过滤器 <?xml version="1.0" e ...

  5. Spring4.0+Hibernate4.0+Struts2.3整合包括增删改查案例,解决整合中出现的异常

    源码下载:http://download.csdn.net/detail/cmcc_1234/7034775 ======================Application.xml======== ...

  6. springboot整合mybatis增删改查(二):springboot热部署

    SpringBoot整合热部署 传统情况下, 我们用idea运行springboot程序时, 如果我们需要修改类里的方法,或者其他信息 我们需要修改完保存,并且重启springboot,有时候会很浪费 ...

  7. springboot整合mybatis增删改查(三):mybatis逆向工程

    上一篇已经把项目基本框架完善,接下来就是利用Mybatis Generator逆向工程进行mybatis的整合. 我们在创建项目开始的时候已经勾选web,mybatis,sql等,但是这些依赖还是不够 ...

  8. springboot整合mybatis增删改查(一):项目创建

    新建 打开 IDEA 工具,通过 File -> New -> Project->Spring Initializr 主要步骤包括: 选择 Spring Initializr 项目 ...

  9. spring mvc hibernate spring 整合的增删改查+后台校验+bootstrap

    整合之前先知道大概的思路,首先要知道每个框架的重点要点. 1.首先我们从数据库开始 --创建数据库 create database gs --创建表 create table food ( id ,) ...

随机推荐

  1. mysql的orde by 按照指定状态顺序排序

    要求按照以下顺序排序 审核中->审核拒绝->待放款->放款失败->待还款->已结清->已逾期 { id:80, label:'审核中'},{ id:100, lab ...

  2. HDU-6060 RXD and dividing

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6060   多校的题目,每次只能写两道SB题,剩下的要么想不到,要么想到了,代码不知道怎么实现,还是写的 ...

  3. 招聘ETL开发工程师

    上班地点徐汇 本科以上学历 3年以上ETL开发经验熟悉Oracle数据库,精通PL  SQL开发与优化,熟悉Vertica或者GreenPlum库优先 熟悉数据库性能优化,有海量数据处理经验优先 自荐 ...

  4. 如何方便的在windows测试python程序

    听说python的网页抓取模块很强大,我想试试看看能给我的网络优化工作带来什么大的帮助,于是跟随廖雪峰老师开始学习python(地址查看),因为我用的是window系统,这就给程序的测试带来了很多麻烦 ...

  5. ubuntu18.04搭建nfs

    1.服务端安装 #apt-get update -y #apt-get install -y nfs-kernel-server #apt-get enable nfs-kernel-server 2 ...

  6. flume接收http请求,并将数据写到kafka

    flume接收http请求,并将数据写到kafka,spark消费kafka的数据.是数据采集的经典框架. 直接上flume的配置: source : http channel : file sink ...

  7. ExtJS中listener方法和handler方法的区别

    listener方法和handler方法的区别在文档中的说明的太玄乎了,看不懂 listeners监听能够对一个click Event事件添加任意多个的事件响应处理函数 而handler处理只能够通过 ...

  8. IntelliJ IDEA的main方法,for循环,syso的快捷键

    原文链接:http://blog.csdn.net/tiantiandjava/article/details/42269173 今天偶然发现了IntelliJ中 创建main函数的快捷键,依次还有f ...

  9. STM32 HAL库的使用心得

    1.I2C函数中HAL_I2C_Mem_Write和HAL_I2C_Master_Transmit有啥区别?{ 使用HAL_I2C_Mem_Write等于 先使用HAL_I2C_Master_Tran ...

  10. win7 docker Toolbox 启动Docker Quickstart Terminal 失败!

    解决办法: 在windows下安装docker Toolbox 启动Docker Quickstart Terminal 失败! 主要是用如下文件启动,临时解决,或设置环境变量