mybatis+springboot中使用mysql的实例

在软件开发中,数据库的引入是必不可少的,这里来展现一下通过mybatis框架在springboot中使用mysql,具有一定的参考价值,感兴趣的可以了解一下

在软件开发中,数据库的引入是必不可少的,其中又属mysql使用最为广泛,而在springboot中,集成使用mysql的方式有很多(例如jpa),这里来展现一下通过mybatis框架在springboot中使用mysql。

依赖引入

首先在使用初始化工程的时候加入mybatis、mysql相关的依赖,如下所示:

   org.springframework.bootspring-boot-starter org.mybatis.spring.bootmybatis-spring-boot-starter2.0.1 mysqlmysql-connector-javaruntime com.alibabadruid1.1.10

配置引入

在配置方面,使用springboot的自动配置功能配置数据源,如下所示:

 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://127.0.0.1:3306/sbac_master?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true username: root password: 1234 driver-class-name: com.mysql.cj.jdbc.Driver 

配置了数据源,剩下的就是引入mybatis了。mybatis的引入同样可以使用自动配置(MybatisProperties)来实现,这里选择不全部使用自动配置属性,而是引入mybatis的配置文件方式注入属性。

 mybatis: config-location: classpath:mybatis-config.xml mapper-locations: classpath:com/lazycece/sbac/mysql/data/dao/*/mapper/*.xml 

这里给出一个mybatis的简单配置,有关更多的配置属性,可以参考mybatis的XML配置。

      

案例实现

这里给出一个简单的案例(用户信息的插入和查询)来展现mapper层的实现,实体就不在这里展示了。mapper接口如下:

 @Mapper public interface UserDao { void insert(User user); User findByUsername(@Param("username") String username); } 

同时需要在主函数上加入注解@MapperScan来扫描我们mapper:

 @SpringBootApplication @MapperScan(basePackages = {"com.lazycece.sbac.mysql.data.dao"}) public class SpringbootAcMysqlSimpleApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAcMysqlSimpleApplication.class, args); } } 

mapper的sql实现,这里选择用xml的方式实现,当然也可以选择用注解方式(这里对应的@Select,@Insert):

   id,create_time,update_time,username,password,telephone,status,editor  INSERT  INTO user (create_time,update_time,username,password,telephone,status,editor) VALUE (#{createTime},#{updateTime},#{username},#{password},#{telephone},#{status},#{editor}); 

细心者可发现,前面配置引入中引入mapper是写的classpath:com/lazycece/sbac/mysql/data/dao//mapper/.xml包名路径,使用这种方式默认情况下是不会成功的,因为包路径下文件默认只会编译java文件,所以需要在pom文件中加入配置使得在工程编译时将其包含进编译后的路径下。

    src/main/java com/lazycece/sbac/mysql/data/dao/*/mapper/*.xml

案例源码

案例源码地址: https://github.com/lazycece/springboot-actual-combat/tree/master/springboot-ac-mysql/springboot-ac-mysql-simple

以上就是mybatis+springboot中使用mysql的实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java