五步完成Spring整合Mybatis的完整示例

一、工程代码总体示例:

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

	@Override
	public 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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://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 -->
			<timeBasedFileNamingAndTriggeringPolicy
				class="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 stub

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

}

结果如下:

示例代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值