ssm框架之mybatis框架搭建

news/2025/3/20 18:02:58/

第一步 引入依赖

<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><!-- mybatis mysql相关依赖 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency>

第二步 编写配置文件

最终目录如下:
在这里插入图片描述
我们要编写mybatis-config.xml,内容如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="logImpl" value="LOG4J" /></settings><typeAliases><package name="com.dts.entity" /></typeAliases><!-- 配置mybatis运行环境 --><environments default="development"><environment id="development"><!-- 使用JDBC的事务管理 --><transactionManager type="JDBC" /><dataSource type="POOLED"><!-- MySQL数据库驱动 --><property name="driver" value="com.mysql.jdbc.Driver" /><!-- 连接数据库的URL --><property name="url"value="jdbc:mysql://localhost:3306/cdes?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true&amp;serverTimezone=Asia/Shanghai" /><property name="username" value="root" /><property name="password" value="123456" /></dataSource></environment></environments><!-- 将mapper文件加入到配置文件中 --><mappers><mapper resource="mapper/WebsiteMapper.xml" /></mappers></configuration>

然后编写log4j.properties,内容如下

# Global logging configuration
log4j.rootLogger=ERROR,stdout
# MyBatis logging configuration...
log4j.logger.com.dts=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

第三步 编写实体类 mapper 和sql脚本

package com.dts.entity;import java.util.Date;public class Website {private int id;private String name;private String url;private int age;private String country;private Date createtime;public Date getCreatetime() {return createtime;}public void setCreatetime(Date createtime) {this.createtime = createtime;}public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}@Overridepublic String toString() {return "id" + id + "name" + name + "url" + url + "age" + age + "country" + country + "createtime" + createtime;}
}
package com.dts.mapper;import com.dts.entity.Website;
import org.apache.ibatis.annotations.Select;import java.util.List;public interface WebsiteMapper {void addWebsite(Website website);List<Website> selectAllWebsite();@Select("select * from website where id = #{id}")Website findById(Integer id);List<Website> selectByIds(List<Integer> ids);List<Website> selectByCondition(Website website);void updateWebsite(Website website);void deleteWebsite(Integer id);void deleteWebsiteByIds(List<Integer> ids);}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.dts.mapper.WebsiteMapper"><!-- 添加一个网站 --><insert id="addWebsite" parameterType="com.dts.entity.Website">insert into website(name,url,age,country)values(#{name},#{url},#{age},#{country})</insert><!-- 查询所有网站信息 --><select id="selectAllWebsite"resultType="com.dts.entity.Website">select * from website</select><select id="selectByIds" resultType="com.dts.entity.Website">select * from website where id in<foreach collection="list" item="id" open="(" close=")" separator=",">#{id}</foreach></select><select id="selectByCondition" resultType="com.dts.entity.Website">select * from website<where><if test="name != null and name != ''">and name like concat('%',#{name},'%')</if><if test="country != null and country != ''">and country like concat('%',#{country},'%')</if><if test="age != null and age != ''">and age = #{age}</if></where></select><update id="updateWebsite">update website<set><if test="name != null and name != ''">name = #{name},</if><if test="url != null and url != ''">url = #{url},</if><if test="age != null and age != ''">age = #{age},</if><if test="country != null and country != ''">country = #{country},</if></set>where id = #{id}</update><delete id="deleteWebsite">delete from website where id = #{id}</delete><delete id="deleteWebsiteByIds">delete from website where id in<foreach collection="list" item="id" open="(" close=")" separator=",">#{id}</foreach></delete>
</mapper>

最后 编写test方法

