MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
理解MyBatis
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。 MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录.
Mybatis的功能架构分为三层:
1) API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
2) 数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
3) 基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。
在SpringBoot中集成Mybatis
<1>在Pom中添加依赖
添加Mybatis相关Jar包
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
添加Mysql jdbc相关Jar包
<properties> <mysql-connector>5.1.39</mysql-connector> </properties>
<!-- MySQL 连接驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency>
<2>为项目添加配置application.properties
spring.application.name=push.messagepush01 server.port=8080 spring.datasource.name = defaultDatasource4Phihome spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.maximum-pool-size = 100 spring.datasource.sql-script-encoding = UTF-8 spring.datasource.min-idle = 50 spring.datasource.initial-size = 50 spring.datasource.max-active = 100 spring.datasource.auto-commit = true spring.datasource.validation-query=SELECT 1 spring.datasource.test-on-borrow=false spring.datasource.test-while-idle=true spring.datasource.time-between-eviction-runs-millis=10000
<3>编写程序代码
<3.1>编写entity:
package com.phicomm.push.messagepush01.model.entity; public class AppDaoModel { private int app_id; private String registration_id; private String alias; private String tag; private String app_product_id; private String version; private String os_type; private long app_regdate=0L; private String pushcompany; private long app_lastpushdate=0L; private String app_wblist; private long create_time=0L; private long update_time=0L; public int getApp_id() { return app_id; } public void setApp_id(int app_id) { this.app_id = app_id; } public String getRegistration_id() { return registration_id; } public void setRegistration_id(String registration_id) { this.registration_id = registration_id; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getApp_product_id() { return app_product_id; } public void setApp_product_id(String app_product_id) { this.app_product_id = app_product_id; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getOs_type() { return os_type; } public void setOs_type(String os_type) { this.os_type = os_type; } public long getApp_regdate() { return app_regdate; } public void setApp_regdate(long app_regdate) { this.app_regdate = app_regdate; } public String getPushcompany() { return pushcompany; } public void setPushcompany(String pushcompany) { this.pushcompany = pushcompany; } public long getApp_lastpushdate() { return app_lastpushdate; } public void setApp_lastpushdate(long app_lastpushdate) { this.app_lastpushdate = app_lastpushdate; } public String getApp_wblist() { return app_wblist; } public void setApp_wblist(String app_wblist) { this.app_wblist = app_wblist; } public long getCreate_time() { return create_time; } public void setCreate_time(long create_time) { this.create_time = create_time; } public long getUpdate_time() { return update_time; } public void setUpdate_time(long update_time) { this.update_time = update_time; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } private int status; }
<3.2>编写Interface Service
package com.phicomm.push.messagepush01.service; import java.util.List; import com.phicomm.push.messagepush01.model.entity.AppDaoModel; public interface AppService { public List<AppDaoModel> getAllAppInfo(); public List<AppDaoModel> selectAppInfo(int app_id); public int addAppInfo(AppDaoModel appDaoModel); public int updateAppInfo(AppDaoModel appDaoModel); public int deleteAppInfo(int app_id); }
<3.3>编写Interface Mapper
package com.phicomm.push.messagepush01.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.phicomm.push.messagepush01.model.entity.AppDaoModel; public interface AppMapper { @Select("select * from phi_push_appinfo") public List<AppDaoModel> getAllAppInfo(); @Select("select * from phi_push_appinfo where app_id=#{app_id}") public List<AppDaoModel> selectAppInfo(@Param("app_id") int app_id); @Insert("insert into phi_push_appinfo(registration_id,alias,tag) values(#{appinfo.registration_id},#{appinfo.alias},#{appinfo.tag})") public int addAppInfo(@Param("appinfo") AppDaoModel appinfo); @Update("update phi_push_appinfo set registration_id=#{appinfo.registration_id},alias=#{appinfo.alias},tag=#{appinfo.tag} where app_id=#{appinfo.app_id}") public int updateAppInfo(@Param("appinfo") AppDaoModel appinfo); @Delete("delete from phi_push_appinfo where app_id=#{app_id}") public int deleteAppInfo(@Param("app_id") int app_id); }
<3.4>编写Service的实现
package com.phicomm.push.messagepush01.service.imp; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.phicomm.push.messagepush01.dao.AppMapper; import com.phicomm.push.messagepush01.model.entity.AppDaoModel; import com.phicomm.push.messagepush01.service.AppService; @Service public class AppServiceImp implements AppService{ @Resource private AppMapper mapper; @Override public List<AppDaoModel> selectAppInfo(int app_id) { // TODO Auto-generated method stub return mapper.selectAppInfo(app_id); } @Override public int addAppInfo(AppDaoModel appDaoModel) { // TODO Auto-generated method stub return mapper.addAppInfo(appDaoModel); } @Override public int updateAppInfo(AppDaoModel appDaoModel) { // TODO Auto-generated method stub return mapper.updateAppInfo(appDaoModel); } @Override public int deleteAppInfo(int app_id) { // TODO Auto-generated method stub return mapper.deleteAppInfo(app_id); } @Override public List<AppDaoModel> getAllAppInfo() { // TODO Auto-generated method stub return mapper.getAllAppInfo(); } }
<3.5>编写Controller
package com.phicomm.push.messagepush01.controller; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.phicomm.push.messagepush01.model.entity.AppDaoModel; import com.phicomm.push.messagepush01.service.AppService; @RestController @RequestMapping("/appinfo") public class AppInfoController { private static Logger logger=LogManager.getLogger(AppInfoController.class); @Autowired private AppService appService; @RequestMapping("/getall") public List<AppDaoModel> getAllAppInfo(){ logger.info("get all app info!"); List<AppDaoModel> a=appService.getAllAppInfo(); for(AppDaoModel x:a) { logger.debug("Alias is: "+x.getAlias()); logger.debug("Tag is: "+x.getTag()); } logger.info("select successed!"); return a; } @RequestMapping("/get") public List<AppDaoModel> getAppInfo(int app_id){ return null; } @RequestMapping("/add") public String regAppInfo(AppDaoModel appDaoModel) { return ""; } @RequestMapping("/upd") public String updAppInfo(AppDaoModel appDaoModel) { return ""; } @RequestMapping("/del") public String delAppInfo(int app_id) { return ""; } }
注意项目中要单独写一个Main类用来加载Main方法
<3.6>编写入口类
package com.phicomm.push.messagepush01; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; @SpringBootApplication(scanBasePackages= { "com.phicomm.push.messagepush01.**" }) @PropertySources(@PropertySource(value="classpath:application.properties",ignoreResourceNotFound=true)) @MapperScan("com.phicomm.push.messagepush01.dao.**") public class PhiPushMain { public static void main(String[] args) { SpringApplication.run(PhiPushMain.class, args); } }
<4>测试连接数据库
首次创建的数据库会报错,提示连不上 Access denied for user 'root'@'localhost' (using password:YES)
因为用jdbc连接数据库的时候root都不太好使,可以参考网络上的调整root的权限,也可以直接新建一个用户专门用来进行远程连接