Spring boot之数据访问及mybatis整合(三)
2017-11-25 13:48
881 查看
数据访问
1、springboot整合使用JdbcTemplate
1.1 pom文件引入
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> |
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 publicclass UserServiceImplimplements UserService { @Autowired private JdbcTemplatejdbcTemplate; publicvoid createUser(Stringname, Integerage) { System.out.println("ssss"); jdbcTemplate.update("insert into users values(null,?,?);",name,age); } } |
1.4 App类
@ComponentScan(basePackages ="com.itmayiedu") @EnableAutoConfiguration publicclass App { publicstaticvoid main(String[]args) { SpringApplication.run(App.class,args); } } |
2、springboot整合使用mybatis
2.1、pom文件引入
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> <relativePath/><!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <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> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> |
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代码
publicinterface UserMapper { @Select("SELECT * FROM USERS WHERE NAME = #{name}") User findByName(@Param("name") Stringname); @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name,@Param("age") Integerage); } |
2.4、启动方式
@ComponentScan(basePackages ="com.itmayiedu") @MapperScan(basePackages ="com.itmayiedu.mapper") @SpringBootApplication publicclass App { publicstaticvoid main(String[]args) { SpringApplication.run(App.class,args); } } |
3.springboot集成mybatis xml方式
参考:https://www.cnblogs.com/powercto/p/6717874.html打开 application.properties 文件, 修改相应的数据源配置
application.properties
打开 application.properties 文件, 修改相应的数据源配置,比如数据源地址、账号、密码等,如下spring.datasource.url=jdbc:mysql://localhost:3306/test_spring_boot?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.typeAliasesPackage=zxy.demo.springboot.boot_feature.entity mybatis.mapperLocations=classpath:mapper/*.xml
注意根据自己的实现项目目录进行相应的修改。
mybatis.typeAliasesPackage:为实体对象所在的包,跟数据库表一一对应
mybatis.mapperLocations:mapper文件的位置
dao
需要配置dao文件,也即操作数据表的接口。通过@MapperScan注解进行dao文件的扫描,如下
// MyBatis 支持 @MapperScan("zxy.demo.springboot.mybatis.dao") @SpringBootApplication public class MainApplicion { public static void main(String[] args) throws Exception { SpringApplication.run(MainApplicion.class, args); } }
controller
@RequestMapping("user") @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/list/all") public Object listAll() { return userMapper.selectByExample(new UserExample()); } }
3.分页
MyBatis提供了拦截器接口,我们可以实现自己的拦截器, 将其作为一个plugin装入到SqlSessionFactory中。Github上有位开发者写了一个分页插件,Github项目地址:https://github.com/pagehelper/Mybatis-PageHelper
3.1 引包
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency>
3.2 添加配置类MyBatisConfiguration
** * Mybatis分页查询配置 **/ @Configuration public class MyBatisConfiguration { @Bean public PageHelper pageHelper() { System.out.println("MyBatisConfiguration.pageHelper()"); PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); // offsetAsPageNum:默认值为 false,该参数对使用 RowBounds 作为分页参数时有效。 // 当该参数设置为 true 时,会将 RowBounds 中的 offset 参数当成 pageNum 使用, // 可以用页码和页面大小两个参数进行分页。 p.setProperty("offsetAsPageNum", "true"); p.setProperty("rowBoundsWithCount", "true"); p.setProperty("reasonable", "true"); pageHelper.setProperties(p); return pageHelper; } }
定义SqlSessionFactory时配置对应的PageHelper插件
@Bean(name = "testSqlSessionFactory") public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Interceptor[] plugins = new Interceptor[]{new PageHelper()}; bean.setPlugins(plugins); return bean.getObject(); }
使用
public PageInfo likeName(String name){ PageHelper.startPage(1,3);//用PageInfo对结果进行包装 List<Demo> list=demoMappper.likeName(name); PageInfo page = new PageInfo(list); return page; }
PageHelper不生效:http://412887952-qq-com.iteye.com/blog/2390340
4.返回主键自增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);
相关文章推荐
- Spring boot整合mybatis实现数据的CRUD
- 文章标题Spring Boot干货系列:(十一)数据存储篇-Spring Boot整合Mybatis通用Mapper插件
- SpringBoot+MyBatis简单数据访问应用的实例代码
- 数据可视化 三步走(二):springboot整合mybatis 搭建Java Web
- 4、spring-boot 整合数据访问
- SpringCloud SpringBoot mybatis 分布式微服务(九)Spring Boot中使用Spring-data-jpa让数据访问更简单
- Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合
- Spring Boot 数据访问 JDBC-Mybatis-JPA(七)
- Spring Boot与Spring Security整合后post数据不了,403拒绝访问
- Spring Boot 数据访问集成 MyBatis 与事物配置
- Spring Boot与Spring Security整合后post数据不了,403拒绝访问
- Spring Boot + MyBatis + MySQL 整合
- Spring Boot中使用Spring-data-jpa让数据访问更简单、更优雅
- Spring Boot 整合mybatis mapper扫描(坑)
- spring boot 整合mybatis org.apache.ibatis.binding.BindingException: Invalid bound statement(not found)
- Spring boot整合mybatis
- 详解Spring Boot整合Mybatis实现 Druid多数据源配置
- 一个简单的SpringBoot整合Mybatis项目
- Spring Boot学习第三篇:Spring Boot整合Mybatis、和其他
- springboot与mybatis整合操作数据库