在while循环中使用hibernate持续保存数据



我正在读取一个文件,并试图使用jpa将所有数据保存到mysqldb中我的readandLoad方法看起来像这个

@Service
public class ReadLoadLog {
@Autowired
private LogbeanRepository logbeanRepository;
public void readFile(LogBean logBean) throws IOException {
Scanner read = new Scanner(
new File(
"/src/main/resources/access.txt"));
while (read.hasNext()) { //checks if there is a valid token
String string = read.nextLine();
System.out.println(string);
Scanner readFileByLine = new Scanner(string);
while (readFileByLine.hasNext()) { //checks valid token if not then goes out of loop
String[] split = readFileByLine.nextLine().split("\|");
logBean.setDateTime(LocalDateTime.parse(split[0], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
logBean.setIp_address(split[1]);
logBean.setRequest(split[2]);
logBean.setStatus(split[3]);
logBean.setUserAgent(split[4]);
}
logbeanRepository.save(logBean);
}
}
}

我使用命令LineRunner((在spring-boot中运行它。我的数据库中有app.properties中声明的mysql属性。我只得到三个新的ID,但我有一千多个数据,当我点击mysql工作台中的execute select from表时,我得到了不同的数据,但有相同的三个ID 1,2,3所以数据看起来是下载到数据库的,但现在是根据主键排列的,我已经设置了

'1', '2017-01-01 18:25:55', '192.168.97.208', '"GET / HTTP/1.1"', '200', '"Mozilla/5.0 (Linux; Android 7.0; Moto G (4) Build/NPJS25.93-14-8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.116 Mobile Safari/537.36"'
'2', '2017-01-01 18:01:27', '192.168.45.70', '"GET / HTTP/1.1"', '200', '"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"'
'3', '2017-01-01 09:41:38', '192.168.87.47', '"GET / HTTP/1.1"', '200', '"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36"'
@Entity
public class LogBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private LocalDateTime dateTime;
private String ip_address;
private String request;
private String status;
private String userAgent;

这是我的主舱

@SpringBootApplication
public class ParserprojectApplication implements CommandLineRunner   {
@Autowired
LogbeanRepository logbeanRepository;
@Autowired
ReadLoadLog readLoadLog;
private Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
SpringApplication.run(ParserprojectApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
LOGGER.debug("run(args)", args);
LogBean logBean = new LogBean();
readLoadLog.readFile(logBean);
}

我想得到所有被读取的数据,所以我应该得到一千多个具有唯一主键的数据,而不是我得到的数据,但它们都在,1,2,3键

您需要为读取的每一行创建一个LogBean的新实例,否则它将覆盖前一行。

最新更新