数据访问
1、SpringBoot整合使用JdbcTemplate
1.1 pom文件引入
<!-- 整合JdbcTemplate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
1.2 application.properties新增配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
1.3 UserService类
@Service
@Slf4j
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void createUser(String name, Integer age) {
log.info("创建用户:名字-"+name+"年龄--"+age);
jdbcTemplate.update("insert into users values(null,?,?);",name,age);
}
}
UserController
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/createUser")
public String createUser(@RequestParam String name,@RequestParam Integer age) {
userService.createUser(name,age);
return "OK";
}
}
1.4 App类
@Configuration
//自动扫描所有Spring组件,包括@Configuration类,,Controller等。
@ComponentScan(basePackages = "com.alen.springboot.demo.*")
@EnableAutoConfiguration
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
注意: spring-boot-starter-parent要在1.5以上
2、SpringBoot整合使用mybatis
2.1、pom文件引入
<!--整合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.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.2、配置文件引入
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2.3、Mapper代码
public interface UserMapper {
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
2.4、启动方式
启动类上加注解@MapperScan
package com.alen.springboot.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
//自动扫描所有Spring组件,包括@Configuration类,,Controller等。
@ComponentScan(basePackages = "com.alen.springboot.demo.*")
@EnableAutoConfiguration
@MapperScan(basePackages ="com.alen.springboot.demo.mapper")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
3. SpringBoot集成mybatis xml方式
参考:https://www.cnblogs.com/powercto/p/6717874.html
3.1 修改application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
type-aliases-package: com.alen.springboot.demo.entity
mapper-locations: classpath:mapper/*.xml
注意根据自己的实现项目目录进行相应的修改。
- mybatis.type-aliases-package:为实体对象所在的包,跟数据库表一一对应
- mybatis.mapper-locations:mapper文件的位置
3.2 dao
需要配置dao文件,也即操作数据表的接口。启动类上加注解@MapperScan,进行dao文件的扫描,如下
@Configuration
//自动扫描所有Spring组件,包括@Configuration类,,Controller等。
@ComponentScan(basePackages = "com.alen.springboot.demo.*")
@EnableAutoConfiguration
@MapperScan(basePackages ="com.alen.springboot.demo.dao")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
3.3 controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UsersMapper usersMapper;
@GetMapping("/list/all")
public Object listAll() {
return usersMapper.selectByPrimaryKey(1);
}
}
4.mybatis分页
PageHelper 是一款好用的开源免费的 Mybatis 第三方物理分页插件
物理分页
支持常见的 12 种数据库。Oracle,MySql,MariaDB,SQLite,DB2,PostgreSQL,SqlServer 等
支持多种分页方式:支持常见的 RowBounds(PageRowBounds),PageHelper.startPage 方法调用,Mapper 接口参数调用
Github项目地址:https://github.com/pagehelper/Mybatis-PageHelper
4.1 引包
<!-- springboot 整合 pagehelper -->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
配置文件application.yml
logging:
level:
com.alen.springboot.demo.dao: DEBUG
pagehelper:
params: count=countSql
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
page-size-zero: true
Entity层
@AllArgsConstructor
@Builder
@Data
@ToString
public class Users {
private int id;
private String name;
private Integer age;
}
Mapper层
public interface UsersMapper {
@Select("SELECT * FROM USERS ")
List<Users> findUserList();
}
Service层
@Service
@Slf4j
public class UserService {
@Autowired
private UsersMapper usersMapper;
public PageInfo<Users> findUserList(int page, int size) {
// 开启分页插件,放在查询语句上面
PageHelper.startPage(page, size);
List<Users> listUser = usersMapper.findUserList();
// 封装分页之后的数据
PageInfo<Users> pageInfoUser = new PageInfo<Users>(listUser);
return pageInfoUser;
}
}
Controller层
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findUserList")
public PageInfo<Users> findUserList(int page, int size) {
return userService.findUserList(page, size);
}
}
启动项目访问:
http://localhost:8080/findUserList?page=1&size=10
5.返回主键自增id
对应的方法添加@Options注解
主键自增(auto_increment),但是在某些情况下,我们插入一条记录后,还想得到这条记录的自增主ID,useGeneratedKeys=true就是定义数据库返回主键ID的,常用的属性如下:
- useCache=true,
- flushCache=false,
- resultSetType=FORWARD_ONLY,
- statementType=PREPARED,
- fetchSize= -1,timeout=-1 ,
- useGeneratedKeys=false ,
- keyProperty=”id“。
KeyProperty是实体类中定义的主键字段名;
KeyColumn是表中主键对应的字段;
useGeneratedKeys=true定义数据库返回主键ID;
注解中的useCache还可以设置缓存相关的选项:
useCache = true表示本次查询结果被缓存以提高下次查询速度,flushCache = false表示下次查询时不刷新缓存,timeout = 10000表示查询结果缓存10000秒。
从上面的描述中,我们会发现@Options实际常用于两种场景:
@Options的两种使用场景:
(1)场景1:保存数据:返回主键id
设置@Options属性userGeneratedKeys的值为true,并指定实例对象中主键的属性名keyProperty以及在数据库中的字段名keyColumn。这样在gendar插入数据后,gendarId属性会被自动赋值。当然flushCache 仍然可以设置,表示插入数据后是否更新缓存,默认是true。
(2)场景2:查询数据:缓存数据、设置超时时间
配合查询语句使用,主要是开关一些查询的选项。比如useCache = true表示将会缓存本次查询结果,以提高下次查询速度;flushCache = Options.FlushCachePolicy.FALSE表示查询时不刷新缓存;timeout = 10000表示查询结果缓存10000秒。
/**
* 保存数据.
*/
@Insert("insert into users(name) values(#{name})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
public void save(Demo demo);
也可以在xml直接写
<insert id="insert" parameterType="com.dzcx.entity.SafeCarStatusLog" useGeneratedKeys="true" >