Java Annotations
Desarrollar en base a annotations nos permite evitar código sucio, ya que el mismo se puede generar automáticamente mediante las annotations en el código fuente. Esto conlleva a programación declarativa, donde el programador dice qué deberia hacerse y las herramientas simplemente emiten el código para hacerlo.
Java Persistant Api
Una de las API que trae la nueva JDK, es la api de JPA, para persistencia con bases de datos basada en annotations. La misma es muy fácil de usar y voy a citar algunos claros ejemplos de los tipos de mapeos que existen, ya que particularmente no suelo encontrar buenos ejemplos en internet.
El modelo aquí expuesto es muy simple: Artículo y Lista de Precios son muchos a muchos, conectados por una tabla que une a las otras 2. Por otro lado, artículo tiene asociado un grupo y un transporte.
One of the many features that brings us the new JDK (version 5) are Annotations. Annotations are like meta-tags that you can add to your code and apply them to package declarations, type declarations, constructors, methods, fields, parameters, and variables. As a result, you will have helpful ways to indicate whether your methods are dependent on other methods, whether they are incomplete, whether your classes have references to other classes, and so on.
Annotation-based development lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it.
Java Persistant Api
JPA is one of the best innovations of this new release. Designed for database persistence, it is based on annotations, and can be implemented with other known frameworks (such as Toplink and Hibernate). It is really easy to use and I am going to expose some examples of the different mappings, because I usually cannot find good examples over the internet.
The model is quite simple: Article and PriceList are many to many, connected by a middle table. On the other hand, article has a group and a transport associated.
Many To Many
1 2 3 4 5 6 7 | @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable( name = "article_list", joinColumns = { @JoinColumn(name = "article_id", unique = true) }, inverseJoinColumns = @JoinColumn(name = "list_id" ) ) private Set<priceList> priceLists; |
1 2 | @ManyToMany( mappedBy="priceLists") private Set<article> articles; |
ManyToOne
10 11 12 | @ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL) @JoinColumn(name = "gruou_id", nullable = false) private Grouo group; |
10 11 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "group", cascade=CascadeType.ALL) private Set<article> articles; |
OneToOne
15 16 17 | @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL) @JoinColumn(name = "transport_id", nullable = false) private Transport transport; |
