spring boot MyBatis整合_spring boot与MyBatis的使用

教程分享 > Java教程 > Spring (22370) 2024-08-07 11:05:25

本文主要讲解在Java编程中,spring boot MyBatis xml mapper方式的入门和通过一个简单的例子带新手入门mybaties基本使用。
项目结构图:

项目结构图
项目结构图

代码清单:

spring boot配置文件application.properties:
#==================DataSource Config Start================== 
#name
#spring.datasource.name=test
#url
#spring.datasource.url=jdbc:sqlserver://192.168.xxx.xxx;instanceName=sql_03;DatabaseName=edu;integratedSecurity=false
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
#DriverClass
#spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#DB username
spring.datasource.username=root
#DB password
spring.datasource.password=root
#==================DataSource Config End==================

#==================mybaties Config Start==================
#ORM Bean Package
MyBatis.type-aliases-package=com.leftso.pojo
MyBatis.mapper-locations=classpath:/mapper/*.xml
#==================mybaties Config End  ==================


spring boot log简单配置,用于打印sql日志logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration>
	<include resource="org/springframework/boot/logging/logback/base.xml" />
	<!-- 打印sql -->
	<logger name="com.leftso.mapper" level="DEBUG" />
</configuration>

 


mybaties Java config 配置MyBatiesConfig.java:

 

package com.leftso.config;

import org.MyBatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * mybaties配置扫描mapper路径
 * 
 * @author leftso
 *
 */
@Configuration
@MapperScan(basePackages = { "com.leftso.mapper" }) /** 注意,这个注解是扫描mapper接口不是xml文件,使用xml模式必须在配置文件中添加xml的配置 **/
public class MyBatiesConfig {

}


简单测试的用户pojo对象User.java:

package com.leftso.pojo;

/**
 * 用户
 * 
 * @author leftso
 *
 */
public class User {
	private Long id;
	private String userName;
	private int age;
	private String sex;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

}


User对象的mapper接口:UserMapper.java:

package com.leftso.mapper;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.leftso.pojo.User;

@Component("userMapper")
public interface UserMapper {
	// 新增
	int add(User user);

	// 修改
	int remove(Long id);

	// 删除
	int update(User user);

	// 查一个
	User findOne(Long id);

	// 查多个
	List<User> findList(Map<String, Object> params);

}


mapper对应的xml文件UserMapper.xml:

<?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.leftso.mapper.UserMapper">
	<!-- 创建一个数据库user表与java中user对象关联的返回映射map -->
	<resultMap type="com.leftso.pojo.User" id="UserMap">
		<id column="id" property="id" jdbcType="NUMERIC" />
		<result column="user_name" property="userName" jdbcType="VARCHAR" />
		<result column="age" property="age" jdbcType="NUMERIC" />
		<result column="sex" property="sex" jdbcType="VARCHAR" />
	</resultMap>

	<!-- 新增 -->
	<insert id="add" parameterType="com.leftso.pojo.User"
		useGeneratedKeys="true" keyProperty="id">
		insert into t_user
		<trim prefix="(" suffix=")" suffixOverrides=","><!-- 说明:使用trim的方式组合sql,属性suffixOverrides表示去除末端多余的该属性值(这里是,) -->
			user_name,
			age,
			sex
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			#{name,jdbcType=VARCHAR},
			#{age,jdbcType=NUMERIC},<!-- 说明:数字类型都是NUMERIC,没有INT,LONG类型;其他对应类型请参照mybaties官方文档 -->
			#{sex,jdbcType=VARCHAR}
		</trim>
	</insert>

	<!-- 删除 -->
	<delete id="remove" parameterType="java.lang.Long">
		delete from t_user where
		id=#{id}
	</delete>

	<!-- 修改属性 -->
	<update id="update" parameterType="com.leftso.pojo.User">
		update t_user
		<set>
			<trim suffixOverrides=",">
				<if test="null!=name and ''!=name">
					user_name=#{name,jdbcType=VARCHAR},
				</if>
				<if test="null!=age">
					age=#{age,jdbcType=NUMERIC},
				</if>
				<if test="null!=sex and ''!= sex">
					sex=#{sex,jdbcType=VARCHAR},
				</if>
			</trim>
		</set>
		where id=#{id,jdbcType=NUMERIC}
	</update>

	<!-- 查询一个 -->
	<select id="findOne" parameterType="java.lang.Long" resultMap="UserMap">
		select * from t_user where id=#{id}
	</select>
	<!-- 查询多个 -->
	<select id="findList" parameterType="java.util.Map" resultMap="UserMap">
		select * from t_user where 1=1
		<if test="null!=name and '' != name">
			and user_name like '%${name}%' 
		</if>
		<if test=" sex != null and '' != sex">
			and sex = #{sex}
		</if>
		<if test="age > 0">
			and age <![CDATA[ >=]]>#{age} <!-- 说明:在xml里面大于小于大于等于需要逆转 -->
		</if>
	</select>

