Spring Boot下如何自定义Repository中的DAO方法
环境配置介绍
jdk 1.8, Spring Boot 1.5.3.RELEASE, Mysql, Spring Data, JPA
问题描述
Spring Data提供了一套简单易用的DAO层抽象与封装,覆盖的CURD的基本功能,但是在诸多的情况下,需要用户自定义DAO的实现方法,来实现更为复杂和精细的数据库访问操作,该如何来解决这个问题?
目标描述
这里我们以自定义testAA的方法为例,来介绍如何实现自定义的DAO方法扩展。
数据库表的定义
我们这里定义了一个非常简单的mycity表,来作为示例的实体类BaseEntity:
数据库表定义:
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
@MappedSuperclass
public abstract class BaseEntity implements java.io.Serializable {
private static final long serialVersionUID = -2420979951576787924L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Version
private Long version;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATE_TIME",columnDefinition="timestamp default CURRENT_TIMESTAMP")
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "UPDATE_TIME",columnDefinition="timestamp default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date updateTime;
}
MyCity的定义如下:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Table(name="mycity")
@Data
public class City extends BaseEntity {
private static final long serialVersionUID = -7510771121759944670L;
@Column(name="Name")
private String name;
@Column(name="country_code")
private String countryCode;
@Column
private String district;
@Column
private int population;
}
这里的@Data使用了lombok提供的强大标注,来简化冗余Getter/Setter方法的使用。
定义Repository
标准的CityRepository.java,这里完全使用缺省提供的方法:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.rose.money.City;
@Repository
public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom{
}
这里的CityRepository继承了2个父类,包括用户自定义的接口类,让用户自定义的接口可以暴漏出来。
这里的CityRepsoitoryCustom定义了用户的自定义方法:
public interface CityRepositoryCustom {
public void testAA();
}
Notice: 这里的Custom后缀是约定的,不能随意修改。
自定义方法的实现类:
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
public class CityRepositoryImpl implements CityRepositoryCustom {
@Autowired
@PersistenceContext
private EntityManager entityManager;
@Override
public void testAA() {
List<Object[]> cities = entityManager.createNativeQuery("select id, name, district from mycity").getResultList();
for (Object[] objs : cities) {
System.out.print("location 1:" + objs[0]);
System.out.print("location 2:" + objs[1]);
System.out.print("location 3:" + objs[2]);
}
}
}
这里的实现类就是读取了几条记录,然后打印出来。其实现了Custom的接口类。
配置信息
application.properties:
spring.application.name=custom jpa
spring.jpa.database=MYSQL
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/world?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=true
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.show-sql=true
测试
测试用例:
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.context.junit4.SpringRunner;
import com.rose.money.repository.CityRepository;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomjpaApplicationTests {
@Autowired
private CityRepository cityRepo;
@Test
public void contextLoads() {
City city = cityRepo.findOne(1l);
System.out.println("city=>" + city);
cityRepo.testAA();
}
}
测试的结果图示:
总结
约定大于配置,Custom后缀实现与扩展,非常的简单实用。
Spring Boot下如何自定义Repository中的DAO方法的更多相关文章
- spring boot / cloud (四) 自定义线程池以及异步处理@Async
spring boot / cloud (四) 自定义线程池以及异步处理@Async 前言 什么是线程池? 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线 ...
- spring boot下使用logback或log4j生成符合Logstash标准的JSON格式
spring boot下使用logback或log4j生成符合Logstash标准的JSON格式 一.依赖 由于配置中使用了json格式的日志输出,所以需要引入如下依赖 "net.logst ...
- 转-Hive/Phoenix + Druid + JdbcTemplate 在 Spring Boot 下的整合
Hive/Phoenix + Druid + JdbcTemplate 在 Spring Boot 下的整合 http://blog.csdn.net/balabalayi/article/detai ...
- Spring Boot下的一种导入Excel文件的代码框架
1.前言 Spring Boot下如果只是导入一个简单的Excel文件,是容易的.网上类似的文章不少,有的针对具体的实体类,代码可重用性不高:有的利用反射机制或自定义注解,开发了Excel导入工具 ...
- 200. Spring Boot JNDI:在Tomcat中怎么玩JNDI?
[视频&交流平台] àSpringBoot视频:http://t.cn/R3QepWG à SpringCloud视频:http://t.cn/R3QeRZc à Spring Boot源 ...
- Spring Boot下Druid连接池+mybatis
目前Spring Boot中默认支持的连接池有dbcp,dbcp2, hikari三种连接池. 引言: 在Spring Boot下默认提供了若干种可用的连接池,Druid来自于阿里系的一个开源连 ...
- Spring boot 自动配置自定义配置文件
示例如下: 1. 新建 Maven 项目 properties 2. pom.xml <project xmlns="http://maven.apache.org/POM/4 ...
- 【spring boot】10.spring boot下的单元测试
spring boot下的单元测试,思前想后还是需要单独用一章篇幅来看看. 然后在看了介绍和使用时候,我感觉并不想多去看了. 但是还是给后来人留下参考的路径: 官网说明:https://spring. ...
- 【ActiveMQ】2.spring Boot下使用ActiveMQ
在spring boot下使用ActiveMQ,需要一下几个条件 1.安装并启动了ActiveMQ,参考:http://www.cnblogs.com/sxdcgaq8080/p/7919489.ht ...
随机推荐
- AngularJS 笔记之创建服务方式比较 : factory vs service vs provider 。
首先说一下服务这个东西是用来干嘛的.很多时候我们把太多的数据和逻辑都一股脑儿地往 controller 里放.这样我们的 controller 原来越臃肿.从它们的生命周期可以发现,其实 contro ...
- beego——静态文件
Go 语言内部其实已经提供了 http.ServeFile,通过这个函数可以实现静态文件的服务. beego 针对这个功能进行了一层封装,通过下面的方式进行静态文件注册: beego.SetStati ...
- Linux Shell编程第5章——文件的排序、合并和分割
目录 sort命令 sort命令的基本用法 uniq命令 join命令 cut命令 paste命令 split命令 tr命令 tar命令 sort命令 sort命令是Linux系统一种排序工具,它将输 ...
- curl简介、安装及使用
目录 curl简介 curl安装 curl使用 curl简介 curl是Linux下一个强大的文件传输工具,它利用URL语法在命令行方式下工作,支持文件上传和下载. curl安装 Ubuntu系统键入 ...
- 腾讯天猫经常出现这些低级的bug!
对于程序员来说,bug很讨厌.每天重复着写代码.找bug.修改bug的动作.按理说互联网巨头的产品,bug应该比较少.但是实际上,无论是用百度.天猫.谷歌等产品,经常都会出现这些低级的bug,让人很火 ...
- 450. Delete Node in a BST
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...
- Mac 一键显示所有隐藏文件 不要那么六好吧
系统应简洁而有效,对一般用户来说这一点尤为重要.不必要让普通用户知道的信息往往会给他们造成困扰,因而,隐藏掉他们便是个不错的选择,既可以保证系统平稳流畅运行,也可以为用户提供友好界面. 对于开发者而言 ...
- powerdesign简单应用
PowerDesigner是一款功能非常强大的建模工具软件,足以与Rose比肩,同样是当今最著名的建模软件之一.Rose是专攻UML对象模型的建模工具,之后才向数据库建模发展,而PowerDesign ...
- 最小可用 Spring MVC 配置
[最小可用 Spring MVC 配置] 1.导入有概率用到的JAR包, -> pom.xml 的更佳实践 - 1.0 <- <project xmlns="http:// ...
- 项目中使用better-scroll实现移动端滚动,报错:Cannot read property 'children' of undefined better-scroll
就是外面的盒子和要滚动的元素之间要有一层div, 插件挂载的元素是menuWrapper,可以滚动的元素是ul,在这两个元素之间加一个div元素即可解决问题.