Reputation: 147
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);
Upvotes: 0
Views: 4543
Reputation: 26
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.
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>
Provide your database credentionals into file 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
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);
Upvotes: 1