</mapper>


单元测试类:

package com.leftso;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.leftso.mapper.UserMapper;
import com.leftso.pojo.User;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
	Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	UserMapper userMapper;

	// @Test
	public void add() {
		try {
			User user = new User();
			user.setUserName("测试用户名");
			user.setAge(25);
			user.setSex("男");
			log.info("新增前ID:" + user.getId());
			userMapper.add(user);
			log.info("新增后ID:" + user.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// @Test
	public void remove() {
		try {
			userMapper.remove(2l);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// @Test
	public void update() {
		try {
			User user = new User();
			user.setId(3l);
			user.setUserName("我是修改");
			user.setAge(2);
			userMapper.update(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// @Test
	public void findOne() {
		try {
			User user = userMapper.findOne(3l);
			log.info("\nName:" + user.getUserName() + "\nAge:" + user.getAge() + "\nSex:" + user.getSex());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void findList() {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", "我");
			params.put("age", 3);
			List<User> list = userMapper.findList(params);
			for (User user : list) {
				log.info("\nName:" + user.getUserName() + "\nAge:" + user.getAge() + "\nSex:" + user.getSex());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


源码下载:
GitHub:https://github.com/leftso/demo-spring-boot-mybaties3

https://www.leftso.com/article/133.html

相关文章
引言    通过之前spring boot mybatis 整合的讲解: spring boot mybaties整合  (spring boot mybaties 整合 基于Java注解方式写...
spring boot mybatis 整合使用讲解介绍,spring boot与MyBatis的使用讲解介绍。spring boot mybatis xml mapper方式的入门和通过一个简...
spring boot框架整合MyBatis数据库暂时选用MySQL
本文主要讲解spring boot框架整合MyBatis后,如何打印出MyBatis的sql语句以及参数列表
本文旨在介绍如何使用Spring Boot和Mybatis来构建应用程序。Spring Boot是一个基于Spring框架的轻量级框架,可以帮助开发者快速构建应用程序,减少编码和维护时间。Myb...
Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用
本文章主要简单讲解目前流行的springMVC4+Spring4+MyBatis3(即SSM)框架整合
Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ
mybatis plus 逻辑删除使用说明全局逻辑值配置,application.properties# 逻辑已删除值(默认为 1) mybatis-plus.global-config.db...
Spring Boot MQTT协议通过spring boot整合apache artemis实现Java语言MQTT协议通信,搭建MQTT服务器可以参考上一篇 MQTT Java入门-搭建MQ...
spring boot 入门之整合spring session实现session共享。一直以来Java编程中web项目中的session共享问题都是一个很难解决的问题。接下来将讲解通过sprin...
Spring Boot 2.0 Redis整合,通过spring boot 2.0整合Redis作为spring缓存框架的实现。
Java编程中spring boot项目如何获取spring容器applicationContext
spring boot 1.5整合redis实现spring的缓存框架,spring boot,redis