Parsing complex XML and inserting databases using XStream (ii)

Source: Internet
Author: User
Tags uuid

Labeling the Yellow place: I need to deepen my study!!!

I write is WebService, at present the specific steps to write WebService I am not clear, finishing small knowledge began to organize webservice!

Parsing for XML in the following format

<?xml version= "1.0" encoding= "UTF-8"?>

<Data>

<Bean>

<A>a</A>

<B>b</B>

<C>1</C>

<A>a</A>

<B>b</B>

<C>2</C>

</Bean>

<D>

<E></E>

</D>

</Data>

Project: We parse 10 beans at once, here, for example two, with 10 beans in data.

We need to put a, B, C data into the database, here, the boss said to use a one-to-many way to store. In our project we use Hibernate to generate tables automatically . For example, I follow the project, of course, it is easier to build a table and establish a relationship between the two tables. Establish a one-to-many relationship.

(1), import dependence, I am oracle,mysql to switch back and forth, and sometimes remote connection to the boss of the database, I use MySQL. Below I use the Oracle database.

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>

<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.9</version>
</dependency>
<!--
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
-
In the project we also introduced the AXSI2, looking back deeply, first put a dependency. The demo I wrote didn't use this.
(2), configuration file application.properties
Of course, now with the Yaml file is more intuitive ~ Another time to try, more practice, I will now, but the code will not knock, all is paste, this is a bad habit!
#配置端口号
server.port=8080

#配置数据源

#mysql
#spring. Datasource.driver-class-name=com.mysql.jdbc.driver
#spring. datasource.url=jdbc:mysql://localhost:3306/test
#spring. Datasource.username=root
#spring. Datasource.password=root

#oracle
Spring.datasource.driver-class-name=oracle.jdbc.driver.oracledriver
Spring.datasource.url=jdbc:oracle:thin: @localhost: 1521:ORCL
Spring.datasource.username=root
Spring.datasource.password=root
#配置JPA
Spring.jpa.database=oracle
#spring. Jpa.database=mysql
Spring.jpa.show-sql=true
Spring.jpa.generate-ddl=true
Spring.jpa.hibernate.ddl-auto=create
at present Show-sql, GENERATE-DDL, ddl-auto worthy meaning I still do not understand, but when we create the table structure must use create, fill in the data after the change to none, otherwise the table new Oh, the data is gone!

(3), create five classes: The main basis is to divide the XML into three parts for inserting the database and parsing the XML into a Java object, and then aggregating all the tags together into one class.
First Class : use it to convert the contents of a bean to a Java object
Import java.util.List;

@Component
@Data
public class Demo {

Private list<string> A;

Private list<string> B;
   
}
Here, remember to add the annotation @component, or you will get an error:

Unable to instantiate Deployer Org.apache.axis2.deployment.ServiceDeployer; See Debug logs for more details

WORKAROUND:the model layer's key class does not add annotations.
Cause the bean to fail to inject, add a bit on the line. and the table corresponding to write @entity, not should write @component.

Problem transfer: https://segmentfault.com/q/1010000005957988/a-1020000005958530

a second to third class . The contents of the bean correspond to two tables.
@Entity
@Data
@Table (name = "Abtable")
@GenericGenerator (name = "Jpa-uuid", strategy = "uuid")
public class Abentity {

@Id
@GeneratedValue (generator = "Jpa-uuid")
@Column (name = "ab_id", length = 32)
Private String ab_id;
@Column (name = "A", length = 200)
Private String A;

@Column (name = "B", length = 200)
Private String B;

@OneToMany (Cascade={cascadetype.all}) //Specify a one-to-many relationship, Cascade
@JoinColumn (name= "ab_id", referencedcolumnname = "ab_id")
Private set<centity> emp = new hashset<centity> ();
}
Import Lombok. Data;
Import Org.hibernate.annotations.GenericGenerator;

Import javax.persistence.*;

@Entity
@Data
@Table (name = "CTable")
@GenericGenerator (name = "Jpa-uuid", strategy = "uuid")
public class Centity {

@Id
@GeneratedValue (generator = "Jpa-uuid")
@Column (name = "c_id", length = 32)
Private String c_id;

@Column (name = "C", length = 200)
Private String C;

@Column (name = "ab_id", length = 32)
Private String ab_id;
}
class Fourth: handling DF two labels.
Import Lombok. Getter;
Import Lombok. Setter;
Import Lombok. ToString;

@ToString
@Setter
@Getter
public class dlable{

Private String E;

}
class Fifth: multiple identical labels are encapsulated into a collection, with multiple beans, using the collection store.
Import com.thoughtworks.xstream.annotations.XStreamImplicit;
Import Lombok. Getter;
Import Lombok. Setter;
Import Lombok. ToString;

Import java.util.List;

