Monday, May 26, 2008

Wood Swing Sets Blueprints

EJB3 - JPA

One of the new EJB specification is the third version of interceptors through which you can easily use the built system of aspect-oriented programming paradigm.
in EJB3 interceptors can refer both to the life cycle of beans and their business methods. Implements to be in the form of methods. Methods-interceptors could be placed in classes of grains as well as base classes of these grains, but also can be placed in separate classes (class interceptors). Methods-interceptors can have any level of access (public , package, protected, private ), But may not be for it or static nor final .
It is worth noting that the implementation interceptor is no more limited, because they can cause JNDI, JMS, other beans, JDBC, and EntityManager'a.

first InvocationContext

method-interceptor to operate effectively must be the primary context for the call, ie, an instance of the grain, information about the called business method and its parameters, and call the result. These data can be obtained by the object InvocationContext , which is passed as a parameter to the method-interceptor.
deserves special attention InvocationContext.proceed method () . Her call to go to the next interceptor control, or (if it is called in the last interceptorze in the chain) to the grain business method (if it is business interceptor methods).

second Class interceptors interceptors

class is a simple class (do not even need to be marked with specific reference), which simply has to define a method-interceptors. These classes must have a public constructor bezargumentowy.
lifecycle interceptors is closely connected with the life cycle grain to which it is assigned.
Class interceptors can be assigned to the whole grain or beans business methods through individual endorsement @ Interceptors , which takes as argument a list of interceptor classes.
In practice, joining the class interceptor looks something like this: @ Stateless
 @ Interceptors (pl.dwalczak.Interceptor1.class) public class Seed {... @ Interceptors (pl.dwalczak.Interceptor2.class) public void metodaBiznesowa () {}} 

third Lifecycle interceptors

grains to the interceptor method has been life-cycle grains should be determined one of the following statements, according to the desired stage of life: - @ PostConstruct - @ PostActivate - @ PreDestroy - @ PrePassivate If the method is defined in the class of grain, it should have the following signature: void
 \u0026lt;METHOD> () 
other hand, if there is a class interceptors it should look like tat:
 void \u0026lt;METHOD> (InvocationContext) 

4th Interceptors

business methods to the method was the interceptor for business methods, it should mark the annotation @ AroundInvoke .
In one class interceptor, beans, grains or base class that can be annotated to mark only one method, but this does not lead to a reduction to a business method of grain was only one interceptor. All interceptors defined in parent classes, interceptorach connected through the @ Interceptors annotation and that defined in the class of grain will be effect, and the sequence of their implementation will comply with the order of their declarations and the class inheritance hierarchy of the grain.
methods annotated @ AroundInvoke are performed on the call stack at samycm business method. This method should return the value returned by the method of business, and be able to throw an exception thrown by the method of business. For this reason, should have the following signature: Object
 \u0026lt;METHOD> (InvocationContext) throws Exception Interceptor 
to pass control further, ie to the next interceptor, or business methods, you should call the proceed on an object InvocationContext .

5th Support Resources

EJB3 specification
The Interceptor Pattern

Saturday, May 24, 2008

What Is The Difference Of Pneumonia

interceptors - the relationship one-to-one

In this article we'll look closer to a one-to-one and mapping it in the JPA.
can say that the one-to-one relationship is a special case jeden-do-wielu/wiele-do-jednego discussed by me in the article JPA - the relationship one-to-many and many-to-one . People who are not familiar with the mapping of that relationship, I would encourage you first read that article.
A one-to-one is also in some way connected with the concept of inline objects discussed in the article I JPA - Embedded objects (components) . Well, these embedded objects are interchangeable with a one-to-one to improve performance.

first Example - a problem area

example in this article are largely taken from the JPA - Embedded objects (components) .
And here's the object model:
is a system of two classes of User and Address, where User aggregates completely Address . It is worth noting that this type of bond, in which the existence of one entity is completely dependent on the existence of another being, is very common in relationships one-to-one. Like the relationship jeden-do-wielu/wiele-do-jednego we can distinguish the parent entity ( User ) and being a child (Address ). As for one being the parent entity is only one child, in order to achieve better performance (at the expense of standardization) are often used instead of the overt embedded objects of a one-to-one. In the relational world
sample model will be presented as follows:
This model shows that the implementation of a one-to-one on the side of the database is very similar to the implementation jeden-do-wielu/wiele-do-jednego relationship, but more on that a bit later.

