0


SpringBoot整合Mybaties增删改查

文章目录

使用 Java 开发或者学习过程中,最避免不了的是连接和操作数据库,此次,学习如何在Spring Boot中配置和使用Mybatis框架,提高开发效率。

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>

在这里插入图片描述

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实体

//用户实体publicclassUser{privateint id;privateString name;privateString phone;privateint age;privateDate createTime;publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicStringgetPhone(){return phone;}publicvoidsetPhone(String phone){this.phone = phone;}publicintgetAge(){return age;}publicvoidsetAge(int age){this.age = age;}publicDategetCreateTime(){return createTime;}publicvoidsetCreateTime(Date createTime){this.createTime = createTime;}}

4、Springboot主类

//@MapperScan会自动扫描里面的包,而且应该是可以自动给每个类装配一个Bean对象@SpringBootApplication@MapperScan("com.jincou.mapper")publicclassMainApplication{publicstaticvoidmain(String[] args){SpringApplication.run(MainApplication.class, args);}}

5、UserMapper

/**
     * 功能描述:访问数据库的接口
     */publicinterfaceUserMapper{//推荐使用#{}取值,不要用${},因为存在注入的风险@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")//keyProperty java对象的属性;keyColumn表示数据库的字段intinsert(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")})UserfindById(Long id);@Update("UPDATE user SET name=#{name} WHERE id =#{id}")voidupdate(User user);@Delete("DELETE FROM user WHERE id =#{userId}")voiddelete(Long userId);}

6、UserServise层

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

7、UserServiseImpl

@ServicepublicclassUserServiceImplimplementsUserService{//因为主类的@MapperScan方法,所以自动为UserMapper装配了一个userMapper对象@AutowiredprivateUserMapper userMapper;//这里你传过去的时候user的id为null,而insert之后传回回来的user会把数据库中的id值带回来,真强大@Overridepublicintadd(User user){
        userMapper.insert(user);int id = user.getId();return id;}}

8、Controller类

@RestController@RequestMapping("/api/v1/user")publicclassUserController{//在UserServiceImpl定义了@Service实现类所以可以得到默认首字母小写的对象@AutowiredprivateUserService userService;@AutowiredprivateUserMapper userMapper;/**
     * 功能描述: user 保存接口
     */@GetMapping("add")publicObjectadd(){User user =newUser();
        user.setAge(11);
        user.setCreateTime(newDate());
        user.setName("张三");
        user.setPhone("1880177");int id = userService.add(user);return id;}/**
     * 功能描述:查找全部用户
     * 这里和下面是直接调用跳过Servise层,直接到DAO层
     */@GetMapping("findAll")publicObjectfindAll(){return userMapper.getAll();}/**
     * 查找单个用户
     */@GetMapping("find_by_id")publicObjectfindById(long id){return userMapper.findById(id);}/**
     * 删除单个用户
     */@GetMapping("del_by_id")publicObjectdelById(long id){
    userMapper.delete(id);return"";}/**
     *更新用户
     */@GetMapping("update")publicObjectupdate(String name,int id){User user =newUser();
        user.setName(name);
        user.setId(id);
        userMapper.update(user);return"";}}

测试

1.准备好数据库数据:

#Sql脚本CREATETABLE`user`(`id`int(11)unsignedNOTNULLAUTO_INCREMENT,`name`varchar(128)DEFAULTNULLCOMMENT'名称',`phone`varchar(16)DEFAULTNULLCOMMENT'用户手机号',`create_time`datetimeDEFAULTNULLCOMMENT'创建时间',`age`int(4)DEFAULTNULLCOMMENT'年龄',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=18DEFAULTCHARSET=utf8;

2测试结果

在这里插入图片描述

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

在这里插入图片描述


本文转载自: https://blog.csdn.net/weixin_44816664/article/details/130620763
版权归原作者 鹤冲天Pro 所有, 如有侵权,请联系我们删除。

“SpringBoot整合Mybaties增删改查”的评论:

还没有评论