当前位置: 首页 > news >正文

mybatis连接数据库

利用mybatis代理开发连接数据库

环境搭建

1. 在pom.xml导入依赖

   <!-- mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!-- mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><!-- lombok,利用注解生成构造函数等 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><!--日志信息--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency>

2. 在resourse文件夹中创建mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql:///数据库名?useSSL=false"/><property name="username" value="用户名"/><property name="password" value="密码"/></dataSource></environment></environments><mappers><package name="这里写你的映射文件的位置,我的是com.jiazhong.jiaocheng.mapper"/></mappers>
</configuration>

[!TIP]

resources里面的BrandMapper.xml为映射文件,路径要与上面src文件夹的路径要一致
src里的com.jiazhong.jiaocheng.mapper.BrandMapper,那么就要在resouse文件夹下创建com/jiazhong/jiaocheng/mapper/BrandMapper.xml

3. 编写映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="这里改为你的mapper接口的位置,我的是com.jiazhong.jiaocheng.mapper.BrandMapper"><!--解决数据库中使用下横线命名但是Java用驼峰命名法导致查不到数据-->
<resultMap id="resultMap" type="Brand"><result column="数据库字段的名字" property="实体类中的名字"/><result column="company_name" property="companyName"/>
</resultMap><select id="selectAll" resultMap="resultMap" ><!--使用自定义的id为resultMap的规则,即上面的-->select * from Blog where id = #{id} <!--#{id},占位符--></select>
</mapper>

[!TIP]

如果你搜索只是返回一个值,比如说String ,或者是int,那你直接用resultType就行了。(基本数据类型默认可不写)。

resultMap可以对返回的参数进行配置,mybatis默认会进行驼峰转换,当数据库字段和Java对象字段不满足驼峰(列名不匹配),可以通过这里来配置,进行字段匹配。

[!TIP]
resultMap标签里type属性后面为结果映射的目标类,也就是查询结果要映射到的 Java 对象类型。我这里原本应该是com.jiazhong.pojo.Brand,但是如果在mybatis-config.xml配置了别名(如下),则这里用类名(不区分大小写)

<!--配置类型别名-->
<typeAliases><package name="com.jiazhong.jiaocheng.pojo"/>
</typeAliases>

手搓项目

pojo软件包下创建Brand类,用于定义实体属性:

package com.jiazhong.jiaocheng.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@NoArgsConstructor
@AllArgsConstructor
@Data
public class Brand {private Integer id;private String brandName;private String companyName;private Integer ordered;private String description;private Integer status;
}

src的mapper包里写一些接口

package com.jiazhong.jiaocheng.mapper;import com.jiazhong.jiaocheng.pojo.Brand;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface BrandMapper {List<Brand> selectAll();Brand selectByIdInt(int id);/*动态sql语句*/Brand select(@Param("id") Integer id,@Param("brandName") String brandName, @Param("companyName") String companyName);
}

[!TIP]

用户在输入查询条件时可能不会每个条件都输入,可能只记得公司名,可能只记得品牌名,如果针对这种情况,编写不同的查询语句,工程量太大,mybatis支持动态sql语句

在BrandMapper.xml写一些sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jiazhong.jiaocheng.mapper.BrandMapper"><!--解决数据库中使用下横线命名但是Java用驼峰命名法导致查不到数据-->
<resultMap id="resultMap" type="Brand"><!--type后面为结果映射的目标类,也就是查询结果要映射到的 Java 对象类型。如果在mybatis-config.xml配置了别名,则这里用类名(不区分大小写)--><result column="brand_name" property="brandName"/><result column="company_name" property="companyName"/>
</resultMap><!--如果你搜索只是返回一个值,比如说String ,或者是int,那你直接用resultType就行了。(基本数据类型默认可不写)。
resultMap可以对返回的参数进行配置,mybatis默认会进行驼峰转换,当数据库字段和Java对象字段不满足驼峰(列名不匹配),可以通过这里来配置,进行字段匹配。--><select id="selectAll" resultMap="resultMap">select *from tb_brand;</select><select id="selectByIdInt" resultMap="resultMap">select * from tb_brand where id=#{id};</select><!--动态sql语句--><select id="select" resultMap="resultMap">select *from tb_brand<where><if test="id!=null">and id=#{id}</if><if test="brandName!=null">and brand_name like #{brandName}</if><if test="companyName!=null">and company_name like #{companyName}</if></where></select>
</mapper>

