Mybatis入门配置

简介: Mybatis入门配置

ec091454685711a3146d4ac8d03ffd07.png

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)      基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。


e7e80a4f9699701a2d341f1c000a4914.png


在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



108317f930a272514f22fe6aab4117d6.png

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;
}


View Code

<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);
}


View Code

<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);
}


View Code

<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();
    }
}


View Code

<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 "";
    }
}


View Code

注意项目中要单独写一个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);
    }
}


View Code

<4>测试连接数据库


首次创建的数据库会报错,提示连不上 Access denied for user 'root'@'localhost' (using password:YES)


因为用jdbc连接数据库的时候root都不太好使,可以参考网络上的调整root的权限,也可以直接新建一个用户专门用来进行远程连接


b63b2a0c7a626494cf3a71d05d4d3b17.png


24a0d09faa2b736731cf5c24462612b0.png


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
XML Java 数据库连接
MyBatis的常见配置
MyBatis 常见配置包括数据库连接、类型别名、映射器等核心模块,合理配置可提升开发效率与系统性能。主要内容涵盖核心配置文件结构、关键配置项详解及配置优先级说明。
1040 4
|
Oracle 关系型数据库 Java
【YashanDB知识库】Mybatis-Plus适配崖山配置
【YashanDB知识库】Mybatis-Plus适配崖山配置
|
SQL 缓存 Java
【吐血整理】MyBatis从入门到精通
本文介绍了 MyBatis 的使用指南,涵盖开发环境搭建、基础操作实例和进阶特性。首先,详细描述了 JDK 和 IDE 的安装及依赖引入,确保项目顺利运行。接着,通过创建用户表和实体类,演示了 CRUD 操作的全流程,包括查询、插入、更新和删除。最后,深入探讨了动态 SQL 和缓存机制等高级功能,帮助开发者提升数据库交互效率和代码灵活性。掌握这些内容,能显著提高 Java 编程中的数据库操作能力。
2237 4
|
Java 数据库连接 微服务
微服务——MyBatis配置——事务管理
本段内容主要介绍了事务管理的两种类型:JDBC 和 MANAGED。JDBC 类型直接利用数据源连接管理事务,依赖提交和回滚机制;而 MANAGED 类型则由容器全程管理事务生命周期,例如 JEE 应用服务器上下文,默认会关闭连接,但可根据需要设置 `closeConnection` 属性为 false 阻止关闭行为。此外,提到在使用 Spring + MyBatis 时,无需额外配置事务管理器,因为 Spring 模块自带的功能可覆盖上述配置,且这两种事务管理器类型均无需设置属性。
350 0
|
Java 数据库连接 数据库
微服务——MyBatis配置——多环境配置
在 MyBatis 中,多环境配置允许为不同数据库创建多个 SqlSessionFactory。通过传递环境参数给 SqlSessionFactoryBuilder,可指定使用哪种环境;若忽略,则加载默认环境。`environments` 元素定义环境配置,包括默认环境 ID、事务管理器和数据源类型等。每个环境需唯一标识,确保默认环境匹配其中之一。代码示例展示了如何构建工厂及配置 XML 结构。
329 0
|
缓存 Java 数据库连接
微服务——MyBatis配置——常见配置
本文介绍了 MyBatis 的常见配置及其加载顺序。属性配置优先级为:方法参数传递的属性 &gt; resource/url 属性中配置 &gt; properties 元素中指定属性。同时列举了多个关键配置项,如 `cacheEnabled`(全局缓存开关)、`lazyLoadingEnabled`(延迟加载)、`useGeneratedKeys`(使用 JDBC 自动生成主键)等,并详细说明其作用、有效值及默认值。这些配置帮助开发者优化 MyBatis 的性能与行为。
347 0
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
775 18
|
SQL XML Java
菜鸟之路Day33一一Mybatis入门
本文是《菜鸟之路Day33——Mybatis入门》的教程,作者blue于2025年5月18日撰写。文章介绍了MyBatis作为一款优秀的持久层框架,如何简化JDBC开发。通过创建SpringBoot工程、数据库表`user`及实体类`User`,引入MyBatis依赖并配置数据库连接信息,使用注解方式编写SQL语句实现查询所有用户数据的功能。此外,还展示了如何通过Lombok优化实体类代码,减少冗余的getter/setter等方法,提高开发效率。最后通过单元测试验证功能的正确性。
556 19
|
Java 关系型数据库 数据库连接
Javaweb之Mybatis入门程序的详细解析
本文详细介绍了一个MyBatis入门程序的创建过程,从环境准备、Maven项目创建、MyBatis配置、实体类和Mapper接口的定义,到工具类和测试类的编写。通过这个示例,读者可以了解MyBatis的基本使用方法,并在实际项目中应用这些知识。
470 11
|
缓存 NoSQL Java
Mybatis学习:Mybatis缓存配置
MyBatis缓存配置包括一级缓存(事务级)、二级缓存(应用级)和三级缓存(如Redis,跨JVM)。一级缓存自动启用,二级缓存需在`mybatis-config.xml`中开启并配置映射文件或注解。集成Redis缓存时,需添加依赖、配置Redis参数并在映射文件中指定缓存类型。适用于查询为主的场景,减少增删改操作,适合单表操作且表间关联较少的业务。
562 6