second Bidirectional one-to-one bidirectional relationship

is one in which both objects are mutually aware that they are in a relationship from one object, you can navigate / move to the second. However, before proceeding to discuss the mapping of this relationship, first I would write a few sentences about the database implementation.
Well, the database implements is a one-to-one by adding a foreign key to one of the two entities. It is thus quite similar to the implementation jeden-do-wielu/wiele-do-jednego relationship, in which the subordinate entity has a foreign key to the parent entity. With the difference that in this case there is no requirement that the subordinate entity owned bonds and may also be the parent entity. At the same time that there was indeed a one-to-one, and could not degenerate into jeden-do-wielu/wiele-do-jednego relationship, it must be assumed Uniqe constraint'a the foreign key column.
when you map one-to-one fundamental role annotation @ OneToOne to be determined field-binding sites are in this relationship. Interestingly, the available attributes for this endorsement is the sum of the attributes available for the annotation @ OneToMany and @ ManyToOne , which highlights the similarity of a one-to-one relationship to jeden-do-wielu/wiele-do-jednego and simultaneously enhances the high symmetry bonds in the relationship.
Optionally, you can use @ JoinColumn annotation , which will serve the foreign key specification - the column name and the definition of unique constraintu on this column. Acc. JPA specification defaults column Foreign key to nazywałaby [nazwa_drugiej_tabeli] _ [nazwa_klucza_głównego_drugiej_tabeli] and that was not founded unique constraint when generating the database schema.
fragment mapping class User :
 @ Entity @ Table (name = "user") public class User {@ OneToOne (cascade = CascadeType.ALL, optional = false) @ JoinColumn (name = "addr_id", unique = true ) private Address address; ... } 
fragment mapping class Address:
 @ Entity @ Table (name = "address") public class Address {@ OneToOne (mappedBy = "address") private User user; ... Semantics} 
annotation attributes @ OneToOne is the same as for those annotations @ OneToMany and @ ManyToOne . I refrain from discussing them again because it is already done in the article JPA - the relationship one-to-many and many-to-one .
worth noting that these mappings are correct, assuming that the owner is an entity relationship User . However, a slightly different look to the owner if the relationship was Entity Address . First of all annotation @ JoinColumn znaczyłaby to check Address.user not User.address . A similar conversion would meet the attribute @OneToOne.mappedBy .

third Unidirectional one-to-one Unidirectional relationship

is one in which only one object is aware of being in a relationship with another object, and only from him, you can navigate / move to the second object. Database programming
unidirectional one-to-one and its mapping is in part the same as in the case of two-way relationship. With the difference that we define the mapping for only one of two entities, which must be the owner of bonds - have a foreign key to another entity. What is interesting in one way relationship, as an alternative to annotation @ OneToOne can use the @ ManyToOne - as someone so much likes to obfuscate the model;) True @ ManyToOne is not possible to determine the attribute mappedBy , but in the case of one-way relationship and the use of this attribute so it would be impossible.

4th Support Resources

JPA specification
JPA - the relationship one-to-many and many-to-one
JPA - Embedded objects (components)

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

Friday, March 28, 2008

Reebok Boxing Any Good

TestNG - provider of data