@ToString
@Setter
@Getter
public class Demoresult {

/**
* multiple identical tags encapsulated into one collection
*/
@XStreamImplicit (itemfieldname = "BEAN")
Private list<demo> BEAN;
Private Dlable D;
}
Then write a class to set the XStream
Protected XStream Getxstream (class data, class Bean) {
XStream XStream = new XStream () {
@Override
Protected Mapperwrapper Wrapmapper (Mapperwrapper next) {
return new Mapperwrapper (next) {
@Override
public boolean shouldserializemember (Class Definedin, String fieldName) {
Ignore attributes that are not
if (Definedin = = Object.class) {
return false;
}
Return Super.shouldserializemember (Definedin, fieldName);
}
};
}
};
Xstream.alias ("Data", data);
Xstream.alias ("Bean", bean);
Xstream.addimplicitcollection (Placepoliceresult.class, "BEAN");
Xstream.alias ("D, Dlable.class);
Xstream.alias ("A", String.class);
Xstream.addimplicitcollection (Demo.class, "A");
Xstream.alias ("B", String.class);
Xstream.addimplicitcollection (Demo.class, "B");
Xstream.alias ("C", String.class);
Xstream.addimplicitcollection (Demo.class, "C");
return xStream;
}

/**
* Encapsulate XML results into Java objects and insert the database
*
* @throws Exception
*/
Here we use @slf4j to output the log.
Parameter description:
XStream Stream:

String text:
String Text = "<?xml version=" 1.0 "encoding=" UTF-8 "? ><data><bean><a>a1</a><b>b1 </B><C>11</C><A>a1</A><B>b1</B><C>22</C></Bean> <bean><a>a2</a><b>b2</b><c>33</c><a>a2</a><b>b2 </B><C>44</C></Bean><D><E></E></D></Data> ";
String Name:
String name = Demo.class.getSimpleName ();
@Autowired
Private Caseinfodao Caseinfodao;
private void Xmltobeandemo (XStream stream, string text, string name) {

Object obj = stream.fromxml (text);
if (obj! = null) {
list<map<string, object>> reslist = new arraylist<> ();
map<string, object> resmap = new hashmap<> (16);
list<centity> morelist = new arraylist<centity> ();

try {
if (obj instanceof Demoresult) {
Demoresult result = (demoresult) obj;
list<demo> list = Result.getbean ();
Traverse one's relationship
for (int i = 0; i < list.size (); i++) {
Morelist = new arraylist<centity> ();
Resmap = new hashmap<> (16);
Demo demo= List.get (i);
Abentity abentity = new abentity ();
Abentity.seta (Demo.geta (). Get (0));
Abentity.setb (Demo.getb (). Get (0));

Resmap.put ("Abentity", abentity);
Traverse a multiple relationship
for (int j = 0; J < Demo.geta (). Size (); j + +) {
Centity centity = new centity ();
Centity.setc (Demo.getc (). Get (j));

Morelist.add (centity);
}
Resmap.put ("Morelist", morelist);
Reslist.add (RESMAP);

}
Log.info ("Parse complete ... ");
}
} catch (Exception e) {
Log.info ("error message, {}", E.getmessage ());
}
Caseinfodao.batchinsertplace (reslist);
Log.info ("Data addition complete");
}
Log.info ("No data returned, {}", name);

}

Set to Insert the returned Java object into the database :
@Slf4j
@Repository
public class Caseinfodao {

/**
* JPA Entity Management
*/
@PersistenceContext
Private Entitymanager Entitymanager;
@Transactional (rollbackfor = exception.class)
public void Batchinsertplace (list<map<string,object>> reslist) {
Map<string,object> map;
for (int i = 0; i < reslist.size (); i++) {
Map = Reslist.get (i);
Abentity abentity = (abentity) map.get ("abentity");
Add entity to session cache
Entitymanager.persist (abentity);
Log.info ("ab_id:{}", abentity.getab_id ());
List<centity> morelist= (list<centity>) map.get ("Morelist");
for (int j = 0; J < Morelist.size (); j + +) {
Centity centity = Morelist.get (j);
CENTITY.SETAB_ID (abentity.getab_id ());
Log.info ("centity:{}", centity.tostring ());
Entitymanager.persist (centity);
}
}

Entitymanager.flush ();
Log.info ("Update data Success");
Empty cache
Entitymanager.clear ();
}
}

Parse the XML and insert the database:

String text:
String Text = "<?xml version=" 1.0 "encoding=" UTF-8 "? ><data><bean><a>a1</a><b>b1 </B><C>11</C><A>a1</A><B>b1</B><C>22</C></Bean> <bean><a>a2</a><b>b2</b><c>33</c><a>a2</a><b>b2 </B><C>44</C></Bean><D><E></E></D></Data> ";
String Name:
String name = Demo.class.getSimpleName ();
Xmltobeandemo (stream, text,name);
Attention:
I have not tested the above, a few days feedback.
Reflection:
Work time to write blog is not correct, to use more time to write, summary, more knock more practice! Blogging time wasted a little too long! Come on!

Parsing complex XML and inserting databases using XStream (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.