⑥. Spring Boot整合 通用mapper
- ①. 通用Mapper的作者也为自己的插件编写了启动器,我们直接引入即可。在项目的 pom.xml 文件中加入如下依赖:
<!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
②. 改造UserMapper继承Mapper<User>
;
public interface UserMapper extends Mapper<User> { }
③. 修改启动引导类Application中的Mapper扫描注解;
package com.itheima; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; /* * Spring boot 工程都有一个启动引导类,这是工程的入口类 * 并在引导类上添加@SpringBootApplocation注解 * */ @SpringBootApplication /*@MapperScan("com.itheima.mapper")*/ @MapperScan("com.itheima.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
④. 修改User实体类添加jpa注解;
package com.itheima.pojo; import lombok.Data; import tk.mybatis.mapper.annotation.KeySql; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; //在编译阶段会根据注解自动生成对应的方法 ; @Data @Table(name="tb_user") public class User { @Id /*主键回填*/ @KeySql(useGeneratedKeys = true) private Long id; @Column //user_name-- userName private String userName; private String password; private String name; private Integer age; private String sex; private Date birthday; private String note; private Date created; private Date updated; }
⑤. 改造UserService实现业务功能;
@Service public class UserService { @Autowired private UserMapper userMapper; /*根据id查询*/ public User queryById(Long id){ return userMapper.selectByPrimaryKey(id); } /*保存用户*/ @Transactional public void saveUser(User user){ //选择性新增;如果属性为空,则改属性不会出现在insert语句中 userMapper.insert(user); } }
- ⑥. 注意:在启动引导类上面的mapper扫描注解 一定要修改为 通用mapper的扫描注解
[ import tk.mybatis.spring.annotation.MapperScan ]
- ⑦.整合测试
@RestController public class HelloController { @Autowired private UserService userService; @GetMapping("/user/{id}") public User queryById(@PathVariable Long id){ return userService.queryById(id); } }
⑦. Spring Boot项目部署
7>.Spring Boot项目部署
- ①. 需要添加打包组件将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package
<build> <plugins> <!-- 打jar包时如果不配置该插件,打出来的jar包没有清单文件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
②. 部署:java -jar 包名
java -jar 包名