As mentioned in the article TestNG - first steps . TestNG Framework lets you define the parameters in the configuration file, which then can be used as arguments to methods of testing.
But TestNG is also available in a much more powerful mechanism for parameterization testing data. It is called. supplier data - data provider.
Data Provider is defined as a method denoted DataProvider annotation . This method should return a two-dimensional array of objects ( Object [] [] ) or the iterator after the one-dimensional arrays of objects (Iterator \u0026lt;Object[]> ). And the following array of objects returned by the iterator (or those in two-dimensional array) containing the arguments to the next call (as many times as these tables) of the test method.
method of data provider may be bezargumentowa or have an argument of type java.lang.reflect.Method , which defines tester method, for which the data will be provided.
To assign a data provider to the test method, you must properly set the parameter dataProvider for the annotation test, which is marked with the Testing Method. Optionally, if the method is a test on a different class than the method to provide data, set the parameter yet dataProviderClass annotations Test. In addition, the test method argument types must be compatible with the types of objects in the arrays returned by the data provider.
Unfortunately you can not use the provider, including data and parameters defined in the configuration file. You also can not pass these parameters to the methods of data providers. Below
stir example of using the data provider TestNG:
 pl.dwalczak.jpapg2 package, import org.apache.log4j.Logger; org.testng.Assert import, import org.testng.annotations.DataProvider imports, org.testng.annotations.Test imports, pl.dwalczak.jpapg2.model.Address imports, pl.dwalczak.jpapg2.model.User; @ public class Test extends UserTest JpaTestCase {private static final Logger LOG = Logger.getLogger (UserTest.class) @ DataProvider (name = "address") public Object [] [] createTestData () {LOG.debug ("createTestData"); return new Object [] [] {{"Heniek", new Address ("Poznan", "11-111", "Hedwig", "12c/23")}, {"Manny", new Address ("Wroclaw, "22-222", "Kosciuszko", "14b ")}};} @ Test (dataProvider =" address ") public void createuser (String user, Address address) {LOG.debug (" create user "+ user) ; em.persist (new User (user, address, address));} @ Test (dependsOnMethods = {"createuser"}, dataProvider = "address") public void findUser (String user, Address address) {LOG.debug (" find user: "+ user); User u = (User) em.createNamedQuery (user.findByNickName"). setParameter ("nickname" user). getSingleResult (); LOG.debug ("Found user:" + u); Assert.assertNotNull (u); Assert.assertEquals (address, u.getAddress ());}} 

Resources

Example Source Files
TestNG documentation - 5.5.2 - From DataProviders

Thursday, March 27, 2008

Pokemon Red Play Game

JPA - Embedded objects (components)

Introduction

embedded objects used in the event of conflict the object model and physical model database. For example, the user is being linked to being address. The object model of these entities will be implemented by separate objects, but in a relational database in order to achieve better performance can be implemented using a single table, containing data from both user and his address. In this example, the URL will be built and will be subject to belong to the permanent facility user. An important feature is the built-in objects that are not sustained its identity (its identifier) \u200b\u200band can not be shared by different objects and equipment. Built Class

embedded object class must be marked with a note Embeddable . This does not mean it as an entity, the more determined not to her table in the database, or ID. In addition to wbudowywanej this class to be specified as the field mapping for simple entities. Below is an example of a class definition wbudowywanej - Address:
 pl.dwalczak.jpapg2.model package imports, javax.persistence.Column imports, javax.persistence.Embeddable; @ Embeddable public class Address {private String city; private String postcode; private String street; private String number; @ Column (length = 50, Nullable = false) public String getCity () {return city;} public void setCity (String city) {this.city = city;} @ Column (length = 6, Nullable = false) public String getPostcode () {return postcode;} public void setPostcode (String postcode) {this.postcode = postcode;} @ Column (length = 50, Nullable = false) public String getStreet () {return street;} public void setStreet (String street) {this.street = street;} @ Column (length = 10, Nullable = false) public String getNumber () {return number;} public void setNumber (String number) {this.number = number;}} 

wbudowywanych Placing objects on the premises and equipment

Class fields of the type designated as a bear in a built Embedded in a note . But it is not necessary, since the specification requires that the JPA EntityManager to seek out the same matter on the basis of annotations Embeddable , which bears the class of the field. The fields are mapped to an object embedded in the columns of the table entity to which it belongs. Overriding attributes
JPA mapping allows to overwrite the attributes defined in the mapping class wbudowywanej. For this purpose the annotation AttributeOverrides , which contains a list of endorsements AttributeOverride . And these only serve to override the mapping of each field class. Mechanism to override the mapping of attributes are big opportunities in the context of reusable class definitions wbudowywancyh. Below is an example of an entity, which includes two buildings built on the type of address (permanent residence address and mailing address.)
 pl.dwalczak.jpapg2.model package imports, javax.persistence.AttributeOverride; javax.persistence.AttributeOverrides import, import javax.persistence.Column imports, javax.persistence.Embedded; javax.persistence.Entity import, import javax.persistence. GeneratedValue; javax.persistence.GenerationType import, import javax.persistence.Id; javax.persistence.NamedQuery import, import javax.persistence.SequenceGenerator imports, javax.persistence.Table; @ NamedQuery (name = "user.findByNickName", query = "select u from User u WHERE u.nickName =: nickname") / / Define a sequence of "users_seq" used to generate the primary key table "users". @ SequenceGenerator (name = "users_seq") / / mapping table "users". @ Entity @ Table (name = "users") public class User {private Long id; private String nickname; private Address address; private Address mailingAddress; @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "users_seq") @ Column (name = "usr_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id;} @ Column (name = "usr_nickname", unique = true, Nullable = false, length = 24) public String getNickName ()  {
return nickName;
}
public void setNickName(String name) {
this.nickName = name;
}

@Embedded
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}

@Embedded
@AttributeOverrides({
@AttributeOverride(name="city", column=@Column(name="ma_city")),
@AttributeOverride(name="postcode", column=@Column(name="ma_postcode")),
@AttributeOverride(name="street", column=@Column(name="ma_street")),
@AttributeOverride(name="number", column=@Column(name="ma_number"))
})
public Address getMailingAddress() MailingAddress {return;} public void setMailingAddress (Address mailingAddress) {this.mailingAddress = mailingAddress;}}

