扩展:SpringBoot+MyBatis框架+mysql数据库的整合(注解版)

开发环境:

开发工具:Intellij IDEA 2017.2.3
JDK : 1.8.0_144
spring boot 版本 : 1.5.10.RELEASE
maven : 3.2.3

SpringBoot集成MyBatis加入基础依赖:

mybatis:

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.1</version>
</dependency>

MySQL:

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.38</version>
</dependency>
数据库配置:

application.yml
spring:
  datasource:
     url: jdbc:mysql://192.168.1.59:3306/test?useUnicode=true&characterEncoding=UTF-8
     username: root
     password: 123456
     driver-class-name: com.mysql.jdbc.Driver

在Mysql数据库中创建数据表:

CREATE DATABASE mytest;
 USE mytest; 
CREATE TABLE t_user(
     id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
     name VARCHAR(255) NOT NULL , 
     password VARCHAR(255) NOT NULL ,
     phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
使用Mybatis:

创建映射对象User
/** * User实体映射类 
    * Created by Administrator on 2017/11/24. 
    */ 
public class User { 
    private Integer id; 
    private String name; 
    private String password; 
    private String phone; 
    //省略 get 和 set ... 
}

创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作

/**
    * User映射类
    * Created by Administrator on 2017/11/24.
    */
@Mapper
public interface UserMapper {
     @Select("SELECT * FROM T_USER WHERE PHONE = #{phone}")
    User findUserByPhone(@Param("phone") String phone);

     @Insert("INSERT INTO T_USER(NAME, PASSWORD, PHONE) VALUES(#{name}, #{password}, #{phone})")
    int insert(@Param("name") String name, @Param("password") String password, @Param("phone") String phone);
}

创建单元测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {

   @Autowired
   private UserMapper userMapper;

   @Test
   public void insert(){
      userMapper.insert("hy","123456","123456789");
   }
   @Test
   public void getBYphone(){
      User user =userMapper.findUserByPhone("123456789");
      Assert.assertEquals("hy", user.getName());
      System.out.println(user.getName()+":"+user.getPassword());
   }
}
注解版是最简单的,只需要在mapper接口种直接写sql就可以

注意:配置版、通用mapper版、配置文件版,这三版可以混合使用,



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值