SpringBoot整合Mybatis实例

来源:互联网 发布:c语言里的共用体怎么用 编辑:程序博客网 时间:2024/06/03 21:57

这只是一个SpringBoot的简单实例。
SpringBoot项目解决配置繁琐的问题,最大化的实现convention over configuration(约定大于配置)。
并且实现自动化配置Spring,简化Maven配置,嵌入tomcat。
第一、创建Maven项目,pom.xml文件配置如下:
这里写图片描述
这里写图片描述

如上,pom.xml文件对数据库,mybatis都做了依赖,而我使用的数据库是oracle。
第二:application.properties文件(.yml文件用得更多)配置如下:
这里写图片描述
这里写图片描述

目录文件结构为:
这里写图片描述

第四、Application代码及运行结果:
这里写图片描述

这里的@SpringBootApplication=(默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。
其中@Service,@Repository,@Controller是@ComponentScan
的子注解。
@EnableAutoConfiguration表示自动配置上下文。
@MapperScan注解dao包/mapper对象,dao包不需要@Repository注解。
Application.java可通过main方法直接启动。

Model类如下:
package com.xieting.node.model;

public class UserVo {
private String username;
private Long Id;
private String uaccountName;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getUaccountName() {
return uaccountName;
}
public void setUaccountName(String uaccountName) {
this.uaccountName = uaccountName;
}
}

Mapper接口:
package com.xieting.node.mapper;
import com.xieting.node.model.UserVo;

public interface UserDao {
UserVo findUserById(long id);
}

Myservice接口:
package com.xieting.node.service;
import com.xieting.node.model.UserVo;

public interface MyService {
UserVo findUserById(long id);
}

MyServiceImpl接口实现类:
package com.xieting.node.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xieting.node.mapper.UserDao;
import com.xieting.node.model.UserVo;
import com.xieting.node.service.MyService;
@Service
public class MyServideImpl implements MyService{
@Autowired
private UserDao userDao;
@Override
public UserVo findUserById(long id) {
return userDao.findUserById(id);
}
}

Controller类代码如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.xieting.node.model.UserVo;
import com.xieting.node.service.MyService;

@RestController
public class SempleController {
@Autowired
private MyService myService;
@RequestMapping(value = “/user/findUser”, method = RequestMethod.GET)
public UserVo gsTest(long id){
return myService.findUserById(id);
}
}
其中@RestController 表示@controller + @ResponseBody。

Mapper映射文件如下:
这里写图片描述
Mybatis-config.xml文件:
这里写图片描述

最后程序通过Application类运行启动,直接可以在浏览器访问地址:http://localhost:8080/SpringBootDemo/user/findUser?id=1

获得结果如图显示:这里写图片描述

到此,一个SpringBoot整合Mybatis项目完成。当然这只是最基础的知识,深入学习请网上查找更多资料。