Resources

example source files
Hibernate Annotations - 2.2.2.3. Embedded objects (aka components)
JPA specification

Tuesday, March 18, 2008

Borderless Printing Laser

TestNG - first steps

example of the way of writing the article "JPA - first steps," I decided that I would do well to learn the first steps to assist framework'u perform unit tests - TestNG. My first impression is very positive. Compared to the JUnit is simpler and more accessible interface, but is more powerful and is also much better documented. Hierarchy

tests in TestNG we doczycznienia with the following hierarchy of tests: suite (set), Test, Class (class containing test methods) and Method (Testing Method). While the Test Suite and are purely logical entities (defined in the configuration level), the Class and Method are units that contain the physical implementation of the tests. In addition, TestNG allows marking Class and Method marker group. At the same time it is possible to assign them to multiple groups. For all of these entities hierarchy and groups can set out the methods that will be called before or after the tests.

dependencies between tests

TestNG allows you to define dependencies between tests. You can specify that the execution of a method of testing organization or a class of tests will depend on successful implementation of the other test methods or test groups. Test Configuration

Tests in TestNG are configured in a xml file conforming to the DTD: http://testng.org/testng-1.0.dtd and through endorsements. In one configuration file can define a Suite (\u0026lt;suite> marker), within which is defined by any number of Test'ów (\u0026lt;Test> tags), or you can import the configuration files for other sets of tests. On the test, in turn, may consist of any number of groups (tag \u0026lt;groups>), class (\u0026lt;classes> marker), and you can specify the Java packages (\u0026lt;pakages> marker), within which the class will be searched for testing. For class, you can also specify which methods are to be executed and which not. Both individuals and Test Suite, you can define parameters that can be transferred In Test methods (marker \u0026lt;parameter>). With the use of annotations can include determine such things as: - whether the class includes the tests (Test annotation), - if the method is a method of testing (including the endorsement test) - the term the group owning class or the method (parameter groups for the endorsement test), and - Testing method or class containing the tests is dependent on other tests (parameter dependsOnGroups dependsOnMethods and annotations test) - identify ways to call before or after the tests (annotate Before and After * *), - define the parameters for the transmission method testing (annotation Parameters)

Example The following example is a unit tests developed for the article "JPA - first steps." It consists of a configuration file, the abstract base class and two classes containing a specific test method.
configuration file configuration file contains the definition of course test (implemented in two classes) and methods used by the majority of testing parameters.
 \u0026lt;suite name="Suite1"> \u0026lt;parameter name="user1" value="heniek" /> \u0026lt;parameter name = "user2" value = "Frank" /> \u0026lt;test Name="Test"> \u0026lt;classes> \u0026lt;class name="pl.dwalczak.jpapg1.UserTest" /> \u0026lt;class name="pl.dwalczak.jpapg1.MessageTest" /> ; \u0026lt;/ classes> \u0026lt;/ test> \u0026lt;/ suite> 
