一、工程代码总体示例:

1、首先创建一个与表中数据相对应的实体类,Studen.java


/** * Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements.  See the NOTICE file distributed with* this work for additional information regarding copyright ownership.* The ASF licenses this file to You under the Apache License, Version 2.0* (the "License"); you may not use this file except in compliance with* the License.  You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/
package com.tompai.entity;import java.util.Date;import com.tompai.utils.DateUtil;/*** @desc: springdemo* @name: Student.java* @author: tompai* @email:liinux@qq.com* @createTime: 2020年3月21日 下午8:14:44* @history:* @version: v1.0*/public class Student {private int id;private String name;private String sex;private int age;private Date inputIime;public Student() {super();}public Student(String name, String sex, int age) {super();this.name = name;this.sex = sex;this.age = age;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getInputIime() {return inputIime;}public void setInputIime(Date inputIime) {this.inputIime = inputIime;}@Overridepublic String toString() {return "{\"id\":\"" + id + "\", \"name\":\"" + name + "\", \"sex\":\"" + sex + "\", \"age\":\"" + age+ "\", \"inputIime\":\"" + DateUtil.parseDateToStr(inputIime) + "\"}";}}

2、写出这个类的映射接口StudentMapper.java,里面有我们要实现的查询的抽象方法。


/** * Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements.  See the NOTICE file distributed with* this work for additional information regarding copyright ownership.* The ASF licenses this file to You under the Apache License, Version 2.0* (the "License"); you may not use this file except in compliance with* the License.  You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/
package com.tompai.mapper;import java.util.List;import com.tompai.entity.Student;/*** @desc: springdemo* @name: StudentMapper.java* @author: tompai* @email:liinux@qq.com* @createTime: 2020年3月21日 下午8:22:16* @history:* @version: v1.0*/public interface StudentMapper {public void save(Student student);public Student findById(int id);public List<Student> findAll();public void modify(Student student);public void deleteById(int id);
}

3、写出这个类的映射Mapper文件,里面有数据库DDL语句。

<?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.tompai.mapper.StudentMapper"><resultMap id="studentMap" type="Student"><id column="id" property="id" jdbcType="INTEGER"/><result column="name" property="name" jdbcType="VARCHAR"/><result column="sex" property="sex" jdbcType="VARCHAR"/><result column="age" property="age" jdbcType="INTEGER"/><result column="input_time" property="inputIime" jdbcType="TIMESTAMP"/></resultMap><insert id="save" parameterType="Student">insert into t_student(name,sex,age,input_time) values(#{name},#{sex},#{age},sysdate())</insert>  <select id="findAll" resultType="Student">select id,name,sex,age,input_time from t_student</select><!-- <select id="findAll" resultMap="studentMap">select id,name,sex,age,input_time from t_student</select> --><select id="findById" parameterType="int" resultType="Student">select * from t_student where id =#{id}</select><update id="modify" parameterType="Student">update t_student set name=#{name},age=#{age} where id=#{id}</update><delete id="deleteById" parameterType="int">delete from t_student where id=#{id}</delete></mapper>

4、准备四个配置文件。

1:准备mysql-local.properties的参数配置文件,里面写上数据库连接要用到的参数。

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root

2:准备spring-config.xml,这个是spring最重要的配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!--表明引用的参数配置文件是mysql-local.properties --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>mysql-local.properties</value></list></property></bean><!--数据库连接池 --><bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">  <property name="driverClassName" value="${jdbc.driver}" /><property name="jdbcUrl" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><!-- 初始连接池大小 --><property name="readOnly" value="false" /><!-- 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒 --><property name="connectionTimeout" value="30000" /><!-- 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟 --><property name="idleTimeout" value="600000" /><!-- 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';) --><property name="maxLifetime" value="1800000" /><!-- 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count) --><property name="maximumPoolSize" value="15" /></bean><!-- 配置SqlSessionFactory对象 --><bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据库连接池 --><property name="dataSource" ref="dataSource" /><property name="configLocation" value="mybatis-config.xml" /></bean><!--配置studentMapper对象 --><bean id="studentMapper"class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="com.tompai.mapper.StudentMapper" /><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean></beans>

3:准备mybatis-config.xml,这个是mybatis的配置文件。

<?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><typeAliases><typeAlias alias="Student" type="com.tompai.entity.Student" /></typeAliases><mappers><mapper resource="mybatis/mapper/StudentMapper.xml" /></mappers>
</configuration>

4:准备logback.xml,这个是日志记录配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为true时,此属性生效。默认的时间间隔为1分钟。 debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="false" scanPeriod="60 seconds" debug="false"><!-- 定义日志的根目录 value表示的是打印到哪里的--><property name="LOG_HOME" value="logs" /><!-- 定义日志文件名称  value表示的是log的名称--><property name="appName" value="u-plan"></property><!-- ch.qos.logback.core.ConsoleAppender 表示控制台输出 --><appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"><Encoding>UTF-8</Encoding><!-- 日志输出格式:%d表示日期时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %logger{50} 表示logger名字最长50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符 --><layout class="ch.qos.logback.classic.PatternLayout"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern></layout></appender><!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 --><appender name="appLogAppender"class="ch.qos.logback.core.rolling.RollingFileAppender"><Encoding>UTF-8</Encoding><!-- 指定日志文件的名称 --><file>${LOG_HOME}/${appName}.log</file><!-- 当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名 TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动。 --><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!-- 滚动时产生的文件的存放位置及文件名称 %d{yyyy-MM-dd}:按天进行日志滚动 %i:当文件大小超过maxFileSize时,按照i进行文件滚动 --><fileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern><!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件。假设设置每天滚动, 且maxHistory是365,则只保存最近365天的文件,删除之前的旧文件。注意,删除旧文件是, 那些为了归档而创建的目录也会被删除。 --><MaxHistory>30</MaxHistory><!-- 当日志文件超过maxFileSize指定的大小是,根据上面提到的%i进行日志文件滚动 注意此处配置SizeBasedTriggeringPolicy是无法实现按文件大小进行滚动的,必须配置timeBasedFileNamingAndTriggeringPolicy --><timeBasedFileNamingAndTriggeringPolicyclass="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>512MB</maxFileSize></timeBasedFileNamingAndTriggeringPolicy></rollingPolicy><!-- 日志输出格式:%d表示日期时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %logger{50} 表示logger名字最长50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符 --><layout class="ch.qos.logback.classic.PatternLayout"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [%logger{50} : %line ] - %msg%n</pattern></layout></appender><!-- logger主要用于存放日志对象,也可以定义日志类型、级别 name:表示匹配的logger类型前缀,也就是包的前半部分 level:要记录的日志级别,包括 TRACE < DEBUG < INFO < WARN < ERROR additivity:作用在于children-logger是否使用 rootLogger配置的appender进行输出,false:表示只用当前logger的appender-ref,true:表示当前logger的appender-ref和rootLogger的appender-ref都有效 --><!-- hibernate logger --><logger name="org.hibernate" level="error" /><!-- Spring framework logger --><logger name="org.springframework" level="error" additivity="false"></logger><logger name="com.fairyland" level="info" additivity="true"><appender-ref ref="appLogAppender" /></logger><!-- root与logger是父子关系,没有特别定义则默认为root,任何一个类只会和一个logger对应, 要么是定义的logger,要么是root,判断的关键在于找到这个logger,然后判断这个logger的appender和level。 --><root level="info"><appender-ref ref="stdout" /><appender-ref ref="appLogAppender" /></root>
</configuration>

5、以上4个xml文件都配置完成之后,我们调用数据插入和所有数据查询方法如下:


/** * Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements.  See the NOTICE file distributed with* this work for additional information regarding copyright ownership.* The ASF licenses this file to You under the Apache License, Version 2.0* (the "License"); you may not use this file except in compliance with* the License.  You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/
package com.tompai;import java.util.ArrayList;
import java.util.List;import org.apache.commons.lang3.RandomUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.tompai.entity.Student;
import com.tompai.mapper.StudentMapper;
import com.tompai.utils.RandomHan;import lombok.extern.slf4j.Slf4j;/*** @desc: springdemo* @name: SpringDemo.java* @author: tompai* @email:liinux@qq.com* @createTime: 2020年3月21日 下午10:23:41* @history:* @version: v1.0*/
@Slf4j
public class SpringDemo {/*** @author: tompai* @createTime: 2020年3月21日 下午10:23:41* @history:* @param args void*/public static void main(String[] args) {// TODO Auto-generated method stubApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");StudentMapper studentMapper = (StudentMapper) context.getBean("studentMapper");for (int i = 0; i < 100; i++) {String name = RandomHan.randomName(true, 3);log.info("name :" + name + " ->" + i);String sex = RandomUtils.nextBoolean() ? "男" : "女";int age = RandomUtils.nextInt() % 100;Student student = new Student(name, sex, age);studentMapper.save(student);}List<Student> students = new ArrayList<Student>();students = studentMapper.findAll();for(Student student:students) {String string=student.toString();log.info("select:{}",student);}}}

结果如下:

示例代码

五步完成Spring整合Mybatis的完整示例相关推荐

  1. spring整合mybatis(实现数据的增删改查)

    一.专业术语解释 1.spring:是分层的Java SE/EE应用full - stack轻量级开源框架,以IoC(控制反转)和AOP(面向切面编程)为内核,提供展现层spring MVC 和 sp ...

  2. spring整合mybatis(入门级简单教程1)--在spring中配置c3p0,并成功测试

    引子:spring整合mybatis.因为,我们看完(我就是这样的)spring和mybatis之后,本想自己写一个小小的项目,以便加深理解,但是我发现在spring中整合mybatis并不是一件容易 ...

  3. SSM之二(Spring整合Mybatis)

    项目与外界交互大概过程如下图: 一般过程是: 前端发送请求,查询数据.增加数据.修改数据.删除数据 中间件经过处理后,对数据发送请求 数据库返回数据,中间件再对数据处理 中间件响应前端请求 上一节关注 ...

  4. 【Java从0到架构师】Spring - 整合 MyBatis

    整合 MyBatis 整合 MyBatis - 依赖 整合 MyBatis - 数据源 整合 MyBatis - SqlSessionFactoryBean 整合 MyBatis - MapperSc ...

  5. Spring整合Mybatis之DAO层、Service层开发

    3. Spring整合Mybatis编程DAO层开发 1. 项目引入相关依赖spring mybatis mysql mybatis-spring druid2. 编写spring.xml整合:spr ...

  6. Spring整合MyBatis:实现登录功能

    一.项目搭建 1.创建 web 项目:spring_mybatis 2.搭建项目的目录结构 3.导入 jar 包 注意: 导入 web/WEB-INF/lib 中,一下 jar 包都需要导入 4.创建 ...

  7. Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(二:mybatis整合spring)

    http://blog.csdn.net/qq598535550/article/details/51703190 二.Spring整合mybatis其实是在mybatis的基础上实现Spring框架 ...

  8. Spring整合Mybatis之注解方式,(注解整合Junit)

    Spring整合Mybatis之注解方式 我有一篇博客详细写了我自己使用xml的方法Spring整合MyBatis,现在我就把核心配置文件中的每个bean的配置使用注解的方式实现 注解整合MyBati ...

  9. spring整合mybatis基于注解

    数据库 /* Navicat MySQL Data Transfer Source Server         : mysql Source Server Version : 50549 Sourc ...

  10. spring整合mybatis基于xml配置

    数据库 /* Navicat MySQL Data Transfer Source Server         : mysql Source Server Version : 50549 Sourc ...

最新文章

  1. Android stadio
  2. 软件测试工资高还是运维高,IT行业的6大热门岗位,薪酬都有多高?
  3. 看看老司机是如何提升B端产品架构能力的
  4. SoPlus回顾 | 行业大咖论道AI,探讨未来行业发展趋势
  5. 【java】窗口和监听器的使用
  6. 部署git服务器(Windows Server 2008)
  7. 2.携程架构实践 --- 移动大前端
  8. 线性代数知识荟萃(3)——行列式
  9. vue中加载OCX控件(IE浏览器执行)
  10. VMware使用OVFTool导入虚拟机
  11. java mysql点赞功能_怎么实现一个点赞功能?
  12. html求视频的原尺寸,PR怎样导出原尺寸视频?
  13. 强化学习入门1—多臂老虎机Multi-armed Bandits
  14. app ui ios airtest +python 环境搭建
  15. onedrive php映射,Microsoft OneDrive空全局账号自建API(Rclone、OneManager-php)
  16. 新iPhone9月登场, 5大特色浮出水!
  17. ros::nodehandle常规操作
  18. 移动硬盘,U盘出现USBC病毒乱码恢复的可能性分析
  19. 在NW.js里面使用node-printer
  20. 第一序列任小粟的能力_第一序列全本免费阅读-第一序列小说精校版

热门文章

  1. python - zipfile模块
  2. [BZOJ2118] 墨墨的等式(最短路)
  3. 1.2 控制器 view 的创建和加载
  4. android开发,assets下面的资源文件不会变化/改动
  5. 优雅的实现Activiti动态调整流程(自由跳转、前进、后退、分裂、前加签、后加签等),含范例代码!...
  6. flask+uswgi+nginx+python3.6的venv发布网站ubuntu14.04
  7. Tomcat—启动时控制台显示文字的颜色
  8. Cesium中HeadingPitchRoll
  9. Java面试题超详细讲解系列之七【MySQL篇】
  10. Sql分页存储过程(支持多表分页存储)