インターネットはそれを記録、参照するには、元:https://blog.csdn.net/Lee_Ho_/article/details/81014215
ワン:はじめに
従来のリレーショナル・データベースへ、春ブーツデータベースの動作を実現するJPA(Javaの永続API)リソースライブラリを使用して、簡単な言葉で、JPAは、POJO(プレーン普通のJavaオブジェクト)規格の持続性を提供し、今後のJavaへですオブジェクトリレーショナルマッピングを介して、通常のオブジェクト(リレーショナルマッピング、ORMオブジェクト)データベースに永続。
2:使用
2.1:JPA構成
JPAとMySQLを使用するためには、春ブーツは、Mavenプロジェクトを作成し、それらに依存してPOMファイルで導入:
<?xml version = "1.0"のエンコード= "UTF-8"?>
<プロジェクトのxmlns = "http://maven.apache.org/POM/4.0.0"のxmlnsを:XSI = "のhttp://www.w3 .ORG / 2001 / XMLスキーマ・インスタンス」
のxsi:のschemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion> 4.0.0 </ modelVersion>
<groupIdを> com.example </ groupIdを>
<たartifactId>春ブート-JPA </たartifactId>
<バージョン> 0.0.1-SNAPSHOT </バージョン>
<パッケージ> JAR </パッケージ>
<名前>春ブート-JPA </ name>の
春ブーツのための<説明>デモプロジェクト</記述>
<親>
<groupIdを> org.springframework.boot </ groupIdを>
<たartifactId>春・ブート・スターター・親</たartifactId>
<バージョン> 2.0.3.RELEASE </バージョン>
<relativePath /> <! -ルック親リポジトリから- >
</親>
<プロパティ>
<project.build.sourceEncoding> UTF-8 </project.build.sourceEncoding>
<project.reporting.outputEncoding> UTF-8 </project.reporting.outputEncoding>
<のjava.version> 1.8 </java.version>
</プロパティ>
<依存性>
<依存性>
<のgroupId> org.springframework.boot </のgroupId>
<たartifactId>ばねブートスタータ-web </たartifactId>
</依存>
<依存性>
<のgroupId> org.springframework.boot </のgroupId>
<たartifactId>ばねブートスタータデータJPA </たartifactId>
</依存>
<依存>
<groupIdを> mysqlの</ groupIdを>
<たartifactId>のmysql-コネクタ-javaの</たartifactId>
<スコープ>実行</スコープ>
</依存>
<依存性>
<のgroupId> org.springframework.boot </のgroupId>
<たartifactId>ばねブートスタータ試験</たartifactId>
<スコープ>テスト</スコープ>
< /依存関係>
</従属関係>
<構築>
<finalName> JPA </ finalName>
<プラグイン>
<プラグイン>
<groupIdを> org.springframework.boot </ groupIdを>
<たartifactId>春・ブートのmaven-pluginの</たartifactId>
<実行>
<実行>
<目標>
<目標>
再パッケージ
</目標>
</目標>
</実行>
</実行>
</プラグイン>
</プラグイン>
</構築>
</プロジェクト>
application.yml配置:
春:
データ・ソース:
?URLます。jdbc:mysqlの:// localhostを:3306 /テストcharacterEncoding = UTF8
ユーザ名:ルート
パスワード:cuoai1995
JPA:
データベース:MySQLの
ショー-SQL:真
#HibernateのDDL自動(検証|作成ドロップを|作成します|更新)
休止状態:
DDL-オート:アップデート
命名戦略:org.hibernate.cfg.ImprovedNamingStrategyの
プロパティ:
休止状態:
方言:org.hibernate.dialect.MySQL5Dialect
2.2:ソリッドモデリング:
、JPAの使用を実証するために、適切なエンティティの関係を確立するために、コメントを介して、ソリッドモデリングを実装する方法を示します。
エンティティ間の関係は、下図のように:
ソリッドモデリング図の関係:
セクターカテゴリ:
輸入のjavax.persistence *。;
インポートしたjava.io.Serializable;
@Entity
@Table(名前= "部署")
publicクラス部門はSerializable {実装
@Id
@GeneratedValue(戦略= GenerationType.IDENTITYを)
プライベートロングIDを。
プライベート文字列名;
公衆ロングのgetId(){
IDを返します。
}
パブリックボイドSETID(ロングID){
this.id = ID。
}
パブリック文字列のgetName(){
戻り名。
}
公共ボイドのsetName(文字列名){
this.name =名。
}
}
角色类。
輸入のjavax.persistence *。;
インポートしたjava.io.Serializable;
@Entity
@Table(名前= "役割")
publicクラスの役割はSerializable {実装
@Id
@GeneratedValue(戦略= GenerationType.IDENTITYを)
プライベートロングIDを。
プライベート文字列名;
公衆ロングのgetId(){
IDを返します。
}
公共ボイドSETID(ロングID){
this.id = ID。
}
パブリック文字列のgetName(){
戻り名。
}
公共ボイドのsetName(文字列名){
this.name =名。
}
}
用户类(ゲッターとセッター...):
輸入com.fasterxml.jackson.annotation.JsonBackReference。
輸入org.springframework.format.annotation.DateTimeFormat。
輸入のjavax.persistence *。;
輸入したjava.io.Serializable;
輸入java.util.Date;
輸入はjava.util.List;
@Entity
@Table(名= "ユーザー")
パブリッククラスユーザーシリアライズ{実装
@Id
@GeneratedValue(戦略= GenerationType.IDENTITYを)
プライベートロングIDと、
プライベート文字列名;
@DateTimeFormat(パターン= "YYYY-MM-DD HH:MM:SS")
プライベート日CREATEDATE。
@ManyToOne
@JoinColumn(名前=「やった」)
@JsonBackReference
民間部門の部門。
@ManyToMany(カスケード= {}、フェッチ= FetchType.EAGER)
@JoinTable(名= "USER_ROLE"、joinColumns @JoinColumn = {(名= "USER_ID")}、
inverseJoinColumns @JoinColumnは= {(名= "roles_id")})
;プライベートリストの<role>ロール
新しいテーブルUSER_ROLEここで使用されますユーザーとロールのテーブル-多くの依存性を表現します。
2.3:春のブート構成JPAのテスト環境:
JPAの設定クラスの作成:JpaConfiguration、設定手順は、クラスのコメントを参照してください。
org.springframework.boot.autoconfigure.domain.EntityScanインポート、
インポートorg.springframework.context.annotation.Bean;
インポートorg.springframework.context.annotation.Configuration;
インポートorg.springframework.core.Ordered;
インポートorg.springframework.core .annotation.Order;
インポートorg.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
インポートorg.springframework.data.jpa.repository.config.EnableJpaRepositories;
インポートorg.springframework.transaction.annotation.EnableTransactionManagement;
@Order(Ordered.HIGHEST_PRECEDENCE)/ほとんどのシニアロード順/カスタムコンポーネント、
@の設定//これは、構成クラスであることを示している
@EnableTransactionManagement(proxyTargetClass =真)// JPA物事を有効に管理
@EnableJpaRepositories(basePackages = "com.example.springbootjpa.repository") // JPAリポジトリを起動し、インタフェース・リポジトリの場所を設定
@EntityScan(basePackages = "com.example.springbootjpa.pojo") // エンティティクラス位置
パブリッククラス{JpaConfiguration
/ **
* @description:ここに豆がPersistenceExceptionTranslationPostProcessorオブジェクト宣言するために、なぜ春を言っ公式文書を引用し、説明
(1)コンポーネント春スキャンによってスキャン*
*(2)例外とplatformSpecificキャッチをし、一つとしてそれらを再スロー未チェック例外との春の統一
しかし、あなたはテンプレートを休止状態にHibernate Aコンテキストのセッションを使用していない場合、どのように例外でCAN
? - Search.com場所を取る
翻訳がある:二つの効果を持っている@Repository:
(1):スキャンするために使用されるコンテナ:
(2 ):プラットフォーム固有の例外を捕捉し、未確認の春の例外として、それらを投げ返します。(そのようなキャッチ例外のロールバックなどのトランザクションのための管理、)
あなたが会話ではなく、Hibernateのテンプレートの休止コンテキストセッションのコンテキストを使用している場合は、それが起こったのかに例外が?
まあ、これはこのタイプの構成の役割があります。
@return *
* /
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
)(新しい新しいPersistenceExceptionTranslationPostProcessorを返す;
}
}
3:JPAインタフェース対応作成エンティティ
ユーザインタフェース:
輸入com.example.springbootjpa.pojo.User;
輸入org.springframework.data.jpa.repository.JpaRepository;
輸入org.springframework.stereotype.Repository;
@Repository
パブリックインターフェイスUserRepositoryはJpaRepository <ユーザー、ロング> {延び
ユーザfindByName(文字列名)。
}
部门接口:
輸入com.example.springbootjpa.pojo.Department。
輸入org.springframework.data.jpa.repository.JpaRepository;
輸入org.springframework.stereotype.Repository;
@Repository
パブリックインターフェイスDepartmentRepositoryはJpaRepository <カテゴリーを、ロング>延び{
}
角色接口。
com.example.springbootjpa.pojo.Roleインポート;
インポートorg.springframework.data.jpa.repository.JpaRepository;
インポートorg.springframework.stereotype.Repository;
@Repository
JpaRepository <ロール、ロング> {延びRoleRepositoryパブリックインターフェース
}
4つ:テスト
上記の作業を行った後、次のステップは、テストされます。
輸入com.example.springbootjpa.pojo.Department。
輸入com.example.springbootjpa.pojo.Role。
輸入com.example.springbootjpa.pojo.User。
輸入com.example.springbootjpa.repository.DepartmentRepository。
輸入com.example.springbootjpa.repository.RoleRepository。
輸入com.example.springbootjpa.repository.UserRepository。
輸入org.junit.Assert。
輸入org.junit.Before;
輸入org.junit.Test、
輸入org.junit.runner.RunWith;
輸入org.slf4j.Logger。
輸入org.slf4j.LoggerFactory;
輸入org.springframework.beans.factory.annotation.Autowired;
輸入org.springframework.boot.test.context.SpringBootTest;
輸入org.springframework.data.domain.Page。
輸入org.springframework.data.domain.PageRequest;
輸入org.springframework.data.domain.Pageable;
輸入org.springframework.data.domain.Sort。
輸入org.springframework.test.context.junit4.SpringRunner。
輸入java.util.Date;
輸入はjava.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
パブリッククラスMysqlTest {
プライベート静的ロガーロガー= LoggerFactory.getLogger(MysqlTest.class)。
@Autowired
プライベートUserRepository userRepository。
@Autowired
プライベートDepartmentRepository departmentRepository。
@Autowired
プライベートRoleRepository roleRepository。
@Before
公共ボイドinitData(){
userRepository.deleteAll()。
roleRepository.deleteAll();
departmentRepository.deleteAll();
部門部門=新しい部門();
department.setName( "开发の部");
departmentRepository.save(部署)。
Assert.assertNotNull(department.getId())。
役割役割=新しい役割();
role.setName( "管理者")。
roleRepository.save(役割)。
Assert.assertNotNull(role.getId())。
ユーザのユーザ=新しいユーザー();
user.setName( "ユーザー");
user.setCreateDate(新しいDate());
user.setDepartment(部署)。
一覧<役割>役割= roleRepository.findAll();
Assert.assertNotNull(ロール);
user.setRoles(ロール);
userRepository.save(ユーザ)。
Assert.assertNotNull(user.getId())。
}
@Test
公共ボイドfindPage(){
ページング可能ページング= PageRequest.of(0、10、新たなソート(Sort.Direction.ASC、 "ID"))。
ページ<ユーザー> =ページuserRepository.findAll(ページング可能);
Assert.assertNotNull(ページ)。
用(ユーザーユーザー:page.getContent()){
logger.info( "====ユーザ====ユーザ名:{}、部署名:{}、役割名:{}"、user.getName() 、
user.getDepartment()のgetName()、user.getRoles()を取得(0).getName())。
}
}
@Test
公共ボイドtestFindByName(){
文字列名= "ユーザー";
ユーザーのユーザー= userRepository.findByName(名);
Assert.assertNotNull(ユーザ)。
logger.info(user.getName())。
}
}
结果:
六:の概要
1:なぜJpaRepositoryを継承する必要がありますか?
継承のシステム全体を見て、例えばUserRepositoryするには:
目に見える、JPAリポジトリは通常の動作要件を満たすための方法の富を提供してくれました。
2:実装のカスタムメソッド:
JPA自体、例えば、メソッドの宣言をカスタマイズするためにいくつかのルールを提供する:エンティティ・クラス・メソッドをステッチ、接頭辞としてインターフェイスのキーワードfindBy、readBy、getByを用いては、(最初の文字は大文字)フィールド属性名、およびステッチの一部を選択することができ方法に結合するSQLクエリキーワードは、例えば、ユーザエンティティのために、このようなキーワードを使用することができます。
1.And、如:findByIdAndName(ロングID、文字列の名前)。
2.Or、如:findByIdOrName(ロングID、文字列の名前)。
3.Between、如:findByCreateDateBetween(日スタート、日付の末尾)。
4.LessThan、如:findByCreateDateLessThan(日スタート)。
5.GreaterThan、如:findByCreateDateGreaterThan(日スタート)。
6.IsNull、如:findByNameIsNull();
同等と7.IsNotNull、
8.Like、如:findByNameLike(文字列名)。
9.NotLike:同等と
10.OrderBy、如:findByNameOrderByIdAsc(文字列名)。
11.Not、如:findByNameNot(文字列名)。
12.In、如:findByNameIn(コレクション<文字列>名前リスト)。
13.NotIn、および同等。
参加これらはまだあなたのビジネス要件を満たすことができない上に、あなたはまた、あなたが望む効果を達成するために@queryコメント+ HQLのステートメントを使用してカスタムメソッドを書くことができると言います。
---------------------
免責事項:この記事はCSDNブロガーのオリジナル記事です、CC BY-SA 4.0の著作権契約に従って、「人間の檻」を再現しました元のソースのリンクと、この文を添付してください。
オリジナルリンクします。https://blog.csdn.net/Lee_Ho_/article/details/81014215