abstract base class
This class defines the basic services needed for testing the model mapping JPA. First of all, provide the EntityManager, which initiates and begins a transaction before executing each test method. However, after performing the test method and to approve the transaction closes EntityManager'a. After completing the entire test suite (Suite) is closed EntityManagerFactory.
 pl.dwalczak.jpapg1 package; javax.persistence.EntityManager import, import org.apache.log4j.Logger; org.testng.annotations.AfterMethod import, import org.testng.annotations.AfterSuite imports, org.testng.annotations.BeforeMethod imports, pl.dwalczak.jpapg1.util.JpaUtil; abstract public class {private static JpaTestCase final Logger LOG = Logger.getLogger (JpaTestCase.class) protected EntityManager em; @ BeforeMethod beginWorkUnitAndTransaction public void () {try {em = JpaUtil. getEntityManager (); em.getTransaction (). begin ();} catch (RuntimeException e) {LOG.error ("Can not  beginWorkUnitAndTransaction", e);
}
}

@AfterMethod
public void closeWotkUnitAndCommitTransaction() {
try {
if (false == em.getTransaction().getRollbackOnly()) {
em.getTransaction().commit();
} else {
em.getTransaction().rollback();
}
} catch (RuntimeException e) {
LOG.error("Can't closeWotkUnitAndCommitTransaction", e);
} finally {
if (null != em) {
try {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
} catch (RuntimeException e) {
LOG.error("Can't close entity manager!", e);
}
} I = null;}} @ AfterSuite public void closeEntityManagerFactory () {JpaUtil.closeEntityManagerFactory ();}}
UserTest
Class This class contains all tests for entity "you" and is provided with a suitable marker groups ("user") . It includes examples of passing parameters to methods of testing and determining the relationship between methods of Test.
 pl.dwalczak.jpapg1 package, import java.util.List; import org.apache.log4j.Logger; org.testng.Assert import, import org.testng.annotations.Parameters; org.testng.annotations.Test import, import pl.dwalczak.jpapg1.model.User; @ Test (groups = "user") public  class UserTest extends JpaTestCase{

private static final Logger LOG = Logger.getLogger(UserTest.class);

@Test
@Parameters({ "user1" })
public void createUser1(String user) {
LOG.debug("create user: " + user);
em.persist(new User(user));
}

@Test
@Parameters({ "user2" })
public void createUser2(String user) {
LOG.debug("create user: " + user);
em.persist(new User(user));
}

@Test(dependsOnMethods={"createUser1", "createUser2"})
@SuppressWarnings(value="unchecked")
public void list() {
LOG.debug("get user list");
em.getTransaction().setRollbackOnly();
List list = em.createNamedQuery (user.findAll "). getResultList (); LOG.debug (" user list: "+ list); Assert.assertEquals (list.size (), 2);} @ Test (dependsOnMethods = { "createUser2"}) @ Parameters ({"user2"}) public void findUser (String user) {LOG.debug ("find user" + user); User u = (User) em.createNamedQuery (user.findByNickName " ). setParameter ("nickname", user). getSingleResult (); LOG.debug ("Found user:" + u); Assert.assertNotNull (u);}}
MessageTest
Class This class contains all tests for entity " Message. " Execution of all testing methods This class is subject to a positive test result from the group "user".
 pl.dwalczak.jpapg1 package, import java.util.List; import org.apache.log4j.Logger; org.testng.Assert import, import org.testng.annotations.Parameters; org.testng.annotations.Test import, import pl.dwalczak.jpapg1.model.Message imports, pl.dwalczak.jpapg1.model.User; @ Test (dependsOnGroups = "user") public class extends MessageTest JpaTestCase {private static final Logger LOG = Logger.getLogger (MessageTest.class) ; @ Test @ Parameters ({"user1" "user2"}) public void user1SendToUser2 (String user1, String user2) {LOG.debug ("user1SendToUser2") SendMessage ("title1", "content1"  user1, user2);
}

@Test
@Parameters({ "user2", "user1" })
public void user2SendToUser1(String user1, String user2) {
LOG.debug("user2SendToUser1");
sendMessage("title2", "content2", user1, user2);
}

private void sendMessage(String title, String content, String userFrom, String userTo) {
User uFrom = (User) em.createNamedQuery("user.findByNickName").setParameter("nickName", userFrom).getSingleResult();
User uTo = (User) em.createNamedQuery("user.findByNickName").setParameter("nickName", userTo).getSingleResult();
Message message = new Message(title, content, uFrom, uTo);
LOG.debug("send a message: " + message);
em.persist(message);
}

@Test(dependsOnMethods={"user1SendToUser2", "user2SendToUser1"})
@Parameters({"user1"})
@SuppressWarnings(value="unchecked")
public void viewUser1Messages(String user) {
LOG.debug("view messages of: " + user);
User u = (User) em.createNamedQuery("user.findByNickName").setParameter("nickName", user).getSingleResult();
Assert.assertNotNull(u);
List received = em.createNamedQuery("message.findReceived").setParameter("user", u).getResultList();
LOG.debug("received messages: " + received);
Assert.assertEquals(received.size(), 1);
Letter em.createNamedQuery send = ("message.findSend"). SetParameter ("user", u). GetResultList (); LOG.debug ("send messages:" + send); Assert.assertEquals (send.size (), 1);}}

