基于springboot2集成jpa,创建dao的案例
作者:小土豆子额 发布时间:2021-08-02 00:40:46
springboot中集成jpa需要再pom文件中添加jpa的jar包,使用springboot的话iju不用自己规定版本号了,自动管理依赖版本即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
然后我们再添加hibernate和oracle的jar包,同样自动管理版本。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4.0</version>
</dependency>
然后我们在配置文件中添加jpa和链接数据库的信息。
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DESKTOP-46DMVCH:1521:orcl
spring.datasource.password=****
spring.datasource.username=****
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
spring.jpa.database=oracle
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.log-abandoned=true
spring.datasource.remove-abandoned=true
spring.datasource.remove-abandoned-timeout=200
添加完成之后我们开始创建jpa使用的公共Repository,创建一个接口。这里的接口可以直接继承JpaRepository,或者可以继承别的Repository.注意要加上@NoRepositoryBean注解,告诉Spring数据:不要创建该接口实例。
当我们在下面使用dao的时候再进行创建实例
@NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T,Long> {
}
现在我们创建好了这基础的Repository如果有自己想封装的公用方法的话就可以添加到这个接口中,进行约束。
当我们创建dao接口的时候,直接继承这个基础的Repository;继承之后这个dao再spring中默认识别为一个Repository。
public interface TbUserDao extends BaseRepository<TbUser> {
}
下面我们就可以直接再service中注入这个dao。
@Service
public class UserService {
@Resource
private TbUserDao userDao;
}
现在我们看一下JpaRepository源码,其中继承了PagingAndSortingRepository和QueryByExampleExecutor,也就是里面直接有了各种查询的方法,并且在这两个基础上添加了保存和删除的方法。
@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll()
*/
List<T> findAll();
/*
* (non-Javadoc)
* @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort)
*/
List<T> findAll(Sort sort);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll(java.lang.Iterable)
*/
List<T> findAllById(Iterable<ID> ids);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable)
*/
<S extends T> List<S> saveAll(Iterable<S> entities);
/**
* Flushes all pending changes to the database.
*/
void flush();
/**
* Saves an entity and flushes changes instantly.
*
* @param entity
* @return the saved entity
*/
<S extends T> S saveAndFlush(S entity);
/**
* Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear
* the {@link javax.persistence.EntityManager} after the call.
*
* @param entities
*/
void deleteInBatch(Iterable<T> entities);
/**
* Deletes all entities in a batch call.
*/
void deleteAllInBatch();
/**
* Returns a reference to the entity with the given identifier.
*
* @param id must not be {@literal null}.
* @return a reference to the entity with the given identifier.
* @see EntityManager#getReference(Class, Object)
* @throws javax.persistence.EntityNotFoundException if no entity exists for given {@code id}.
*/
T getOne(ID id);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example)
*/
@Override
<S extends T> List<S> findAll(Example<S> example);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
@Override
<S extends T> List<S> findAll(Example<S> example, Sort sort);
}
我们再看Jpa继承的两个接口中的代码,PagingAndSortingRepository是继承了CrudRepository的,这个CrudRepository中同样有删除保存查询等方法,是比较全的,但是如果我们直接使用这个CrudRepository的话里面的查询是没有分页的方法。
而PagingAndSortingRepository是在基础上新加了分页查询的方法。
所以我们没有直接使用CrudRepository
@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort var1);
Page<T> findAll(Pageable var1);
}
会有疑问的是我们这里的接口为什么可以直接注入。
因为当我们运行项目的时候,spring识别这个dao是一个Repository会自动为这个接口创建一个接口名+Impl的实现类,如下例子中的就是生成TbUserDaoImpl的实现类。
这个我们可以在EnableJpaRepositories注解源码中可以看到。
里面的repositoryImplementationPostfix()方法是定义repository接口生成的实现类后缀是什么,springboot默认帮我们定义成了Impl。
我们也可以在springboot启动类上面使用这个注解自己定义这个值。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(JpaRepositoriesRegistrar.class)
public @interface EnableJpaRepositories {
/**
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.:
* {@code @EnableJpaRepositories("org.my.pkg")} instead of {@code @EnableJpaRepositories(basePackages="org.my.pkg")}.
*/
String[] value() default {};
/**
* Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this
* attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names.
*/
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The
* package of each class specified will be scanned. Consider creating a special no-op marker class or interface in
* each package that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {};
/**
* Specifies which types are eligible for component scanning. Further narrows the set of candidate components from
* everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters.
*/
Filter[] includeFilters() default {};
/**
* Specifies which types are not eligible for component scanning.
*/
Filter[] excludeFilters() default {};
/**
* Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So
* for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning
* for {@code PersonRepositoryImpl}.
*
* @return
*/
String repositoryImplementationPostfix() default "Impl";
/**
* Configures the location of where to find the Spring Data named queries properties file. Will default to
* {@code META-INF/jpa-named-queries.properties}.
*
* @return
*/
String namedQueriesLocation() default "";
/**
* Returns the key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to
* {@link Key#CREATE_IF_NOT_FOUND}.
*
* @return
*/
Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND;
/**
* Returns the {@link FactoryBean} class to be used for each repository instance. Defaults to
* {@link JpaRepositoryFactoryBean}.
*
* @return
*/
Class<?> repositoryFactoryBeanClass() default JpaRepositoryFactoryBean.class;
/**
* Configure the repository base class to be used to create repository proxies for this particular configuration.
*
* @return
* @since 1.9
*/
Class<?> repositoryBaseClass() default DefaultRepositoryBaseClass.class;
// JPA specific configuration
/**
* Configures the name of the {@link EntityManagerFactory} bean definition to be used to create repositories
* discovered through this annotation. Defaults to {@code entityManagerFactory}.
*
* @return
*/
String entityManagerFactoryRef() default "entityManagerFactory";
/**
* Configures the name of the {@link PlatformTransactionManager} bean definition to be used to create repositories
* discovered through this annotation. Defaults to {@code transactionManager}.
*
* @return
*/
String transactionManagerRef() default "transactionManager";
/**
* Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the
* repositories infrastructure.
*/
boolean considerNestedRepositories() default false;
/**
* Configures whether to enable default transactions for Spring Data JPA repositories. Defaults to {@literal true}. If
* disabled, repositories must be used behind a facade that's configuring transactions (e.g. using Spring's annotation
* driven transaction facilities) or repository methods have to be used to demarcate transactions.
*
* @return whether to enable default transactions, defaults to {@literal true}.
*/
boolean enableDefaultTransactions() default true;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/chenyidong521/article/details/79798158


猜你喜欢
- Android Fragment滑动组件ViewPager的实例详解1适配器FragmentPagerAdapter的实现对于Fragmen
- 现在的手机一般都会提供相机功能,有些相机的镜头甚至支持1300万以上像素,有些甚至支持独立对焦、光学变焦这些只有单反才有的功能,甚至有些手机
- 如下图所示,你的UI元素可能小于48dp,图标仅有32dp,按钮仅有40dp,但是他们的实际可操作焦点区域最好都应达到48dp的大小。为使小
- 为什么要在控制台输出 SQL 呢?当然是为了开发调试的时候方便了。如果一个 数据库相关的操作出现了问题,我们可以根据输出的SQL语句快速排查
- 在java中,单例有很多种写法,面试时,手写代码环节,除了写算法题,有时候也会让手写单例模式,这里记录一下单例的几种写法和优缺点。1.初级写
- 这篇文章主要介绍了JAVA如何按字节截取字符串,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参
- 本文实例为大家分享了Java网络编程TCP实现文件上传的具体代码,供大家参考,具体内容如下上一篇博客,用网络编程TCP 实现聊天,这次实现文
- 一、来源项目中遇到混合动画的情况,每次实现都需要生命一堆属性,让代码变得杂乱,难以维护。参考 iOS 组动画 CAAimationGroup
- 本文实例为大家分享了android自定义View实现五子棋的具体代码,供大家参考,具体内容如下先说一下吧,android的自定义View就是
- C#的FileInfo类提供了与File类相同的功能,不同的是FileInfo提供的都是成员方法,使用示例如下所示:1、读文件://创建只读
- Android 获取IP地址最近做项目,有一个需求是Android设备获取当前IP的功能,经过一番查询资料解决了,记录下实现方法。1.使用W
- 本文实例讲述了Android中断线程的处理方法。分享给大家供大家参考。具体方法如下:我现在对一个用户注册的功能1.用ProgressDial
- Springboot上传文件时提示405问题描述:上传文件时请求不通,状态码返回405,如下图: 问题分析:405 Method
- 本文实例讲解了java遍历读取xml文件内容的详细代码,分享给大家供大家参考,具体内容如下package test;import java.
- //1.创建数据库public class DBService extends SQLiteOpenHelper {private fina
- 参考ColorComboBox做修改,并对颜色名做些修正,用于CR MVMixer产品中,聊作备忘~效果图:代码://颜色拾取框using
- 准备工作这里就不说了,包括签约和申请APPID,附上微信开放平台APP开发步骤,不懂的同学可以参考这里:https://pay.weixin
- menu部分xml代码<?xml version="1.0" encoding="utf-8"
- 引言热修复技术如今已经不是一个新颖的技术,很多公司都在用,而且像阿里、腾讯等互联网巨头都有自己的热修复框架,像阿里的AndFix采用的是ho
- 在微服务架构中,我们将一个项目拆分成很多个独立的模块,这些独立的模块通过远程调用来互相配合工作,但是,在高并 * 况下,通信次数的增加会导致总