Sunday, April 27, 2008

What To Do For Someone Aspirating

JPA - the relationship one-to-many and many-to-one

In this article I would like to present the mapping of a one-to-many and the twin her a many-to-one. In this type of relationship we can distinguish between the entities being a parent - on one side of the relationship and any number of sub-entities - the other side of the relationship.
This relationship is so special that, in the relational world of its implementation is the starting point to implement a one-to-one and many-to-many.
distinguish between the following options for the relationship of this type:
- two-way relationship jeden-do-wielu/wiele-do-jednego: the parent has a collection of references to child objects that have reference to the parent;
- unidirectional one-to-many: the parent has a collection of references to child objects;
- one-way many-to-one: a child has a reference to the parent;

first Example - an area traditionally

problem for the auxiliary will use very complex example. And here's the object model:

is a system of two classes Person and Contact . The latter represents the contact details such as phone number or email address. An aggregates completely Kontatk 's (bond-type composition), which also has reflected the supremacy of one being to another. Of course, the relationship in question also concerns the type of bond association and normal aggregation, but chose the theme because the relational model, this will involve an additional reduction not null. In the relational world
exemplary model will be the following:

second Two-way relationship wiele-do-jednego/jeden-do-wielu

The object model in which there are connections between objects, very often we expect the possibility of two-way "navigation" between related objects. In our example, this means that we expect to upgrade the facility Person to its related objects Contact and vice versa.
To meet these requirements we must appropriately map these two classes.
2.1. Mapping class Contact
Entity Contact the owner of a link, because it has a foreign key to entity person.
 @ Entity @ Table (name = "contact") public class Contact {... private Person person; @ ManyToOne (optional = false) @ JoinColumn (name = "oso_id") / / default column to be called osoba_oso_id getOsoba public Person () {return person;}} 
