问题描述
我是一名初级开发人员,无法完成我的项目.我需要将从 XML 文件接收的数据保存到数据库中.我写了代码,但是我无法将接收到的数据保存到数据库中:
I am a beginner developer and cannot finish my project. I need the data received from the XML file to be saved to the database. I wrote the code, but I can't save the received data to the database:
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
@Service
public class UploadURLServiceImpl implements UploadURLService {
private final FileDTORepository fileDTORepository;
@Autowired
public UploadURLServiceImpl(FileDTORepository fileDTORepository) {
this.fileDTORepository = fileDTORepository;
}
public void store(MultipartFile file) throws IOException {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
SnEntryDTO snEntryDTO = new SnEntryDTO(fileName, file.getContentType(), file.getContentType(), file.getBytes());
fileDTORepository.save(snEntryDTO);
}
@Override
public boolean uploadData(String url) {
try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File("sn.xml"))) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
} catch (IOException e) {
System.out.println(e);
return false;
}
return true;
}
@Override
public void parseSdnFile(String fileName) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(fileName));
doc.getDocumentElement().normalize();
System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
System.out.println("------");
// get <staff>
NodeList list = doc.getElementsByTagName("snEntry");
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getElementsByTagName("uid").item(0).getTextContent();
String lastName = element.getElementsByTagName("lastName").item(0).getTextContent();
String snType = element.getElementsByTagName("snType").item(0).getTextContent();
String programList = element.getElementsByTagName("program").item(0).getTextContent();
System.out.println(id + " " + lastName + " snType " + snType + " programList " + programList);
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
请告诉我.据我了解,我还需要创建一个对象吗?
Tell me please. As I understand it, I still need to create an object?
这部分代码,我需要把它塑造成一个对象吗?
this part of the code, I need to shape it as an object?
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getElementsByTagName("uid").item(0).getTextContent();
String lastName = element.getElementsByTagName("lastName").item(0).getTextContent();
String snType = element.getElementsByTagName("snType").item(0).getTextContent();
String programList = element.getElementsByTagName("program").item(0).getTextContent();
System.out.println(id + " " + lastName + " snType " + snType + " programList " + programList);
推荐答案
您的问题有多种解决方案.最常见的方法是将您的 xml 序列化为实体并将其持久化到数据库中.如我所见,您正在使用 spring-package 中的注释 @Service
.这使得可以使用 Spring-Data JPA 或普通的 Hibernate.我将为您提供 Postgresql 和 Spring-Data 的示例.
Your question has several solutions.The most common way is serealize your xml into entity and persist it to database. As I see, you are use annotation @Service
from spring-package. This makes available to use Spring-Data JPA or plain Hibernate. I'll provide you example with Postgresql and Spring-Data.
将 db 驱动程序和 spring-data-jpa 启动程序添加到您的项目
Add db driver and spring-data-jpa starter to your project
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
将您的数据库凭据提供到文件 application.properties
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
spring.datasource.username=postgres
spring.datasource.password=12345
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
小心 spring.jpa.hibernate.ddl-auto
将休眠模式设置为更改数据库.为避免数据丢失,如果您使用不害怕丢失数据的本地/测试数据库,请使用 create、create-drop.如果您使用数据丢失至关重要的阶段或生产数据库,请使用更新或验证.
Be careful spring.jpa.hibernate.ddl-auto
sets hibernate mode to changing database. To avoid data lose use create, create-drop if you work with your local/test database where you are not afraid of losing data. Use update or validate if you working with stage or production database where data losing will be critical.
创建将持久化到数据库的实体类:
Create Entity class that will be persisted to database:
@Entity
@Table(name = "my_entity")
public class MyEntity {
@Id
@Column(name = "id", length = 16, unique = true, nullable = false)
private UUID uid = randomUuid();
@Column(name = "last_name")
private String lastName;
@Column(name = "sn_type")
private String snType;
@Column(name = "program")
private String program;
// Constructors
// Getters and setters
}
创建简单的存储库
Create simple Repository
@Repository
public interface MyRepository extends CrudRepository<MyEntity, UUID> {
}
在代码中使用创建的存储库
Use created repository in your code
@Autowired
private MyRepository myRepo; //Inject your repo in service
@Override
public void parseSdnFile(String fileName) {
//...
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getElementsByTagName("uid").item(0).getTextContent();
String lastName = element.getElementsByTagName("lastName").item(0).getTextContent();
String snType = element.getElementsByTagName("snType").item(0).getTextContent();
String programList = element.getElementsByTagName("program").item(0).getTextContent();
MyEntity entity = new MyEntity(id, lastName, snType, program); //serealize your data into entity
myRepo.save(entity) //saving to database
System.out.println(id + " " + lastName + " snType " + snType + " programList " + programList);
这篇关于将 XML 文件保存到数据库/Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!