SpringBoot——SpringData中MyBatis框架的使用这里讲述的是三个框架:
- SpringBoot框架
- Spring框架
- SpringData框架
- MyBatis框架
实体类的封装:
package pojo; public class User { private int id; private String name; private String password; }
MyBatis数据库的连接
Pom.xml文件依赖:
<!--官方--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
MyBatis框架技术的依赖:
<!-- 导入MyBatis依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
项目结构图
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--比要时候要加上--> <!--suppress ALL --> <mapper namespace="com.mybatis.mapper.UserMapper.xml"> <!--查序--> <select id="queryUserList" resultType="User"> select * from user </select> <!--增加--> <insert id="addUse" parameterType="User"> INSERT INTO `mybatis`.`user`(`name`, `password`) VALUES (#{name}, #{password}) </insert> <!--修改--> <update id="updateUser" parameterType="User"> UPDATE `mybatis`.`user` SET `name` =#{name}, `password` =#{password} WHERE `id` = #{id} </update> <!--删除--> <delete id="deleteUser" parameterType="int"> delete from user where id = #(id] </delete> </mapper>
package mapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import pojo.User; import java.util.List; //@Mapper : 表示本类是一个 MyBatis 的 Mapper Dao层 @Mapper @Repository public interface UserMapper { //查 List<User> queryUserList(); User queryUserById(int id); //增 int addUser(User user); //改 int updateUser(User user); //删 int deletUser(int id); }
package controller; import mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import pojo.User; import java.util.List; @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/queryUserList") public List<User> qUserList(){ List<User> userList = userMapper.queryUserList(); for (User user : userList) { System.out.println(user); } return userList; } }
package com.mybatis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Springboot05MybatisApplication { public static void main(String[] args) { SpringApplication.run(Springboot05MybatisApplication.class, args); } }