spring boot整合MyBatis

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


本博文主要讲解spring boot项目整合MyBatis
1.最终项目结构图
结构
2.文件清单
清单:pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>demo-springboot-MyBatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo-springboot-MyBatis</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.1.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- MyBatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.2.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

清单:User.java

package com.example.pojo;

public class User {
	private Long id;
	private String userName;
	private String userSex;
	private int userAge;

	public User() {

	}

	public User(String userName, String userSex, int userAge) {
		super();
		this.userName = userName;
		this.userSex = userSex;
		this.userAge = userAge;
	}

	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 String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}

	public int getUserAge() {
		return userAge;
	}

	public void setUserAge(int userAge) {
		this.userAge = userAge;
	}

}

清单:UserMapper.java

package com.example.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.pojo.User;

public interface UserMapper {
	/**
	 * 查询所有用户信息
	 * 
	 * @return
	 */
	@Select("select * from user")
	@Results(value = { @Result(property = "userSex", column = "user_sex", javaType = String.class),
			@Result(property = "userName", column = "user_name"), @Result(property = "userAge", column = "user_age") })
	List<User> findList();

	/**
	 * 通过ID查询
	 * 
	 * @param id
	 * @return
	 */
	@Select("select * from user u where u.id=#{id}")
	User findOne(@Param("id") Long id);

	/**
	 * 新增一个
	 * 
	 * @param user
	 */
	@Insert("insert into user (user_name,user_sex,user_age) values(#{userName},#{userSex},#{userAge})")
	void insert(User user);

	/**
	 * 修改
	 * 
	 * @param user
	 */
	@Update("update user u set u.user_name=#{userName},u.user_sex=#{userSex},u.user_age=#{userAge} where u.id=#{id}")
	void update(User user);

	/**
	 * 删除
	 * 
	 * @param id
	 */
	@Delete("delete from user where id=#{id}")
	void delete(@Param("id") Long id);
}

清单:UserController.java

package com.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class UserController {

	@Autowired
	UserMapper userMapper;

	/**
	 * index
	 * 
	 * @return
	 */
	@RequestMapping("/")
	public String index() {
		return "User Info By MyBatis";
	}

	@RequestMapping("/user/list.json")
	public Object allUsers() {
		List<User> users = userMapper.findList();
		return users;
	}

}

清单:Application.java

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@MapperScan(basePackages = { "com.example.mapper" }) // 自动扫描mapper
@EnableTransactionManagement//启用事物管理,在service上使用@Transactional(注意是spring的 注解)
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

清单: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==================

#==================MyBatis Config Start==================
#ORM Bean Package
mybatis.type-aliases-package=com.example.pojo
mybatis.mapper-locations=classpath:/mapper/*.xml
#打印MyBatisSql语句
logging.level.com.example.mapper=DEBUG
#==================MyBatis Config End  ==================

清单:UserMapperTest.java

package com.example.test;

import java.util.List;

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

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
	@Autowired
	private UserMapper userMapper;

	// @Test
	public void testInsert() {
		try {
			userMapper.insert(new User("xqlee1", "男", 26));
			userMapper.insert(new User("xqlee2", "男", 23));
			userMapper.insert(new User("xqlee3", "男", 27));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// @Test
	public void testUpdate() {
		try {
			User user = new User("测试0000", "男", 23);
			user.setId(1l);
			userMapper.update(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//@Test
	public void testQuery() {
		try {
			List<User> users=userMapper.findList();
			for(User u:users){
				System.out.println("ID:"+u.getId()+" Name:"+u.getUserName()+" Sex:"+u.getUserSex()+" Age:"+u.getUserAge());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testDelete(){
		try {
			userMapper.delete(1l);
			testQuery();
		} catch (Exception e) {

			e.printStackTrace();
		}
		
	}
}
https://www.leftso.com/article/80.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来构建应用程序。Spring Boot是一个基于Spring框架的轻量级框架,可以帮助开发者快速构建应用程序,减少编码和维护时间。Myb...
本文主要讲解spring boot框架整合MyBatis后,如何打印出MyBatis的sql语句以及参数列表
mybatis plus 逻辑删除使用说明全局逻辑值配置,application.properties# 逻辑已删除值(默认为 1) mybatis-plus.global-config.db...
本文章主要简单讲解目前流行的springMVC4+Spring4+MyBatis3(即SSM)框架整合
Spring Boot 2.0 支持的Apache Camel 版本发布了_Apache Camel 2.22发布支持Spring Boot 2.0
Spring Boot 2.0,Spring框架的Spring Boot 中的Spring Boot Actuator变化讲解。并且了解如何在Spring Boot 2.0中使用Actuator...
Spring Boot 2.0 绑定properties属性资源文件 Spring Boot 2.0 读取properties配置文件值 Spring Boot 2.0获取properties配...
spring boot入门,spring boot是一个崭新的spring框架分支项目,本文讲解其属性配置相关
spring boot 1.5整合redis实现spring的缓存框架,spring boot,redis
spring boot是一个崭新的spring框架分支项目,本文讲解基本的数据库配置
Spring Boot validation整合hibernate validator实现数据验证,Spring Boot validation使用说明,Spring Boot validat...