springboot-スタータデータ-JPA依存導入された新しい発想でspringbootアイテム
application.ymlデータベース接続、次の例を設定します。
春: データソース: ドライバー・クラス名:com.mysql.cj.jdbc.Driver ユーザ名:ルート パスワード:123 URLます。jdbc:mysqlの:// localhost /をシェルcharacterEncoding = UTF-8 &userSSL = falseの JPA: ショー-SQL :真
次のようにデータテーブルには、次のとおりです。
作成 表( `product_category`を category_id`は` int型 ない ヌルAUTO_INCREMENT、 `category_name` VARCHAR(64)未 ヌルコメント' カテゴリ名を' 、 category_type`は` int型 ない ヌルコメント' カテゴリ番号を' 、 `create_time` タイムスタンプ されない ヌル デフォルト CURRENT_TIMESTAMPコメント「作成時間」、 `update_time` タイムスタンプ ではありません nullの デフォルトの CURRENT_TIMESTAMP ON アップデート CURRENT_TIMESTAMPのコメント' 修正' 、 プライマリ キー( `category_id`)、 UNIQUE キー` uqe_category_type`( `category_type`) )コメント' カテゴリ表' ;
新しいエンティティクラスProductCategoryは、@Entity注釈を(下のjavax.persistence-APIに依存)クラスを追加します
新しいインターフェイスProductCategoryRepositoryは、JpaRepositoryインターフェース(来春データ-JPA依存)、次のように、一般的な指定を継承しました。
パブリック インターフェース ProductCategoryRepositoryは延び JpaRepository <ProductCategory、整数> { }を
新しいテストクラスProductCategoryRepositoryTest、射出productCategoryRepository、テストクエリメソッド、次のように:
パッケージcom.example.shell.repository。 輸入com.example.shell.dataobject.ProductCategory。 輸入org.junit.Test; 輸入org.junit.runner.RunWith; 輸入org.springframework.beans.factory.annotation.Autowired; 輸入org.springframework.boot.test.context.SpringBootTest; 輸入org.springframework.test.context.junit4.SpringRunner。 輸入はjava.util.List; 輸入java.util.Optional; 輸入静的org.junit.Assert *。 @RunWith(SpringRunner.class) @SpringBootTest パブリッククラスProductCategoryRepositoryTest { @Autowired プライベートProductCategoryRepository productCategoryRepository。 @テスト 公共ボイドfindOneTest(){ オプションの<ProductCategory> productCategory = productCategoryRepository.findById(1)。 System.out.println(productCategory)。 } }
エンティティに指定さ报错ません識別子:
エラー処理:追加@Id注釈(下のjavax-持続-APIに依存する)は、ProductCategoryのエンティティクラスのフィールドを区分しました
試験挿入方法:
@Test 公共 ボイドsaveTest(){ ProductCategory productCategory = 新しいProductCategory()。 productCategory.setCategoryName( "男生最爱" ); productCategory.setCategoryType( 3 )。 productCategoryRepository.save(productCategory)。 }
报错このクラスのIDは、手動で()のセーブを呼び出す前に割り当てる必要があります。
エラー処理:依存性のjavax-持続-APIに区分ProductCategoryエンティティクラスフィールド上@GeneratedValue(戦略= GenerationType.IDENTITYを)を追加します。
ProductCategoryエンティティクラスのフィールドと次のように注釈付き
@Entity @DynamicUpdate パブリック クラスProductCategory { / ** 类目ID。* / @Id @GeneratedValue(戦略 = GenerationType.IDENTITYを) 民間整数区分。 / ** 类目名字。* / プライベート文字列のカテゴリ名。 / ** 类目编号。* / プライベート整数カテゴリタイプ。 プライベート日付CREATETIME。 プライベート日付updateTime。
再び挿入メソッドをテストします。
@Test 公共 ボイドsaveTest(){ オプション <ProductCategory> productCategory = productCategoryRepository.findById(2 )。 productCategory.get()setCategoryType(。 11 ); // ProductCategory productCategory =新しいProductCategory(); // productCategory.setCategoryId(2)。 // productCategory.setCategoryName( "男生最爱"); // productCategory.setCategoryType(3)。 productCategoryRepository.save(productCategory.get())。 }
それは更新を変更しないことが見出された場合、エンティティ・クラスにアノテーションを追加@DynamicUpdate ProductCategory(休止コア - 低級依存)