1. 程式人生 > >JPA hibernate spring repository pgsql java 工程(二):sql文件導入數據,測試數據

JPA hibernate spring repository pgsql java 工程(二):sql文件導入數據,測試數據

ber tracking evel 主鍵 出現 一個 OS resources pos

使用jpa保存查詢數據都很方便,除了在代碼中加入數據外,可以使用sql進行導入。目前我只會一種方法,把數據集中在一個sql文件中。

而且數據在導入中常常具有先後關系,需要用串行的方式導入。

第一步:配置 需要指定spring boot對數據有create的配置,才能自動加載sql文件

[java] view plain copy
  1. spring.jpa.hibernate.ddl-auto=create


第二步:將對應的.sql文件放入src/main/resources下。我采用的是import.sql文件,如果有多個sql似乎系統會選擇一個文件名排序靠前的文件讀取。

第三步:

在sql寫入執行語句:如參考所示就是pgsql的插入語句。nextval(‘location_seq‘)是指定主鍵的值為對應的自增序列的值。對於jpa中定義了自增

序列作為主鍵,如果采用自定義主鍵值方法插入數據,並且沒對相應的序列做處理,會在系統調用Repository方法進行操作的時候發生錯誤。

出現無法保存,更改的情況!

[sql] view plain copy
    1. insert into location(location_id,location_is_deleted,location_name,location_parent_id,location_position_code,location_town_code,location_level_ll_id) values(nextval(‘location_seq‘),false,‘綏德縣‘,39902,‘610826‘,‘000000‘,3);
    2. insert into location(location_id,location_is_deleted,location_name,location_parent_id,location_position_code,location_town_code,location_level_ll_id) values(nextval(‘location_seq‘),false,‘薛家峁鎮‘,40018,‘610826‘,‘101000‘,4);
    3. insert into location(location_id,location_is_deleted,location_name,location_parent_id,location_position_code,location_town_code,location_level_ll_id) values(nextval(‘location_seq‘),false,‘崔家灣鎮‘,40018,‘610826‘,‘102000‘,4);
    4. insert into location(location_id,location_is_deleted,location_name,location_parent_id,location_position_code,location_town_code,location_level_ll_id) values(nextval(‘location_seq‘),false,‘定仙墕鎮‘,40018,‘610826‘,‘103000‘,4);
    5. insert into location(location_id,location_is_deleted,location_name,location_parent_id,location_position_code,location_town_code,location_level_ll_id) values(nextval(‘location_seq‘),false,‘棗林坪鎮‘,40018,‘610826‘,‘104000‘,4);
    6. insert into location(location_id,location_is_deleted,location_name,location_parent_id,location_position_code,location_town_code,location_level_ll_id) values(nextval(‘location_seq‘),false,‘義合鎮‘,40018,‘610826‘,‘105000‘,4);

JPA hibernate spring repository pgsql java 工程(二):sql文件導入數據,測試數據