1. 数据库准备
a.创建数据库
CREATE DATABASE test_logistics;
b.创建表
create table wh_user (
userId int auto_increment primary key comment '用户Id',
userCode varchar(20) unique key comment '用户编码',
userName varchar(20) comment '用户名称'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 comment '用户表';
c.录入数据
INSERT INTO `wh_user` (`userCode`, `userName`) VALUES(uuid(),'张三') ;
INSERT INTO `wh_user` (`userCode`, `userName`) VALUES(uuid(),'李四') ;
INSERT INTO `wh_user` (`userCode`, `userName`) VALUES(uuid(),'王五') ;
2.项目代码
a. 项目目录
b.配置pom.xml
引入mybatis依赖
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
c.配置application.properties
#数据库配置
spring.datasource.url=jdbc:mysql://192.168.0.95:3306/test_logistics? useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=bjbshwlff
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis配置
mybatis.typeAliasesPackage=test.entity
#端口配置
server.port=8085
d.创建WhUser实体对象
package test.entity;
public class WhUser {
private Integer userId;
private String userCode;
private String userName;
public Integer getUserId() {
return userId;
}
public WhUser() {
super();
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
e.创建WhUserDao接口
package test.dao;
import org.apache.ibatis.annotations.Select;
import test.entity.WhUser;
public interface WhUserDao {
@Select("SELECT * FROM wh_user WHERE userId = #{userId}")
WhUser getUserInfo(WhUser user);
}
f.控制层和service层代码
testController.java代码
@RequestMapping("/testUserInfo.show")
public String testUserInfo(){
WhUser user = new WhUser();
user.setUserId(1);
user = testService.getUserInfo(user);
return user.getUserName();
}
testService.java代码
package test.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test.dao.WhUserDao;
import test.entity.WhUser;
@Service
@Transactional(rollbackFor = Exception.class)
public class testService {
@Resource
private WhUserDao whUserDao;
public WhUser getUserInfo(WhUser user){
return whUserDao.getUserInfo(user);
}
}
g.配置Application.java
通过@MapperScan注解进行dao文件的扫描
@SpringBootApplication //工程启动自动扫描的基础注解
@MapperScan("test.dao")//扫描dao层代码
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 运行项目
a.在启动文件Application.java中,右击–> Run As –> java Application,启动项目
b.打开浏览器,输入地址,查看返回数据,如下图