JPA requires only that a child in the facility to mark a reference to the parent with the annotation @ ManyToOne . But I also overwrite some default setting. And so:
- set the attribute optional = false this annotation, which means that the reference to person must be set, which will be expressed during the automatic generation of database schema by adding NOT NULL constraints;
; - Through the @ JoinColumn annotation set the column name, which is a foreign key to table Person . By default, that was used in a column named [nazwa_tabeli_nadrzędnej] _ [nazwa_klucza_głównego_tabeli_nadrzędnej]
2.2. Mapping the Person class
 @ Entity @ Table (name = "person") public class Person {... private List contacts \u0026lt;Contact>; @ OneToMany (cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, mappedBy = "person") @ Cascade ({org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) public List \u0026lt;Contact> getKontakty ( ) {return contacts;} public void dodajKontakt (Contact contact) {if (null == contact) {contacts = new ArrayList \u0026lt;Contact> ();} kontakt.setOsoba (this); kontakty.add (contact);}} 
For the parent is required to determine the reference collections of child objects with entries @ OneToMany . Because this is a two-way binding, and mapping to the relational model has already been defined in the class Contact , it should express this by attribute mappedBy this annotation, which should be assigned a value that is the name of references (in the sub-object) to obietku parent. The attribute mappedBy be used not only to avoid having a double set of physical parameters of the relational model, but mainly because, to avoid duplicate records in the database. Attribute mappedBy is unavailable for the annotation @ ManyToOne .
Besides mapping is equipped with the parameters defining the cascade action, but they write some more in the discussion of preservation and disposal facilities.
2.3. Consolidation of objects in the database objects can
Fixation be implemented in a separable or cascading. Scheme of distributive
fixation of objects in our example would be as follows. First, create and save object Person: Person
 o = new Person (); em.persist (o); 
Then, create, relationship with the person and write the object Contact: Contact
 k = new Contact ("tel "," +48123124234 "); o.dodajKontakt (k); em.persist (k); 
Here I will note that the method dodajKontakt adds a contact to the collection contacts in the building of and sets the reference person in the building k .
If you want to fix the object Contact in the next transaction, then he must set the appropriate references to the object person. Assuming that we have only the id of the person that can do the following: Contact
 k = new Contact ("GG", "124234") = Person with em.getReference (Osoba.class, osobaId); k.setOsoba ( o); em.persist (k); 
I'd be manually create an instance person and setting the id field not work.

fixation cascade of objects. Often the need for fixation of the whole tree of objects, such as a parent - the root of the tree ( person) and the related child objects ( Contact ). JPA allows you to do this by performing operations on the parent object fixation. At the same time, be sure to set the cascade attribute the CascadeType.PERSIST in mapping - as was done in the mapping class person for property contacts.
cascading effect fusing of objects can also be set on the side of the child, but it appears to be very practical.
2.4. Removing objects from DB
As well as consolidating and removing objects can be separated or cascaded.
Cascading delete objects is analogous to the cascade fixation. Ie. performing surgery to remove the main object - the root of the tree of objects, are automatically removed the related child objects. Here you should be sure to set the cascade attribute the CascadeType.REMOVE in mapping - as was done in the mapping class person for property contacts. Implementation of the JPA should be removed before removing the child objects parent, to avoid infringement of database constraints. However, the removal of these may not be optimal. For example hibernate'owa implementation removes each object separately after its id, while a better solution would be to remove all objects from one group one question referring to the foreign key to being the parent. Activities
cascade delete objects can not be set on the side of the child.
Following the removal of the child objects in the relationship can be used to extend jeden-do-wielu/wiele-do-jednego hibernate'owe - Cascading effects delete-orphan. However, when in the mapping of a parent class, a collection of references to child objects denote endorsement @ Cascade ({org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) , after removing an object from the collection and consolidation of the parent object, removed object from the collection will also be removed from the database.
 o.getKontakty (). Remove (k); em.persist (o); 
When using this extension should be remembered that for the parent at least once settled, can not be around with the collection of child objects, say a new instance of ArrayList , and the attempt to consolidate such a facility simply fails. This is because hibernate uses its own implementations of the collection - persistence collections, which help in the implementation of the delete-orphan.

Removing separable. No, no problem to delete the child objects in a manner separable. Moreover, without the use of a series of extensions hibernate'owego delete-orphan, is the only way to get rid of the database in a single child object.
But to dispense with a series of disposal for the parent objects is not very attractive. If the database is assumed restriction that the foreign key to the parent entity can not be empty, such an operation at all will fail. Generally what happens to this further depends on the settings of cascading on the database.

third One-way many-to-one

compared to two-way relationship wiele-do-jednego/jeden-do-wielu, class Contact and its mapping remains unchanged, but with class person will be removed the link to the class Contact . This approach prevents
of cascading configuration (other than those specified in the schema of the database) wyzwalanymi by operations on the object person. Alternatively, you can specify action cascade triggered by operations on the object Contact .
In this example, I have a lot of one-way-to-one does not make much practical use.

4th Unidirectional one-to-many

compared to two-way relationship wiele-do-jednego/jeden-do-wielu, the class will disappear Contact link to the class person, while the class Person and mapping changes as follows : @ Entity
 @ Table (name = "person") public class Person {... private List contacts \u0026lt;Contact>; @ OneToMany (cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) @ Cascade ({org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @ JoinColumn (name = "oso_id" Nullable = false) public List \u0026lt;Contact> getKontakty () {return contacts;} public void dodajKontakt (Contact contact) {if (null == contact) {contacts = new ArrayList \u0026lt;Contact> ();} kontakty.add (contact);}} 
As you can see has changed the method dodajKontakt , which no longer contains the user object binding contact with the object Person . But most importantly, changed a little bit mapping. Since the class Contact does not contain been mapping this relationship is:
- disappeared attribute definition mappedBy the annotation @ OneToMany ;
- to map the property contacts been added @ JoinColumn annotation , which like the Contact class is used to specify the column in the entity Contact , which is a foreign key to the Person entity . Otherwise, by default, the table would be used an intermediary, like a many-to-many, called [nazwa_tabeli_nadrzędnej] _ [nazwa_tabeli_podrzędnej] which would include two foreign keys to the tables with the following schema names [tablename] _ [nazwa_klucza_głównego] .

For example, I have presented the use of a unidirectional one-to-many is quite a reasonable approach. The only thing that is lost is the ability to write objects Contact whatever object person. Has also lost the ability to define a cascading action from the object Contact , but to take advantage of this possibility in this case, and so there is a reasonable condition.

5th Support Resources

Example Source Files
JPA - first steps
Hibernate Annotations - 2.2.5. Mapping entity bean Associations / relationships
2.4. Hibernate Annotation Extensions
JPA specification

Monday, April 14, 2008

How To Do Makeup Like Tracy Turnblad

JPA - modeling inheritance

inheritance relationship is appropriate only for the object model and a fashion does not exist in the relational model. Therefore, approaches have been developed to represent the relational models of inheritance:
- one table per concrete class (Single table per Concrete Class)
- one table per class hierarchy (Single table per Class Hierarchy),
- join subclass (Joined Subclass).
JPA specification, using the @ Inheritance annotation , enables the use of each of these three strategies represent inheritance.

Example -

problem area for the purposes of this article will use the following data model: It is a simple hierarchy of classes, from which the abstract class person is the parent class, and class OsobaPrawna and OsobaFizyczna inherit from it.

One table per class concrete (Single table per Concrete Class)

Acc. this strategy would present the relational model is as follows: This approach provides that for each class of concrete will fall a table in the relational model. In our case we will set up tables for classes and OsobaPrawna OsobaFizyczna . At the same time, these tables will also include a column representing the inherited attributes. Here it should be noted that it is not possible to override the mapping of inherited attributes - will not work @ AttributeOverride endorsement (s) .

class An not explicitly mapped in the relational model. This feature makes the polymorphic associations (ie, a general reference to being person, not a specific kind of people) are not possible, and polymorphic queries very difficult (in queries using the union, or dissected by a separate query for each subclasses).

Below code snippets class definitions mapping: @ Entity
 @ Inheritance (strategy = InheritanceType.TABLE_PER_CLASS) public abstract class Person {... } @ Entity 
 (name = "osoba_prawna") public class Person {OsobaPrawna extends ... } 
 @ Entity (name = "osoba_fizyczna") public class Person {OsobaFizyczna extends ... } 
full source in the form of a project can be downloaded maven'owego here.

One table per class hierarchy (Single table per Class Hierarchy)

Acc. this strategy would present the relational model is as follows: In this approach, a hierarchy of classes is only one table. In our case, this means that all classes (Person , OsobaPrawna , OsobaFizyczna ) will be represented by only one table. This table is in addition to the columns representing attributes of these classes, will have a column flag (discriminator) - os_typ , which will determine which class is given a particular record. It is not necessary to define the class attribute representing discriminator'a, but once this is done, then the mapping of this attribute must be switched off the option of recording and updating of this value, since it can not be changed manually.

The solution does not have the disadvantages associated with polymorphism, which had the previous approach. However, has another drawback in the ability to define constraints of columns (above all not null ) specific to particular classes. For example, you can not enforce that the column mapping OsobaPrawna.regon could not accept blank values, since this condition does not meet any record representing the object OsobaFizyczna .

Below code snippets from the mapping class definition: @
 Entity (name = "person") @ Inheritance (strategy = InheritanceType.SINGLE_TABLE) @ DiscriminatorColumn (name = "os_typ") public abstract class Person {... } @ Entity 
 @ DiscriminatorValue (value = "IP") public class Person {OsobaPrawna extends ... } @ Entity 
 @ DiscriminatorValue (value = "OF") public class Person {OsobaFizyczna extends ... } 
full source in the form of a project can be downloaded maven'owego here. Merge

subclass (Joined Subclass)

Acc. this strategy would present the relational model is as follows: In this approach, each class (even abstract) in the relational model, its representation in the form of a table. This means that a particular object will be stored in the table in part an abstract class and partly in the table a specific class. In our example, the object attributes OsobaPrawna will be stored in a table OsobaPrawna as well as the inherited attributes in the table Person. Being
inheriting must have recourse to the entity from which it inherits. The role of the appeal may be common master key. And so the row in the table Klast OsobaPrawna will have a primary key equal in value to a key line in the table class Person .

This approach does not have the disadvantages of previous solutions. In addition, the relational model is characterized by a higher degree of standardization in relation to competitive solutions. What it may also be a disadvantage of this strategy, because a higher degree of standardization means that the data are scattered in more tables, which increases the complexity of queries and to some extent the time of their execution.

Below code snippets from the mapping class definition: @
 Entity (name = "person") @ Inheritance (strategy = InheritanceType.JOINED) public abstract class Person {... } @ Entity 
 (name = "osoba_prawna") @ PrimaryKeyJoinColumn (name = "op_id") public class Person {OsobaPrawna extends ... } @ Entity 
 (name = "osoba_fizyczna") @ PrimaryKeyJoinColumn (name = "of_id") public class Person {OsobaFizyczna extends ... } 
Complete source as maven'owego project can be downloaded here .

Inheritance is not a class of entities

JPA specification provides for two ways of behavior in the case of inheritance from a non-class entities.
first option - the base class is not annotated @ MappedSuperclass . In this case, the inherited attributes are fleeting and will not be stored in the database after the operation the fixation object.
second option - the base class is marked with a note @ MappedSuperclass . Then the attributes are inherited according to fixed. mappings defined in this base class. At the same time it is possible to overwrite these mappings by using the annotation @ AttributeOverride (s) . In my opinion
mapped class parents are an interesting option and can be used even in the definition of base class of all entities that will contain the attributes that contain information about changes made to the entity.
Below is an example of the mapped class:
 MappedSuperclass public class @ {private String EncjaAudytowalna uzytkownikModyfikujacy; private Date dataModyfikacji; @ Column (name = "audyt_uzytkownik") public String getUzytkownikModyfikujacy () {return uzytkownikModyfikujacy;} public void setUzytkownikModyfikujacy (String uzytkownikModyfikujacy)  {
this.uzytkownikModyfikujacy = uzytkownikModyfikujacy;
}

@Column(name="audyt_data")
@Temporal(value=TemporalType.TIMESTAMP)
public Date getDataModyfikacji() {
return dataModyfikacji;
}
public void setDataModyfikacji(Date dataModyfikacji) {
this.dataModyfikacji = dataModyfikacji;
}
}

 @Entity
@AttributeOverride(name="uzytkownikModyfikujacy", column=@Column(name="uz_au_um"))
public class Uzytkownik extends EncjaAudytowalna {
private Long id;
private String name;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;} @ Column (name = "name") public String getName () {return name;} public void setName (String name) {this.name = name;}}

Resources

Hibernate Annotations - 2.2.4. Mapping inheritance
JPA specification

Sunday, April 13, 2008

Myammee Love Money Nackt

XML Serialization - save java.util.Date and enumeration values \u200b\u200b

This article is a continuation thread from the article TestNG - test data from an XML file to use standard (J2SE), XML serialization of objects schemy for the preparation of test data. This article will treat a data entry type java.util.Date and enumerated type - enumeration.
As a reminder in this If it's not about serialization of objects from java, but a manual preparation of XML files containing zserializowane objects that are zdeserializowane using a standard mechanism - java.beans.XMLDecoder and will then be used as input for the unit tests.

However, even when serializing an object from the levels of Java, which has a field of type java.util.Date and the second about the type of enumeration, we obtain the effect of far been disappointing, which certainly do not want to emulate.
field enumeration of the type in general will not be saved. The box with the dates will be saved, but as the number of milliseconds since January 1, 1970. Surely this is not a convenient form for humans, Ana read, let alone to write. In any event, java.beans.XMLEncoder zserializuje java.util.Date as follows:
 \u0026lt;void property="birthDate"> \u0026lt;object class="java.util.Date"> \u0026lt; ; long> 439254000000 \u0026lt;/ long> \u0026lt;/ object> \u0026lt;/ void> 
Not so ... that's pretty logical, because it is the only one not "condemned" the way to set the date which provides an interface java.util.Date.
Normally (in Java), if I had to get the date from a string, I would have benefited from java.text.SimpleDateFormat. But how to use it in that this XML ... now I've included:
 \u0026lt;void id="sdf" class="java.text.SimpleDateFormat"> \u0026lt;string> yyyy-MM-dd \u0026lt;/ string> \u0026lt;void id="date0" method="parse"> ; \u0026lt;string> 1983-12-03 \u0026lt;/ string> \u0026lt;/ void> \u0026lt;/ void> ... \u0026lt;object class="pl.dwalczak.Osoba"> ... \u0026lt;void property="dataUrodzin"> \u0026lt;object idref="date0"/> \u0026lt;/ void> ... \u0026lt;/ Object> 
first part of the structure (a marker of void id = "sdf" ), a declaration, which corresponds in Java:
 java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat ("yyyy-MM -dd "); java.util.Date sdf.parse date0 = (" 1983-12-03 "); 
She does not define any zserializowanego object, and only variables that can be used when defining zserializowanych obietków. Can be placed in the main element, or directly in zserializowanym object.
The second part of the structure (the marker object ) defines an object of type pl.dwalczak.Osoba , which sets the field dataUrodzin predefined variable date0 .

Returning to the enumerated type.
Suppose that the class has pl.dwalczak.Osoba typOsoby field of type pl.dwalczak.TypOsoby which is enumeracjom:
 package pl.dwalczak; {public enum TypOsoby OsobaFizyczna, OsobaPrawna;} 
then set the field typOsoby for pl.dwalczak.Osoba object might look like this:
 \u0026lt;void property="type"> \u0026lt;object class="com.dwalczak.TypOsoby" field="OsobaFizyczna"/> \u0026lt;/ void> 
Or this:
 \u0026lt;void property="type"> ; \u0026lt;object class="com.dwalczak.TypOsoby" method="valueOf"> \u0026lt;string> OsobaPrawna \u0026lt;/ string> \u0026lt;/ object> \u0026lt;/ void> 

Summary

While the problem of serializing a value of type The enumeration does not specifically reduce the attractiveness of the standard format of XML serialization of objects in J2SE, as a general format for recording test data manually because it would be in pretty decent shape. This is a problem with the date actually reduces the attractiveness, because the formula in the record of its "human" character is a little too long and complicated. Still, I think that the use of this format may be less time consuming than designing and writing your own code, it deserializującego objects.

Resources Long-Term Persistence of JavaBeans Components: XML Schema
Malenkova Sergey's Blog - How to encode Type-Safe enums?

Monday, April 7, 2008

Fifth Disease In Blacks

Testing EJB3 beans with

After the first skirmishes of the JPA is time for gain first experiences in the writing of EJB3 beans. But first I wanted to explore issues related to testing of these grains. In previous versions of EJB testing was pretty hard, because as we all know the grain, to work had to be embedded in the EJB container, which were only available in application servers. As for me, this is too complicated and too time-consuming process of testing. Unfortunately, EJB3 beans also need to run them in an EJB container.

Wbudowywalny EJB3 container

For some time, make JBoss EJB3 container wbudowywalny . It is a container that can be run outside the application server. At present, the container has indeed some limitations, but as long as access to all services required by me I'm not going to be too bothered;)
However koncepcja wbudowywalnego EJB3 container lets you create, fast and easy to use unit testing environment for EJB3 beans. EJB3 test environment

When creating a unit test environment for the beans will use the said wbudowywalny EJB3 container.
To run is required in order to reach classpath'a were (in addition to the implementation of the container and the dependent libraries), the following configuration files: embedded-jboss-beans.xml , ejb3-interceptors -aop.xml , jndi.properties , default.persistence.properties .
In order to avoid placing these files in all subprojects EJB modules, forming a corporate application, and determination in each of them depending on the EJB3 container jar'ów built, I decided to create a dedicated project maven'a. Draft Environmental unit testing EJB will include these configuration files, which are defined according to jar'ów implement container and test base class for tests individual grains.
Here's implementation unit test base class: package
 pl.dwalczak.ejb3testenv; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.log4j.Logger; import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap imports, org.jboss.ejb3.embedded.EJB3StandaloneDeployer; org.testng.annotations.AfterSuite import, import org.testng.annotations.BeforeSuite; abstract public class {private static Ejb3Test final Logger LOG = Logger.getLogger (Ejb3Test.class); private static final String LOCAL_POSTFIX = "/ local"; private InitialContext InitialContext; private EJB3StandaloneDeployer deployer; @ BeforeSuite startupEjb3 public void ()  {
EJB3StandaloneBootstrap.boot(null);
EJB3StandaloneBootstrap.scanClasspath();

deployer = EJB3StandaloneBootstrap.createDeployer();
try {
deployer.setKernel(EJB3StandaloneBootstrap.getKernel());
deployer.getArchivesByResource().add("META-INF/ejb-jar.xml");
deployer.create();
deployer.start();
initialContext = new InitialContext();
} catch (NamingException e) {
LOG.error("Can't initialize context.", e);
throw new RuntimeException(e);
} catch (Exception e) {
LOG.error("Deployer error.", e);
throw new RuntimeException(e);
}
}

@AfterSuite
public void shutdownEjb3() {
if (null != initialContext) {
try {
initialContext.close();
} catch (NamingException e) {
LOG.error("Can't close context.", e);
}
}
if (null != deployer) {
try {
deployer.stop();
deployer.destroy();
} catch (Exception e) {
LOG.error("Can't close deployer.", e);
}
}
EJB3StandaloneBootstrap.shutdown();
}

@SuppressWarnings(value = "unchecked")
public T lookup(String beanName, Class businessInterface) {
T result = null;
try {
result = (T) initialContext.lookup(beanName + LOCAL_POSTFIX);
} catch (NamingException e) {
LOG.error("Can't bean lookup: "+ beanName, e) throw new RuntimeException (e);} return result;}}
This adaptation of the new EJB module in maven'ie will be to add the dependencies for this project (the scope set to test).

It should be noted that a more complex enterprise application is likely to be required specially tailored project test environment. But I think I have prepared a draft of that environment is a good starting point.

Testing EJB3 beans - such

In my example, we have dealing with a very simple seeds:
 pl.dwalczak.ejb3pg1 package; javax.ejb.Stateless import, import org.apache.log4j.Logger; @ Stateless public class Calculator implements CalculatorBean {private static Logger LOG = Logger.getLogger (CalculatorBean.class) public int add ( int x, int y) {LOG.debug ("add (" + x + "" + y + ")"); return x + y;}} 
business interface: package
 pl.dwalczak.ejb3pg1; public interface Calculator {int add (int x, int y);} 
After adding the project according to the test environment, you can write a unit test for this grain, which might look as follows:
 pl.dwalczak.ejb3pg1 package imports, org.testng.Assert; org.testng.annotations.Test import, import pl.dwalczak.ejb3testenv.Ejb3Test; public class extends CalculatorTest Ejb3Test {@ Test public void testAdd () {Calculator calculator = lookup ("CalculatorBean" Calculator.class) calculator.add int sum = (2, 2); Assert.assertEquals (sum, 4);}} 
is just one more question. Do you need to add the EJB module configuration file META-INF/ejb-jar.xml, even if you do not need to configure anything in it. It is simply necessary that the container used for grain zaczytał EJB3 class even though they are configured using annotations.

Resources

Example Source Files Source files
ejb3-test-env
EJB 3.0 Embeddable
JSR-000220 Enterprise JavaBeans 3.0
JavaTM Platform, Enterprise Edition, v 5.0 API Specifications

Tuesday, April 1, 2008

Can You Get Hives On Ankles

using TestNG TestNG - test data from XML files

Article Writing TestNG - provider of data remembered a mini framework'u to perform unit tests, which came to me one day to write. I had to write it, not because the project was not known jUnit) but because jUnit in some cases not much help. In practical terms, the situation when many tests have the same algorithm, and differ in test data (sometimes they are quite large data sets).
my opinion in this case, we separately manage the data and test algorithms, and place it in different files. Then there is the possibility that the test data prepared by someone other than the test algorithms, no need to recompile the test when the data has changed, and no easier to avoid problems with the encoding of input data.

DataProvider in TestNG does not directly zaczytywania test data from XML files. But as it turned out, doing it yourself is not difficult, and most importantly does not require significant coding effort. Simply use the specifications provided by the J2SE XML serialization JavaBean'ów.
Schema serialization is relatively understandable to people, and most importantly is very flexible. This schema allows to save any number of custom objects. In addition, you can easily generate a sample input file for testing by zserializowanie crafted in the code sample data.

Below is an example of the contents of the XML file with test data:
 \u0026lt;? Xml version = "1.0"  encoding="UTF-8" ?>
<java version="1.5.0" class="java.beans.XMLDecoder">
<array>
<string>test1</string>
<object class="pl.dwalczak.testngdp1.User">
<void property="nickName">
<string>heniek</string>
</void>
<void property="address">
<object class="pl.dwalczak.testngdp1.Address"
id="addr1">
<void property="city">
<string>Poznań</string>
</void>
<void property="postcode">
<string>11-111</string>
</void>
<void property="street">
<string>Jadwigi</string>
</void>
<void property="number">
<string>11a/3</string>
</void>
</object>
</void>
<void property="mailingAddress">
<object idref="addr1" />
</void>
</object>
</array>
<array>
<string>test2</string>
<object class="pl.dwalczak.testngdp1.User">
<void property="nickName">
<string>maniek</string>
</void>
<void property="address">
<object idref="addr1" />
</void>
<void property="mailingAddress">
<object IDREF = "Addr1" /> \u0026lt;/ void> \u0026lt;/ object> \u0026lt;/ array> \u0026lt;/ java>
However, implementation TestNG'owego data provider that uses this XML file might look like this: package com
 . dwalczak.testngdp1; java.beans.XMLDecoder import, import java.io.FileInputStream; import java.util.ArrayList; org.testng.annotations.DataProvider import, import org.testng.annotations.Test; @ Test public class SimpleTest { @ DataProvider (name = "dp") public Object [] [] createData () {ArrayList result = new \u0026lt;Object[]>  ArrayList<Object[]>();
XMLDecoder dec = null;
try {
dec = new XMLDecoder(new FileInputStream("testData.xml"));
while (true) {
Object o = dec.readObject();
result.add((Object[]) o);
}
} catch (ArrayIndexOutOfBoundsException e) {
// no more objects in stream
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (dec != null) {
dec.close();
}
}

return result.toArray(new Object[result.size()][]);
}

@Test(dataProvider="dp")
public void test(String arg0, User user) {
System.out.println("arg0: " + arg0) System.out.println ("user" + user);}}

Resources

example source files
Long Term Persistence of JavaBeans Components: XML Schema
TestNG documentation - 5.5.2 - From DataProviders