我正在读取文件并尝试使用 jpa 将所有数据保存到 mysql 数据库中 我的 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);
}
}
}
我正在使用 commandLineRunner() 在 spring boot 中运行它 我在我的数据库的 app.properties 中声明了 mysql 属性 我只得到三个新的 ID 但我有超过一千个数据,当我单击执行从表中选择时在我的 mysql workbench 中,我得到了不同的数据,但是三个 ids 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实例,否则它会覆盖之前的。
关于mysql - 在 while 循环中使用 hibernate 持续保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662188/