package com.dts;import com.dts.entity.Website;
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.InputStream;
import java.util.List;public class MybatisTest {public static void main(String[] args)throws Exception {test1();}public static void test1() throws Exception {// 读取配置文件mybatis-config.xmlInputStream config = Resources.getResourceAsStream("mybatis-config.xml");// 根据配置文件构建SqlSessionFactorySqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);// 通过SqlSessionFactory创建SqlSessionSqlSession ss = ssf.openSession();ss.getConnection().setAutoCommit(false);// SqlSession执行文件中定义的SQL,并返回映射结果// 添加网站Website website = new Website();website.setName("编程帮");website.setUrl("https://www.cainiaoplus.com/");website.setAge(21);website.setCountry("CN");ss.insert("com.dts.mapper.WebsiteMapper.addWebsite", website);//这种方式
//        WebsiteMapper mapper = ss.getMapper(WebsiteMapper.class);
//        mapper.addWebsite(website);// 查询所有网站List<Website> listWeb = ss.selectList("com.dts.mapper.WebsiteMapper.selectAllWebsite");for (Website site : listWeb) {System.out.println(site);}// 提交事务ss.commit();// 关闭 SqlSessionss.close();}}

经过以上步骤,mybatis框架就算搭建完成了。最终项目结构如下
在这里插入图片描述

文章来源:https://blog.csdn.net/qq_36268452/article/details/146354021
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/1580321.html

相关文章

[UTCTF 2025]

周末时间真的紧&#xff0c;注册了3个比赛&#xff0c;结果只抽时间打了两了。 Crypto DCΔ 提示是每次只能生成一个素数&#xff0c;那就是np**2略 RSA e3,c<n略 Autokey Cipher lpqwma{rws_ywpqaauad_rrqfcfkq_wuey_ifwo_xlkvxawjh_pkbgrzf} AES autokey模式&#x…

STM32 - 在机器人领域,LL库相比HAL优势明显

在机器人控制器、电机控制器等领域的开发&#xff0c;需要高实时性、精细化控制或者对代码执行效率、占用空间有较高要求。所以&#xff0c;大家常用的HAL库明显不符合要求。再加上&#xff0c;我们学习一门技术&#xff0c;一定要学会掌握底层的原理。MCU开发的底层就是寄存器…

leecode417.太平洋大西洋水流问题

由海洋逆推回到经过的坐标&#xff0c;用dfs方式将海洋逆推回去的坐标都设置为true&#xff0c;那么只要这个坐标能被太平洋和大西洋逆推为true&#xff0c;那么就添加到结果集中 class Solution { private:void pacificAtlantic(vector<vector<int>>& height…

Python F-String 深度解析:原理、用法与最佳实践

# Python F-String 深度解析&#xff1a;原理、用法与最佳实践 ## 一、引言 Python 的 F-String&#xff08;格式化字符串字面值&#xff09;自 3.6 版本引入以来&#xff0c;凭借其简洁性和高效性&#xff0c;迅速成为字符串格式化的首选方案。本文将从原理、核心用法和编码规…

从零开始使用 **Taki + Node.js** 实现动态网页转静态网站的完整代码方案

以下是从零开始使用 Taki Node.js 实现动态网页转静态网站的完整代码方案&#xff0c;包含预渲染、自动化构建、静态托管及优化功能&#xff1a; 一、环境准备 1. 初始化项目 mkdir static-site && cd static-site npm init -y2. 安装依赖 npm install taki expre…

PG数据库创建分区表

-- 创建自增序列号CREATE SEQUENCE dw_dwm_cdt_device_day_detail_id_seq1 INCREMENT BY 1;-- 创建主表&#xff0c;PARTITION BY RANGE为分区字段CREATE TABLE "public"."dw_dwm_cdt_device_day_detail" ("id" int8 NOT NULL DEFAULT nextval(d…

HTML 中如何设置页面的语言,这对 SEO 和无障碍访问有什么影响?

大白话HTML 中如何设置页面的语言&#xff0c;这对 SEO 和无障碍访问有什么影响&#xff1f; 1. HTML 中设置页面语言的方法 在 HTML 里&#xff0c;你可以借助 <html> 标签的 lang 属性来设定页面的语言。lang 属性的值是一个符合 ISO 639 - 1 标准的双字母语言代码&a…

CVPR2025自动驾驶端到端前沿论文汇总

自动驾驶 文章目录 自动驾驶前言自动驾驶的轨迹预测论文端到端自动驾驶论文 前言 汇总CVPR2025自动驾驶前沿论文 自动驾驶的轨迹预测论文 Leveraging SD Map to Augment HD Map-based Trajectory PredictionModeSeq: Taming Sparse Multimodal Motion Prediction with Seque…