Spring Boot And MyBatis 整合实例 (二)

本文档详细介绍了如何在Spring Boot项目中整合MyBatis框架进行数据库操作,包括项目的搭建过程、实体类定义、Mapper接口创建及Controller层的具体实现。

 

一,创建项目

        项目名称为 “springboot_mybatis_demo”,创建过程中勾选 “Web”,“MyBatis”,“MySQL”,第一次创建Maven需要下载依赖包(耐心等待)。

                101243_A3er_2962740.png

勾选 web,MyBatis,MySql三个选项。

    101535_AmAt_2962740.png

 二,实现

2.1 创建User类

package com.huwei.bean;


//创建一个User的bean
public class User {

	private Long id;
	
	private String userName;
	
	private Integer age;
	
	public User(){}

	public User(Long id, String userName, Integer age) {
		super();
		this.id = id;
		this.userName = userName;
		this.age = age;
	}

	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 Integer getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]";
	}
	
}

 

2.2创建UserMapper接口

    创建接口UserMapper,并添加@Mapper注解

package com.huwei.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.huwei.bean.User;

// 创建一个User的mapper接口
@Mapper
public interface UserMaper {

	// 查找User表中所有的数据
	@Select("select * from user")
	User queryAll();
}

   

2.3创建UserController

    

package com.huwei.controller;

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

import com.huwei.bean.User;
import com.huwei.mapper.UserMaper;

@RestController
@RequestMapping("/web")
public class UserController {

	@Autowired
	private UserMaper userMaper;
	
	@RequestMapping("/index")
	public User queryAll(){
		return userMaper.queryAll();
	}
}

2.4设置application.properties文件

    # mysql
spring.datasource.url=jdbc:mysql://localhost/spring_boot_demo?
useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=tq26556570
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2.5创建数据库

102009_hRX1_2962740.png

102019_Zu0l_2962740.png

三,测试

102108_DFZG_2962740.png

转载于:https://my.oschina.net/dzsgwz/blog/1506367

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值