这两天学习了一下SpringBoot的相关内容,记录一下
1.创建一个SpringBoot项目后,引入依赖(其中lombok插件需要自己安装)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jt.1902</groupId> <artifactId>springboot-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--添加属性注入依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!--引入插件lombok 自动的set/get/构造方法插件 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--支持热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!--引入数据库驱动 --> <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.12</version> </dependency> <!--spring整合mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.6</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.创建如下结构文件
(1)表的结构:
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` char(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(11) NULL DEFAULT NULL, `sex` char(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `cc`(`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 56 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; SET FOREIGN_KEY_CHECKS = 1;
(2)编写实体类com.jt.pojo.User
@Accessors 注解用来配置lombok如何产生和显示getters和setters的方法。
chain表示生成的方法名是setxx() getxx()的样子
@Data //set/get/toString @Accessors(chain = true) //链式加载 @NoArgsConstructor //无参构造 @AllArgsConstructor //有参构造 @TableName("user") //对象与数据表完成映射 public class User implements Serializable{ @TableId(type=IdType.AUTO) //主键自动 private Integer id; //@TableField("name") private String name; //@TableId("age") private Integer age; private String sex;
}
(3)编写接口com.jt.mapper.UserMapper
该接口继承自mybatisplus的BaseMapper接口
public interface UserMapper extends BaseMapper<User>{ //查询全部的user表中的数据 List<User> findAll(); /** * 规定: Mybatis中要求数据传参必须是单值 * 方案: * 0.本身就是单值 id * 1.利用对象将数据封装 id age name * 2.将数据封装为map集合. @Param("key")int id * 3.将数据封装为array/list * @param user * @return */ @Insert("insert into user values(null,#{name},#{age},#{sex})") int insertUser(User user); //实现用户修改 age=18的 名称改为xxx @Update("update user set name=#{name} where age=#{age}") int updateUser(User user); }
(4)编写在resources文件中创建mybatis/mapper/UserMapper.xml文件
namespace与接口对应,id与方法名对应
<?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"> <mapper namespace="com.jt.mapper.UserMapper"> <select id="findAll" resultType="com.jt.pojo.User"> select * from user </select> <!-- <insert id="insertUser"> insert into user values(null,#{name},#{age},#{sex}) </insert> --> <!-- <update id="updateUser"> update user set name=#{name} where age=#{age} </update> --> </mapper>
(5)编写接口com,jt.service.UserService
public interface UserService { List<User> findAll(); int insertUser(User user); int updateUser(User user); }
(6)编写实现类com.jt.service.UserServiceImpl
在实现类里利用@AutoWired注解进行自动装配,而不是在接口上
@Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.findAll(); } @Override public int insertUser(User user) { return userMapper.insertUser(user); } @Override public int updateUser(User user) { return userMapper.updateUser(user); } }
(7)编写API接口com.jt.Controller.UserController
@RestController注解相当于@ResponseBody + @Controller合在一起的作用
@RestController public class UserController { @Autowired private UserService userService; //用户通过localhost:8090/findAll获取用户数据 @RequestMapping("/findAll") public List<User> findAll(){ return userService.findAll(); } //用户新增 public int insertUser(User user) { return userService.insertUser(user); } public int updateUser(User user) { return userService.updateUser(user); }
(8)在启动类中加入对接口的扫描
@SpringBootApplication //为mapper接口创建代理对象 @MapperScan("com.jt.mapper") public class SpringBootRun { public static void main(String[] args) { SpringApplication.run(SpringBootRun.class, args); } }
3.配置文件
在resources中创建application.yml文件,并编写配置
server: port: 8090 servlet: context-path: / #引入数据源配置 spring: datasource: #引入druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true username: root password: root #mybatis-plush配置 mybatis-plus: #配置别名包 type-aliases-package: com.jt.pojo #配置mapper映射 mapper-locations: classpath:/mybatis/mappers/*.xml #开启驼峰映射 configuration: map-underscore-to-camel-case: true #添加日志输出 logging: level: com.jt.mapper: debug
4.启动并测试
(1)测试UserMapper接口
@SpringBootTest @RunWith(SpringRunner.class) public class TestCRUD { @Autowired //从容器中取值 private UserController userController; @Test public void insertUser() { User user = new User(); user.setName("小橘子").setSex("女").setAge(18); userController.insertUser(user); System.out.println("入库成功!!!!!"); } //测试修改 @Test public void testUpdate() { User user = new User(); user.setAge(18).setName("哈利波特!!!"); userController.updateUser(user); } }
(2测试MybatisPlus
@SpringBootTest @RunWith(SpringRunner.class) public class TestMybatisPlus { @Resource private UserMapper userMapper; @Test public void insert() { User user = new User(); user.setName("mybatisplus"); user.setAge(19); user.setSex("男"); int rows = userMapper.insert(user); System.out.println("影响行数:"+rows); } /**查询用户列表信息 将对象中不为null的属性当做where条件 条件:age=18 关键字说明: = eq,> gt,< lt,ge >=,le <= */ @Test public void testFind() { //1.方式1.使用对象封装 //User user = new User(); //user.setAge(18); //2.直接使用字段赋值 QueryWrapper<User> queryWrapper = new QueryWrapper<User>(); //测试等于 //queryWrapper.eq("age",18); //测试大于 queryWrapper.ge("age",18); List<User> userList = userMapper.selectList(queryWrapper); System.out.println(userList); } /** * 3.数据更新 将年龄为18岁的用户改19岁 * entity:需要修改数据的值 * updateWrapper 条件构造器 充当where条件 */ @Test public void testUpdate() { User user = new User(); user.setAge(19); UpdateWrapper<User> updateWrapper = new UpdateWrapper<>(); updateWrapper.eq("age", 18); userMapper.update(user, updateWrapper); } //删除name字段为null的数据 @Test public void deleteUser() { QueryWrapper<User> queryWrapper = new QueryWrapper<User>(); queryWrapper.isNull("name"); userMapper.delete(queryWrapper); } }
@Data //set/get/toString @Accessors(chain = true) //链式加载 @NoArgsConstructor //无参构造 @AllArgsConstructor //有参构造 @TableName("user") //对象与数据表完成映射 public class User implements Serializable{ @TableId(type=IdType.AUTO) //主键自动 private Integer id; //@TableField("name") private String name; //@TableId("age") private Integer age; private String sex; }