Resources

source files
TestNG documentation

Monday, March 17, 2008

Broken Cappileries In Breasts

JPA - Getting Started

longish introduction

Since the publication of the final specifications EJB3 lot of time has elapsed, and there are more and more implementation of this technology - more or less complete. This probably means that EJB3 will be increasingly popular as the technology base for new projects. So I thought that it's time to explore this technology a little closer. I would like to begin by defining the specifications of the lowest layer of the average webaplikacji - a model of persistent data and interface with a database (or perhaps with JDBC), a Java Persistence API - JPA. In fact, JPA is nothing revolutionary. SFE rather on concepts proven in the most popular ORM framework unless - Hibernate. I enjoy it more that the last two years with Hibernate I had a lot to do. What is more out of Hibernate is an implementation of JPA - and I'm going to use it. Undoubted advantage of JPA is that in a compact and relatively easy way to standardize the basic mechanisms of ORM. JPA interface is not too extensive and advanced applications may prove to be insufficient. The JPA will not find many of the advanced elements of existing frameworks ORM. It has no API to dynamically create search criteria, or it is not possible to define the class as a field enumerated SQL formula. Therefore, JPA implementations available to provide extensions to the basic specification. However, this means that a transparency of the implementation of the JPA specification may be only illusory. From a user perspective Hibernate knowledge JPA is inevitable, and so if you want to use the mapping annotations. However, in the style of the application configurations and EntityManager'a JPA is not necessary - at least for now. Another advantage of JPA is that you can use not only in the EJB3 container, but also in the normal JSE. But no longer have enough of these digressions, so move on to describe a specific example using JPA.

matter problem

to do is a model in which the center is being Message - Message, which contains in itself: the subject - title, content - content, and links to the entity User - User in the role of sender and recipient.

JPA Configuration

JPA specification specifies that the configuration file should be in your META-INF/persistence.xml. Listing the configuration file of my sample application:
 \u0026lt;persistence version = "1.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns: xsi = "http://www.w3.org/ 2001/XMLSchema-instance "xsi: schemaLocation =" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd "> \u0026lt; persistence-unit name = "jpapg1"> \u0026lt;! - Identify suppliers that implements JPA. -> \u0026lt;Provider> Org.hibernate.ejb.HibernatePersistence \u0026lt;/ provider> \u0026lt;! - \u0026lt;class> \u0026lt;/ Class> You can specify a list of classes of mapping model database. The EJB3 container is completely unnecessary, because the JPA specification imposes the obligation to implement an automatic search classes. This feature however, is not defined when you run in the normal environment JSE. However, Hibernate can be parameterized in order to search for these classes also in the JSE. -> \u0026lt;properties> \u0026lt;! - Bed configuration parameters JPA - Hibernate -> \u0026lt;property name = "hibernate.archive.autodetection" value = "class" /> \u0026lt;property name="hibernate.show_sql" value="true" /> \u0026lt;property name="hibernate.format_sql" value="true" /> \u0026lt;! - Parameters access to the database. -> \u0026lt;property Name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" /> \u0026lt;property name = "hibernate.connection.url" value = "jdbc: HSQLDB file: jpapg1db "/> \u0026lt;property name="hibernate.connection.username" value="sa" /> \u0026lt;property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> \u0026lt;! - Parameter specifying the database schema generation from mapingów. -> \u0026lt;property Name="hibernate.hbm2ddl.auto" value="create" /> \u0026lt;/ properties> \u0026lt;/ persistence-unit> \u0026lt;/ persistence> 

data model and mapping

