整合Mybaties增删改查

1、填写pom.xml

         <!-- mybatis依赖jar包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <!-- web项目依赖jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- 热部署依赖jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency> <!-- mysql连接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> <!-- 阿里巴巴druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

pom文件

2、填写application.properties

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

配置连接属性

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

3、User实体

import java.util.Date;
//用户实体
public class User { private int id; private String name; private String phone; private int age; private Date createTime; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}

User实体

4.Springboot主类

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

5、UserMapper

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.jincou.model.User; /**
* 功能描述:访问数据库的接口
*/
public interface UserMapper { //推荐使用#{}取值,不要用${},因为存在注入的风险
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java对象的属性;keyColumn表示数据库的字段
int insert(User user); //column指数据库中的列,property是指实体的属性名,如果一致就不需要写
@Select("SELECT * FROM user")
@Results({
@Result(column = "create_time",property = "createTime")
})
List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(column = "create_time",property = "createTime")
})
User findById(Long id); @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
void update(User user); @Delete("DELETE FROM user WHERE id =#{userId}")
void delete(Long userId); }

6、UserServise层

import com.jincou.model.User;

public interface UserService {

    //这里只写了个add方法,其它的直接在控制层调用Dao层,正常开发流程都应该写在Service层
public int add(User user); }

UserServise

7、UserServiseImpl

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.jincou.mapper.UserMapper;
import com.jincou.model.User;
import com.jincou.service.UserService; @Service
public class UserServiceImpl implements UserService{ //因为主类的@MapperScan方法,所以自动为UserMapper装配了一个userMapper对象
@Autowired
private UserMapper userMapper; //这里你传过去的时候user的id为null,而insert之后传回回来的user会把数据库中的id值带回来,真强大
@Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
}
}

8.Controller类

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.jincou.mapper.UserMapper;
import com.jincou.model.JsonData;
import com.jincou.model.User;
import com.jincou.service.UserService; @RestController
@RequestMapping("/api/v1/user")
public class UserController { //在UserServiceImpl定义了@Service实现类所以可以得到默认首字母小写的对象
@Autowired
private UserService userService; @Autowired
private UserMapper userMapper; /**
* 功能描述: user 保存接口
*/
@GetMapping("add")
public Object add(){ User user = new User();
user.setAge(11);
user.setCreateTime(new Date());
user.setName("张三");
user.setPhone("1880177");
int id = userService.add(user); return id;
} /**
* 功能描述:查找全部用户
* 这里和下面是直接调用跳过Servise层,直接到DAO层
*/
@GetMapping("findAll")
public Object findAll(){ return userMapper.getAll();
} /**
* 查找单个用户
*/
@GetMapping("find_by_id")
public Object findById(long id){
return userMapper.findById(id);
} /**
* 删除单个用户
*/
@GetMapping("del_by_id")
public Object delById(long id){
userMapper.delete(id);
return "";
} /**
*更新用户
*/
@GetMapping("update")
public Object update(String name,int id){
User user = new User();
user.setName(name);
user.setId(id);
userMapper.update(user);
return "";
}
}

测试

1.准备好数据库数据:

#Sql脚本
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT '名称',
`phone` varchar(16) DEFAULT NULL COMMENT '用户手机号',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`age` int(4) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) 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. 一次性获取PPT图片方法

    XXX.ppt 改成 XXX.zip 或者 XXX.rar 解压,查看文件夹即可

  2. PostgreSQL时间段查询

    1.今日 select * from "表名" where to_date("时间字段"::text,'yyyy-mm-dd')=current_date 2. ...

  3. APP界面设计 大概总结

    APP界面设计大概总结 首先,你得有个Android Studio 其次,你得学会有耐心的对它 最后,要适应它习惯它了解它 来看看APP的基本步骤 先有资源 再是界面布局 下来承载布局Activity ...

  4. ubuntu18.04静态ip设置

    1.配置文件 vi /etc/netplan/-cloud-init.yaml network: ethernets: enp129s0f0: addresses: [] dhcp4: true op ...

  5. Unity3D中AssetBundle应用

    工程中的模型等资源转化为Prefab后,打包成AssetBundle,可以大幅降低资源的空间占有度,并且提高资源加载的效率. 一.AssetBundle的打包 先看下打包Prefab的脚本代码,这段脚 ...

  6. shell传递参数

    简单介绍python的脚本传参 我们知道python脚本传递参数,有一个很方便的方式-sys.argv.它将脚本本身名字和后面的各项参数都放入一个列表. 使用的时候,索引这个列表就可以了.例如: py ...

  7. 20155205 郝博雅 《网络对抗技术》Exp1 PC平台逆向破解

    20155205 郝博雅 <网络对抗技术>Exp1 PC平台逆向破解 一.实验准备 1. 掌握NOP.JNE.JE.JMP.CMP汇编指令的机器码 NOP:NOP指令即"空指令& ...

  8. js基础知识1:标识符 注释

    何为标识符:意思是标记识别的的符号,简称标识符,主要的用途声明变量,函数的名字,属性以及函数中的参数. 标识符的规则1:首先第一个字符必须是字母(abcABC),_(下划线),$(美元符号).不能是( ...

  9. BAT:通过连接符处理判断OR的关系

    使用情况说明: 适用于对某个文件夹下不同的文件夹(名称)做不同的处理,但存在需要对其中多个文件夹(名称)进行相同处理的情况 例子中的目录结构: .\1.2.3 -- 文件夹.\a.b.c -- 文件夹 ...

  10. 转 Refresh Excel Pivot Tables Automatically Using SSIS Script Task

    Refresh Excel Pivot Tables Automatically Using SSIS Script Task https://www.mssqltips.com/sqlservert ...