JPA hibernate spring repository pgsql java 工程(二):sql文件导入数据,测试数据

使用jpa保存查询数据都很方便,除了在代码中加入数据外,可以使用sql进行导入。目前我只会一种方法,把数据集中在一个sql文件中。

而且数据在导入中常常具有先后关系,需要用串行的方式导入。

第一步:配置 需要指定spring boot对数据有create的配置,才能自动加载sql文件

  1. spring.jpa.hibernate.ddl-auto=create  


第二步:将对应的.sql文件放入src/main/resources下。我采用的是import.sql文件,如果有多个sql似乎系统会选择一个文件名排序靠前的文件读取。

第三步:

在sql写入执行语句:如参考所示就是pgsql的插入语句。nextval('location_seq')是指定主键的值为对应的自增序列的值。对于jpa中定义了自增

序列作为主键,如果采用自定义主键值方法插入数据,并且没对相应的序列做处理,会在系统调用Repository方法进行操作的时候发生错误。

出现无法保存,更改的情况!

    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);  
    7.                  
原文地址:https://www.cnblogs.com/Amos-Turing/p/8820585.html