[!TIP]

动态sql语句中标签可以动态去除语句前的and,保证sql语句正确性

在测试类编写方法

package com.jiazhong.jiaocheng;import com.jiazhong.jiaocheng.mapper.BrandMapper;
import com.jiazhong.jiaocheng.pojo.Brand;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class Demo01 {/*public static void main(String[] args) throws Exception {///1. 加载mybatis的核心配置文件,获取 SqlSessionFactoryInputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);/// 2. 获取SqlSession对象,用它来执行sqlSqlSession sqlSession = sqlSessionFactory.openSession();//     不是代理模式   List<Brand>List=sqlSession.selectList("selectAll");/// 3. 执行sql/// 3.1 获取UserMapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);List<Brand> list = brandMapper.selectAll();System.out.println(list);sqlSession.close();}*/
/*    public static void main(String[] args) throws IOException {InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = build.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);System.out.println(mapper.selectByIdInt(21));}*/public static void main(String[] args) throws IOException {InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = build.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);Brand select = mapper.select(null,null,"%苹果%");System.out.println(select);}
}

eAsStream);
SqlSession sqlSession = build.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand select = mapper.select(null,null,“%苹果%”);
System.out.println(select);
}
}

http://www.xdnf.cn/news/1322569.html

相关文章:

  • Kafka 零拷贝(Zero-Copy)技术详解
  • 数据赋能(401)——大数据——持续学习与优化原则
  • RAG 入门指南:从概念到最小系统搭建
  • 基于Android的随身小管家APP的设计与实现/基于SSM框架的财务管理系统/android Studio/java/原生开发
  • 从0-1使用Fastmcp开发一个MCP服务,并部署到阿里云百炼 -持续更新中
  • Flutter 自定义 Switch 切换组件完全指南
  • 深度学习——R-CNN及其变体
  • React diff——差异协调算法简介
  • 【Python面试题】写一个用元类(metaclass)实现API接口自动注册的Demo。以及装饰器在项目中典型应用场景。
  • AI行业应用深度报告:金融、医疗、教育、制造业落地案例
  • 前端环境安装
  • AI 在金融领域的落地案例
  • go语言条件语if …else语句
  • ——链表——
  • 音频算法工程师技能1
  • 调试技巧(vs2022 C语言)
  • 【速通】深度学习模型调试系统化方法论:从问题定位到性能优化
  • 剧本杀小程序系统开发:保障游戏公平,营造健康娱乐环境
  • 蔬菜批发小程序:生产商的数字化转型利器——仙盟创梦IDE
  • 云计算-云上实例部署 RocketChat:Mongodb、主从数据库、Node 环境配置指南
  • 【人工智能】2025年AI代理失控危机:构建安全壁垒,守护智能未来
  • Python 面向对象三大特性详解(与 C++ 对比)
  • 【OpenAI】今日话题: GPT-4o-Audio-Preview 多模态语音交互模型介绍+API的使用教程!
  • 【verge3d】如何在项目里调用接口
  • ⭐CVPR2025 RigGS:从 2D 视频到可编辑 3D 关节物体的建模新范式
  • 【2025CVPR-目标检测方向】RaCFormer:通过基于查询的雷达-相机融合实现高质量的 3D 目标检测
  • BeeWorks 私有化会议系统:筑牢企业会议安全防线,赋能高效协同
  • 高并发网络编程实战:深入理解epoll客户端的事件驱动模型
  • OpenCV---特征检测算法(ORB,Oriented FAST and Rotated BRIEF)
  • css word-pass