最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于springboot2集成jpa,創(chuàng)建dao的案例

 更新時(shí)間:2021年01月29日 10:39:18   作者:小土豆子額  
這篇文章主要介紹了基于springboot2集成jpa,創(chuàng)建dao的案例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

springboot中集成jpa需要再pom文件中添加jpa的jar包,使用springboot的話iju不用自己規(guī)定版本號了,自動(dòng)管理依賴版本即可。

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

然后我們再添加hibernate和oracle的jar包,同樣自動(dòng)管理版本。

 <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和鏈接數(shù)據(jù)庫的信息。

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

添加完成之后我們開始創(chuàng)建jpa使用的公共Repository,創(chuàng)建一個(gè)接口。這里的接口可以直接繼承JpaRepository,或者可以繼承別的Repository.注意要加上@NoRepositoryBean注解,告訴Spring數(shù)據(jù):不要?jiǎng)?chuàng)建該接口實(shí)例。

當(dāng)我們在下面使用dao的時(shí)候再進(jìn)行創(chuàng)建實(shí)例

@NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T,Long> {
}

現(xiàn)在我們創(chuàng)建好了這基礎(chǔ)的Repository如果有自己想封裝的公用方法的話就可以添加到這個(gè)接口中,進(jìn)行約束。

當(dāng)我們創(chuàng)建dao接口的時(shí)候,直接繼承這個(gè)基礎(chǔ)的Repository;繼承之后這個(gè)dao再spring中默認(rèn)識別為一個(gè)Repository。

public interface TbUserDao extends BaseRepository<TbUser> {
}

下面我們就可以直接再service中注入這個(gè)dao。

@Service
public class UserService {
 @Resource
 private TbUserDao userDao;
}

現(xiàn)在我們看一下JpaRepository源碼,其中繼承了PagingAndSortingRepository和QueryByExampleExecutor,也就是里面直接有了各種查詢的方法,并且在這兩個(gè)基礎(chǔ)上添加了保存和刪除的方法。

@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繼承的兩個(gè)接口中的代碼,PagingAndSortingRepository是繼承了CrudRepository的,這個(gè)CrudRepository中同樣有刪除保存查詢等方法,是比較全的,但是如果我們直接使用這個(gè)CrudRepository的話里面的查詢是沒有分頁的方法。

而PagingAndSortingRepository是在基礎(chǔ)上新加了分頁查詢的方法。

所以我們沒有直接使用CrudRepository

@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
 Iterable<T> findAll(Sort var1);
 Page<T> findAll(Pageable var1);
}

會(huì)有疑問的是我們這里的接口為什么可以直接注入。

因?yàn)楫?dāng)我們運(yùn)行項(xiàng)目的時(shí)候,spring識別這個(gè)dao是一個(gè)Repository會(huì)自動(dòng)為這個(gè)接口創(chuàng)建一個(gè)接口名+Impl的實(shí)現(xiàn)類,如下例子中的就是生成TbUserDaoImpl的實(shí)現(xiàn)類。

這個(gè)我們可以在EnableJpaRepositories注解源碼中可以看到。

里面的repositoryImplementationPostfix()方法是定義repository接口生成的實(shí)現(xiàn)類后綴是什么,springboot默認(rèn)幫我們定義成了Impl。

我們也可以在springboot啟動(dòng)類上面使用這個(gè)注解自己定義這個(gè)值。

@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;
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • Java Process類的詳解及實(shí)例代碼

    Java Process類的詳解及實(shí)例代碼

    這篇文章主要介紹了Java Process類的詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • 解讀controller層,service層,mapper層,entity層的作用與聯(lián)系

    解讀controller層,service層,mapper層,entity層的作用與聯(lián)系

    這篇文章主要介紹了關(guān)于controller層,service層,mapper層,entity層的作用與聯(lián)系,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • 淺談Spring Boot 微服務(wù)項(xiàng)目的推薦部署方式

    淺談Spring Boot 微服務(wù)項(xiàng)目的推薦部署方式

    這篇文章主要介紹了淺談Spring Boot 微服務(wù)項(xiàng)目的推薦部署方式,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-09-09
  • JavaWeb簡單文件上傳流程的實(shí)戰(zhàn)記錄

    JavaWeb簡單文件上傳流程的實(shí)戰(zhàn)記錄

    在Web應(yīng)用系統(tǒng)開發(fā)中,文件上傳和下載功能是非常常用的功能,下面這篇文章主要給大家介紹了關(guān)于JavaWeb實(shí)現(xiàn)簡單文件上傳流程的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-03-03
  • 深入理解Java設(shè)計(jì)模式之單例模式

    深入理解Java設(shè)計(jì)模式之單例模式

    這篇文章主要介紹了JAVA設(shè)計(jì)模式之單例模式的的相關(guān)資料,文中示例代碼非常詳細(xì),供大家參考和學(xué)習(xí),感興趣的朋友可以了解下
    2021-11-11
  • Java連接Redis的兩種方式

    Java連接Redis的兩種方式

    Redis 是一種高性能的鍵值存儲數(shù)據(jù)庫,廣泛應(yīng)用于緩存、消息隊(duì)列、會(huì)話存儲等場景,Java 作為一門廣泛使用的編程語言,提供了多種方式來連接和操作 Redis,本文將介紹兩種常用的 Java 連接 Redis 的方式,需要的朋友可以參考下
    2025-03-03
  • springboot 加載 META-INF/spring.factories方式

    springboot 加載 META-INF/spring.factories方式

    這篇文章主要介紹了springboot 加載 META-INF/spring.factories方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 詳解Java中的線程池

    詳解Java中的線程池

    這篇文章主要介紹了Java中的線程池,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Mybatis對mapper的加載流程深入講解

    Mybatis對mapper的加載流程深入講解

    這篇文章主要給大家介紹了關(guān)于Mybatis對mapper的加載流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • java實(shí)現(xiàn)md5加密示例

    java實(shí)現(xiàn)md5加密示例

    這篇文章主要介紹了java實(shí)現(xiàn)md5加密示例,需要的朋友可以參考下
    2014-05-05

最新評論

专栏| 游戏| 叙永县| 亳州市| 萍乡市| 错那县| 博白县| 郸城县| 安顺市| 崇信县| 建湖县| 三亚市| 留坝县| 清涧县| 林芝县| 义马市| 台前县| 铁力市| 施甸县| 九龙县| 鹤峰县| 宁波市| 霍州市| 容城县| 云阳县| 贺州市| 怀仁县| 渝北区| 宣武区| 大埔县| 龙海市| 定结县| 卢湾区| 乌恰县| 龙陵县| 弋阳县| 霞浦县| 湟中县| 彰化县| 隆尧县| 长乐市|