confine myself Listing only on presentation of an example source code, which - at least I hope so - it is enough okroszony comments.
User - User
 pl.dwalczak.jpapg1.model package, import java.util.List; javax.persistence.Column import, import javax.persistence.Entity; javax.persistence.GeneratedValue import, import javax.persistence.GenerationType; javax.persistence.Id import, import javax.persistence.JoinColumn imports, javax.persistence.NamedQueries; javax.persistence.NamedQuery import, import Javax . persistence.OneToMany; javax.persistence.SequenceGenerator import, import javax.persistence.Table; @ NamedQueries (value = {@ NamedQuery (name = "user.findAll", query = "select u from User u order by asc u.nickName "), @ NamedQuery (name =" user.findByNickName ", query =" select u from User u WHERE u.nickName =: nickname ")}) / / Define a sequence of" users_seq "for the generation primary key table "users". @ SequenceGenerator (name = "users_seq") / / mapping table "users". @ Entity @ Table (name = "users") public class User {private Long id; private String nickname; private letter  receivedMessages; private letter  sendMessages / / availability of default constructor is required by the JPA. public User () {} public User (String nickname) {this.nickName = nickname;} / / Primary key table (column "usr_id"), / / \u200b\u200bwhose value is determined by the sequence "users_seq. @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "users_seq) @ Column (name = "usr_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id;} / / mapping column usr_nickname "which must have a unique value / / and have a maximum length of 24 characters. @ Column (name = "usr_nickname", unique = true, Nullable = false, length = 24) public String getNickName () {return nickname;} public void setNickName (String name) {this.nickName = name;} / / mapping connections to the table "messages" in the role of the recipient. / / Definition of columns in the table "messages" which is the concatenation (Msg_to "). / / Select the record for being the "User" has nothing to do with the "Message" / / associated by the association. @ OneToMany @ JoinColumn (name = "msg_to", insertable = false, updatable = false) public List  getReceivedMessages () {return receivedMessages;} public void setReceivedMessages (Letter  receivedMessages) {this.receivedMessages = receivedMessages;} / / Definition connection to the table "messages" in the role of the sender. @ OneToMany @ JoinColumn (name = "msg_from", insertable = false, updatable = false) public List  getSendMessages () {return sendMessages;} public  void setSendMessages(List   sendMessages) {
this.sendMessages = sendMessages;
}
}
Wiadomość - Message
 package pl.dwalczak.jpapg1.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@NamedQueries(value={
@NamedQuery(
name="message.findReceived",
query="select m from Message WHERE m.to m =: user "), @ NamedQuery (name =" message.findSend ", query =" select m from Message m WHERE m.from =: user ")}) / / Define a sequence of" messages_seq "for the generate the primary key table "messages". @ SequenceGenerator (name = "messages_seq") / / mapping table "messages". @ Entity @ Table (name = "messages") public class Message {private Long id; private String title; private String content; User from private, private to User / / availability of default constructor is required by the JPA public Message () {} public Message (String title, String content, User from, the User) {this.title = title; this.content = content; this.from = from; this.to = this;} / / Primary key table (column 'msg_id'), / / \u200b\u200bwhose value is determined by the sequence "messages_seq. @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "messages_seq") @ Column (name = "msg_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id; } / / mapping column msg_title "whose value can be up to 64 characters. @ Column (name = "msg_title", length = 64) public String getTitle () {Return title;} public void setTitle (String title) {this.title = title;} / / mapping column msg_content "whose value can be up to 1024 characters. @ Column (name = "msg_content", length = 1024) public String getContent () {return content;} public void setContent (String content) {this.content = content;} / / Mapping to the table "users" - the message sender. / / This link is mandatory - it must be set - and is implemented by the / / foreign key to table "users", which stores the value of column "msg_from. / / This is equivalent to the relationship defined on User.sendMessages. @ ManyToOne (optional = false) @ JoinColumn (name = "msg_from" Nullable = false) public User getFrom () {return from;} public void setFrom (User from) {this.from = from;} / / Mapping to the table "users" - the message recipient. / / This is equivalent to the relationship defined in the User.receivedMessages. @ ManyToOne (optional = false) @ JoinColumn (name = "msg_to" Nullable = false) public User ghetto () {return this;} public void Setto (User to) {this.to = this;}}

Entity Manager

Entity Manager is that in the JPA, which is in the Hibernate Session. The JSE You can obtain it as follows:
 javax.persistence.Persistence.createEntityManagerFactory ($ PERSISTANCE_UNIT_NAME). createEntityManager (); 
In EJB3, you can do this by injecting (the container) to the field in the beanie EJB:
 javax.ejb.Stateless import; import javax.persistence.PersistenceContext; @ Stateless public class Example implements ExampleBean {@ PersistenceContext EntityManager em; ... 
} Entity Manager is the starting point to perform such operations as: - the consolidation of the object (the method persist) - queries execution (method and find methods of family group createQuery) - manulnego determining transaction - beginning, acceptance and withdrawal (method getTransaction ())

