java技术--SpringBoot整合Mybatis访问MySQL注解方式(07)

1.MyBatis是一款优秀的持久层框架

(1)它支持定制化SQL、存储过程以及高级映射
(2)几乎避免了所有的JDBC代码和手动设置参数以及获取结果集
(3)使用简单的XML或注解来配置和映射原生信息
    <1>将接口和Java的POJOs(普通的 Java对象)映射成数据库中的记录

2.引入依赖

(1)在pom文件引入mybatis-spring-boot-starter的依赖:
       <dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter<artifactId>
			<version>1.3.0</version>
		</dependency>
(2)在pom文件引入数据库连接依赖:
       <!-- MySQL Driver驱动包 -->
       <dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- 阿里系的Druid依赖包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.29</version>
		</dependency>	
(3)application.properties配置文件中引入数据源
    # 驱动配置信息		
	spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    # 启用mybatis的命名策略(即驼峰命名法)
    mybatis.configuration.map-underscore-to-camel-case=true
    # 连接池的配置信息
    # 初始化大小,最小,最大
    spring.datasource.initialSize=5
    spring.datasource.minIdle=5
    spring.datasource.maxActive=20
    # 配置获取连接等待超时的时间
    spring.datasource.maxWait=60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    spring.datasource.timeBetweenEvictionRunsMillis=60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    spring.datasource.minEvictableIdleTimeMillis=300000
    spring.datasource.validationQuery=SELECT 1 FROM DUAL
    spring.datasource.testWhileIdle=true
    spring.datasource.testOnBorrow=false
    spring.datasource.testOnReturn=false
(4)这样,springboot就可以访问数据了  
     <1>不同的数据库连接池属性可能不同
     <2>常用的数据库连接池:C3P0,Druid,DBCP,BoneCP,Proxool
        2.1.其中C3P0、DBCP常和Hbernate结合使用

3.创建数据库表(略,自行创建)
4.具体实现:通过注解的形式实现

1)创建实体:
    public class Account {
       private int id ;
       private String name ;
       private double money;
       setter...
       getter...}2)Dao层
   @Mapper
   public interface AccountMapper {
    @Insert("insert into account(name, money) values(#{name}, #{money})")
    int add(@Param("name") String name, @Param("money") double money);
    @Update("update account set name = #{name}, money = #{money} where id = #{id}")
    int update(@Param("name") String name, @Param("money") double money, @Param("id") int  id);
    @Delete("delete from account where id = #{id}")
    int delete(int id);
    @Select("select id, name as name, money as money from account where id = #{id}")
    Account findAccount(@Param("id") int id);
    @Select("select id, name as name, money as money from account")
    List<Account> findAccountList();}3)Service层  
     @Service
    public class AccountService {
      @Autowired
      private AccountMapper accountMapper;
      public int add(String name, double money) {
        return accountMapper.add(name, money);}
      public int update(String name, double money, int id) {
        return accountMapper.update(name, money, id);}
      public int delete(int id) {
        return accountMapper.delete(id);}
      public Account findAccount(int id) {
        return accountMapper.findAccount(id);}
      public List<Account> findAccountList() {
        return accountMapper.findAccountList();}}  
(4)Controller层,构建restful API    
    @RestController
    @RequestMapping("/account")
    public class AccountController {
       @Autowired
       AccountService accountService;
       @RequestMapping(value = "/list", method = RequestMethod.GET)
       public List<Account> getAccounts() {
        return accountService.findAccountList();}
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
       public Account getAccountById(@PathVariable("id") int id) {
        return accountService.findAccount(id);}
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
       public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "money", required = true) double money) {
        int t= accountService.update(name,money,id);
        if(t==1) {return "success";}else {return "fail";}}
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
       public String delete(@PathVariable(value = "id")int id) {
        int t= accountService.delete(id);
        if(t==1) {return "success";}else {return "fail";}}
    @RequestMapping(value = "", method = RequestMethod.POST)
       public String postAccount(@RequestParam(value = "name") String name,@RequestParam(value = "money") double money)
     {int t= accountService.add(name,money);
       if(t==1) {return "success";}else {return "fail";}}}       
  1. SpringBoot中@Mapper和@Repository的使用区别
(1)@Mapper和@Repository是常用的两个注解,两者都是用在dao上
(2)@Repository需要在Spring中配置扫描地址,然后生成Dao层的Bean才能被注入到Service层中
      举例:在启动类中配置扫描地址:
      @SpringBootApplication   //添加启动类注解
      @MapperScan("com.anson.dao")  //配置mapper扫描地址
       public class application{
         public static   void main(String[] args){
        SpringApplication.run(application.class,args);}}  
(3)@Mapper不需要配置扫描地址,通过xml里面的namespace里面的接口地址,生成了Bean后注入到Service层中
(4)也就是@Repository多了一个配置扫描地址的步骤
发布了178 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq591009234/article/details/104334940