springboot 学习之路 3( 集成mybatis )
目录:【持续更新。。。。。】
spring 部分常用注解
spring boot 学习之路1(简单入门)
spring boot 学习之路2(注解介绍)
spring boot 学习之路3( 集成mybatis )
spring boot 学习之路4(日志输出)
spring boot 学习之路5(打成war包部署tomcat)
spring boot 学习之路6(定时任务)
spring boot 学习之路6(集成durid连接池)
spring boot 学习之路7(静态页面自动生效问题)
spring boot 学习之路8 (整合websocket(1))
spring boot 学习之路9 (项目启动后就执行特定方法)
下面就简单来说一下spring boot 与mybatiis的整合问题,如果你还没学习spring boot的注解的话,要先去看spring boot的注解
好了,现在让我们来搞一下与mybatis的整合吧,在整合过程中,我会把遇到的问题也说出来,希望可以让大家少走弯路!
首先,是在pom.xml中添加一些依赖
- 这里用到spring-boot-starter基础和spring-boot-starter-test用来做单元测试验证数据访问
- 引入连接mysql的必要依赖mysql-connector-java
- 引入整合MyBatis的核心依赖mybatis-spring-boot-starter
- 这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖
pom.xml部分依赖如下:
<!--lombok用于实体类,生成有参无参构造等只需要一个@Data注解就行-->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
注意,在上面依赖中,我多加了一个lombok的依赖,与本应用没多大关系,不要也是可以的,不影响项目运行。具体作用是实体类上通过注解来替代get/set tosSring()等,具体用法参考lombok的简单介绍(1)
在application.properties中配置mysql的连接配置:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
#连接mybatis 和在springmvc中一致,要制定mybatis配置文件的路径 上面是连接jdbcTemplate 相当于连接jdbc
# mybatis.config= classpath:mybatis-config.xml
#mybatis.mapperLocations=classpath:mappers/*.xml #mybatis.mapper-locations=classpath*:mappers/*Mapper.xml
#mybatis.type-aliases-package=com.huhy.web.entity spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp #设置端口
server.port=9999
#指定server绑定的地址
server.address=localhost
#设置项目访问根路径 不配置,默认为/
server.context-path=/
上面这些配置具体什么意义我就在这不多解释了,这些配置好之后,就可以搞代码开发了。
首先创建一个User类:
package com.huhy.web.entity; import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; /**
* Created by ${huhy} on 2017/8/5.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String id;
private String name;
private int age;
}
实体类中我用到的注解是来自lombok中的,添加上@Data, @NoArgsConstructor, @AllArgsConstructor这几个注解,和我们写出来那些get/set,有参无参,toString 是一样的
UserMapper接口
package com.huhy.web.mapper; import com.huhy.web.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; /**
* @Author:{huhy}
* @DATE:Created on/8/5 22:19
* @Class Description:
*/
@Mapper
public interface UserMapper {
/*
* 通过id查询对应信息
* */
@Select("SELECT * FROM USER WHERE id = #{id}")
User selectByPrimaryKey(String id);
/*
* 通过name 查询对应信息
* */
@Select("Select * from user where name = #{name} and id = #{id}")
User selectByName(@Param("name") String name, @Param("id") String id); /**
* @param id
* @param name
* @param age
* @return
*/
@Insert("INSERT INTO USER(id,NAME, AGE) VALUES(#{id},#{name}, #{age})")
int insert(@Param("id") String id,@Param("name") String name, @Param("age") Integer age);
}
在mapper通过注解编程写的,你也可以通过配置文件的形式,在.properties也有,只是被我注释了,现在统一用注解开发。
Service
package com.huhy.web.service.impl; import com.huhy.web.entity.User;
import com.huhy.web.mapper.UserMapper;
import com.huhy.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @Author:{huhy}
* @DATE:Created on 2017/8/5 22:18
* @Class Description:
*/
@Service
public class UserServiceImpl implements UserService{ @Autowired
private UserMapper userMapper; @Override
public User queryById(String id) {
User user = userMapper.selectByPrimaryKey(id);
return user;
} public User queryByName(String name,String id){
User user = userMapper.selectByName(name,id);
return user;
}
}
注意:在这有个问题: 通过UserMapper 的类上有两种注解可以使用:@Mapper 和 @Repository (我从网上查了一下,没发现有太大的差别,而且用不用都可以。我在使用中的唯一区别就是 @Repository注解,在service进行自动注入不会报warn,而@Mapper会报warn ,不管怎样不影响程序的运行)
展示层(controller)
package com.huhy.web.controller; import com.huhy.web.entity.User;
import com.huhy.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* Created by ${huhy} on 2017/8/5.
*/ @RestController
public class JDBCController {
/* @Autowired
private JdbcTemplate jdbcTemplate;
*/
@Autowired
private UserService userService; /**
* 测试数据库连接
*/
/*@RequestMapping("/jdbc/getUsers")
public List<Map<String, Object>> getDbType(){
String sql = "select * from user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}*/ @RequestMapping("/jdbcTest/{id}")
public User jdbcTest(@PathVariable("id") String id){
return userService.queryById(id);
} @RequestMapping("/jdbcTestName/{name}/{id}")
public User queryByName(@PathVariable("name") String name,@PathVariable("id") String id){
return userService.queryByName(name,id);
}
@RequestMapping("/name")
public String getName(){
return "huhy";
} }
最后运行启动类就可以测试了:(在这有两中方式测试,第一种单独运行测试类,第二种就是junit测试)
第一种:启动类启动
package com; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("com.huhy.web.mapper")//扫描dao接口
public class DemoApplication {
/**
*
* @param 启动类
*/
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
上面@MapperScan后面跟的是我的mapper文件的包名。
第二种启动方式:junit测试(注意注解@SpringBootTest)
package com.example.demo; import com.DemoApplication;
import com.huhy.web.entity.User;
import com.huhy.web.mapper.UserMapper;
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.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! @RunWith(SpringRunner.clss)
@SpringBootTest(classes = DemoApplication.class) // 指定我们SpringBoot工程的Application启动类 @SpringBootTest
@WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
public class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
@Rollback
public void findByName() throws Exception {
userMapper.insert("17","def",123);
User user = userMapper.selectByName("def","17");
System.out.println(user);
}
}
注意 :@SpringBootTest注解是在1.4版本之后才有的,原来是SpringApplicationConfiguration。在使用junit测试时,具体看看你的sprin-boot-test的版本
如果你遇到SpringApplicationConfiguration 不能使用那就是以为 Spring Boot的SpringApplicationConfiguration注解在Spring Boot 1.4开始,被标记为Deprecated
springboot 学习之路 3( 集成mybatis )的更多相关文章
- springboot 学习之路 15(集成shiro)
shiro: Apache Shiro 是 Java 的一个安全框架.功能强大,使用简单的Java安全框架,它为开发人员提供一个直观而全面的认证,授权,加密及会话管理的解决方案. 更多shiro介 ...
- springboot 学习之路 6(集成durid连接池)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 8 (整合websocket(1))
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 1(简单入门)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 6(定时任务)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 9 (项目启动后就执行特定方法)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 2(注解介绍)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 4(日志输出)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- springboot 学习之路 5(打成war包部署tomcat)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
随机推荐
- HTML5拍照、摄像机功能实战
HTML5拍照.摄像机功能实战 苏格团队 作者:Tomey 开篇 最近在做一个chrome app的云相机应用,应用包括拍照.摄像.保存照片视频.上传文件等等核心功能,其中涉及到很多HTML5对媒体流 ...
- 剑指offer【07】- 斐波那契数列(java)
题目:斐波那契数列 考点:递归和循环 题目描述:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0),n<=39. 法一:递归法,不过递归比较慢, ...
- PythonDay02——编程语言、python介绍以及安装解释器、运行程序的两种方式、变量
一.编程语言 1.1 机器语言:直接用计算机能理解的二进制指令编写程序,直接控制硬件 1.2 汇编语言:用英文标签取代二进制指令去编写程序,本质也是直接控制硬件 1.3 高级语言:用人能理解的表达方式 ...
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
Java中,可以使用Arrays.asList(T... a)方法来把一个数组转换为List,返回一个受指定数组支持的固定大小(注意是固定大小)的列表.此方法同 Collection.toArray( ...
- mysql 开发进阶篇系列 17 MySQL Server(key_buffer与table_cache)
一.key_buffer 上一篇了解key_buffer设置,key_buffer_size指定了索引缓冲区的大小,它决定索引处理的速度,尤其是索引读的速度.通过检查状态值Key_read_reque ...
- Java线程之 InterruptedException 异常
Java线程之 InterruptedException 异常 当一个方法后面声明可能会抛出InterruptedException 异常时,说明该方法是可能会花一点时间,但是可以取消的方法. 抛 ...
- 自动化测试 | UI Automator 进阶指南
UI Automator 相关介绍: 跨应用的用户界面自动化测试 包含在 AndroidX Test(https://developer.android.com/training/testing) 中 ...
- MFC控件GDI编程
MFC控件GDI编程 一丶学习内容 1.了解常用的GDI函数绘图. 2.使用常用的画笔画刷. 二丶常用的GDI函数绘图 上方则为我们常用的GDI函数了. 画线 矩形. 以及圆 等等. 2.1 画线代码 ...
- 基于saltstack自动化部署高可用kubernetes集群
SaltStack自动化部署HA-Kubernetes 本项目在GitHub上,会不定期更新,大家也可以提交ISSUE,地址为:https://github.com/skymyyang/salt-k8 ...
- Nacos系列:欢迎来到Nacos的世界!
什么是Nacos? Nacos 是构建以"服务"为中心的现代应用架构 (例如微服务范式.云原生范式) 的服务基础设施. Nacos可以做什么? 1.动态配置服务:支持以中心化.外部 ...