Query Language query language in the JPA is a JPA-QL (EJB-QL extension) and is very similar to Hibernate'owego HQL'a. I think I used the example queries are simple enough that it does not require comment. Resources

example source files
Java Persistence with Hibernate - Sample Chapter 2
JPA - javadoc
Hibernate Annotations
Hibernate EntityManager

Friday, February 29, 2008

Samsung Ml-2010 Laser Printer

Research web

PBJ Market Research have the ability to perform research on the Internet. Surveys may be available to all visitors to our site as well as for selected respondents who receive an email with your password access to the survey.

survey publicly available gives a lot of opportunities, but reduces our control over the criteria for selection of the sample - we do not know who really fills in, and whether he writes the truth.

Survey respondents selected is suitable for studies such as employee or customer satisfaction. Certain limitation of this method is the need for an e-mail addresses database. However, we are confident that the survey is completed by a competent person.

a few months of 2007 on our web survey was available that could anonymously fill in all the willing. The survey concerned the behavior of the network. Completed her 200.

research results will be available soon on our website and blog.

Below I present some basic conclusions of the research:


wyniki ankiety

* In our study population nearly 60% use the Internet for several hours day. Az 17% of respondents are people who spend several hours online during the day.

* 80% of respondents have between 1 and 3 email accounts. Most respondents have 2 email accounts (35%).

* the mail every day using nearly 70% of respondents. 20% of respondents use several times a week.

* Respondents rarely enter chat rooms. 60% had never comes. In the sample there were 7.5% of people who enter the chat rooms at least once a week.

* Using the theme for it was more common. 47% at least once a week for thematic use. 17% never enter the forums.

* Shopping on the Internet, our respondents rarely do - at least once a week - 64%. Do not buy over the internet 28% of respondents.

* information about social and political subjects derive primarily from the TV (73%) and portals (71%) and radio (49%). Only 33% of the draws about newspapers.

* With friends, our respondents often talk on the phone (81%) and esemesują (67%). It is not strange, because up to 98% of respondents own a mobile phone. Landline phone conversations are definitely urban popular - only 16% of respondents using landline phone to contacts with friends. Respondents frequently (64% of responses) are also in contact with friends in person and by instant messaging (64%). Relatively rare (37% of responses) respondents contacted via email with friends.

* quarter of respondents go to the cinema once a month. 22% comes once every six months.

* examined the 72% women and 28% of men. 40% are staff employees. The same in our sample found themselves unemployed.

* Our respondents have a mobile phone (98%) and internet at home (93%). Only 68% have a landline phone.

* bank account managed by the Internet seems to be popular in the studied group - it has more than 60% of respondents. Definitely fewer people (15%) has a web page, and (14%) blog.

Monday, February 4, 2008

Clonazepam And Flagyl

PBJ Market Research News at

Page PBJ Market Research enriched with photocopies of references of existing customers their services, but when they post, I noticed by reading in their content, that practically each of the recommendations issued concerns some other division of marketing research and market. And so we have:
references for conducting surveys
references for the efficient conduct of research focusowych
testimonial for viewing advertising, testing
references for a study on branding
references for the type test desk research
References for quantitative study and statistical analysis
And it would be enough when it comes to changes on the corporate side. Carnival is over, so it's time to go to work - and his way this year, it was a short record, which has its plus so that next Christmas no longer just right ... ;)

Tuesday, January 29, 2008

Abdominal Pain 9 Weeks Pregnant.

PBJ Market Research Company image on Google Maps

As we know more and more importance in shaping the company's image and the internet becomes more and more companies also commission market research into this particular angle. Should I hire a professional who will create a positive image on the web, but can also be the same, even using only the free solutions make it a potential the client will know how to find us. This free service offers, among other things Google, and more specifically a service called Google Maps, but until recently it was connected with the knowledge of the API code. Currently, this service has been substantially simplified, giving even the possibility of including pictures in a cloud, a link to our site, etc. After setting up everything, we are left with only the code ready to copy and paste in the appropriate place on our corporate website - the best in the tab with our data full contact - and you're done. The only limitation of this solution is the amount of displaying the maps on the day, a limit which is set to 500 impressions per day. Contrary to appearances, this is a lot, because even if you visit our corporate website X thousand people a day, it must be remembered that only one person who either enters the data at our company. This solution, except that it is free, is very well seen in the eyes of the customer, who by means of maps is able to immediately determine the location of our headquarters.
And so it looks like a map location of the research center PBJ - Market Research:

View Larger Map