No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Vous devez être membre et vous identifier pour publier un article.
Les visiteurs peuvent toutefois commenter chaque article par une réponse.

Hibernate et JPA; Accès aux membres ou via les accesseurs

Astuces de l’Infobrol (Java)Article publié le 05/10/2010 09:21:02


Dans certaines applications, je continue à utiliser un bon vieux DAO avec JDBC, mais c’est quand même beaucoup plus rapide de développer avec Hibernate.

Le problème, c’est que le modèle (la logique métier) se trouve dans un projet Java qui est utilisé comme dépendance Maven dans le projet qui s’occupe de la persistance des données. Il n’est donc pas question de modifier le modèle pour l’adapter à Hibernate, c’est à Hibernate de s’adapter au modèle.

Hibernate et encapsulation


Nous pouvons spécifier dans Hibernate la manière d’accéder aux champs, soit directement au champ lui-même par réflexion, soit au travers des accesseurs(get... et set...).

Pour cela, nous pouvons utiliser l’attribut "default-access" pour le comportement par défaut pour la classe, ou encore simplement "access" au niveau d’un membre.

Exemple avec Hibernate et un fichier de configuration(.hbm)


  1. package be.gaudry.model.brolmeter;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.Collections;
  6. import java.util.Date;
  7. import java.util.List;
  8. import java.util.RandomAccess;
  9. import java.util.Set;
  10. import java.util.TreeSet;
  11.  
  12. import be.gaudry.model.LightObject;
  13.  
  14. /**
  15.  * Adding or removing measures from the indexes may lead to dirty relative
  16.  * measures (i.e. adding an index with an oldest date than the last index). This
  17.  * method sort the original measures (indexes), and re-evaluate the relative
  18.  * measures. The cost of maintaining relative measures is minimized by the fact
  19.  * nothing is done on an insert or a remove, but the state is set to dirty, and
  20.  * the relative measures must be re-evaluated the next time they will be asked
  21.  * for. Asking for relative measures if dirty flag is not set has no cost.
  22.  *
  23.  * @date Feb 7, 2009
  24.  * @author Steph GAUDRY
  25.  *
  26.  */
  27. public class Meter extends LightObject {
  28.  
  29.  
  30. /**
  31. * Indexes of the meter
  32. * @todo: use a Set and builds a treeset to avoid sorting manually
  33. */
  34. private List‹Measure› measures;
  35. private EMeterType meterType;
  36. private String unit;
  37.  
  38.  
  39. public Meter() {
  40. this("?", "?");
  41. }
  42.  
  43. public Meter(String name, String unit) {
  44. this(-1, EMeterType.DEFAULT, unit);
  45. this.display = name;
  46. }
  47.  
  48. /**
  49. * @param id
  50. * @param _meterType
  51. * @param _unit
  52. */
  53. public Meter(int id, EMeterType _meterType, String _unit) {
  54. super(id, "");
  55. this.unit = _unit;
  56. this.meterType = _meterType;
  57. this.measures = new ArrayList‹Measure›();
  58. }
  59.  
  60.  
  61. /**
  62. * @return the meterType
  63. */
  64. public EMeterType getMeterType() {
  65. return meterType;
  66. }
  67.  
  68. /**
  69. * Returns an unmodifiable view of the measures (only ‹b›indexes of the
  70. * meter‹/b›). This collection is ‹b›sorted by insertion order‹/b› and not
  71. * by date; call the {@link java.util.Collections#sort(List)
  72. * Collections.sort(List)} method to sort by date. ‹br /›
  73. * This method allows modules to provide users with "read-only" access to
  74. * the measures. Query operations on the returned list "read through" to the
  75. * specified list, and attempts to modify the returned list, whether direct
  76. * or via its iterator, result in an ‹tt›UnsupportedOperationException‹/tt›. ‹br /›
  77. * ‹br /›
  78. * The returned list will be serializable if the specified list is
  79. * serializable. Similarly, the returned list will implement
  80. * {@link RandomAccess} if the specified list does.
  81. *
  82. * @return an unmodifiable view of the measures (never null).
  83. */
  84. public Collection‹Measure› getMeasures() {
  85. return Collections.unmodifiableList(measures);
  86. }
  87.  
  88. /**
  89. * @param unit
  90. * the unit to set
  91. */
  92. public void setUnit(String unit) {
  93. this.unit = unit;
  94. }
  95.  
  96. /**
  97. * @return the unit
  98. */
  99. public String getUnit() {
  100. return unit;
  101. }
  102.  
  103.  
  104. /**
  105. * Adds a {@link Measure} for this meter.
  106. * ‹br /›Sets also the {@link Measure#setMeter(Meter) measure meter} with this.
  107. * @param measure
  108. * @deprecated use {@link #addMeasure(Date, double)} instead of this (will be protected into next versions)
  109. */
  110. public void addMeasure(Measure measure) {
  111. measures.add(measure);
  112. measure.setMeter(this);
  113. }
  114.  
  115. /**
  116. * Builds and adds a {@link Measure} for this meter.
  117. */
  118. public void addMeasure(Date date, double value) {
  119. measures.add(new Measure(this, date, value));
  120. }
  121.  
  122. public void clearMeasures() {
  123. measures.clear();
  124. relativeMeasures.clear();
  125. dirty = false;
  126. }
  127. }



  1. ‹?xml version="1.0" encoding="UTF-8"?›
  2. ‹!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.6//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"›
  3. ‹hibernate-mapping default-access="field"
  4. default-cascade="none" default-lazy="false" package="be.gaudry.model.brolmeter"›
  5. ‹union-subclass name="MeterHibernateWrapper" table="T_METERS"
  6. extends="be.gaudry.model.LightObject"›
  7. ‹list name="measures" cascade="all"›
  8. ‹key column="meter"/›
  9. ‹index column="MEASURES_LIST_INDEX"/›
  10. ‹one-to-many class="MeasureHibernateWrapper"/›
  11. ‹/list›
  12. ‹property name="unit" type="string" not-null="false" /›
  13. ‹property name="meterType" type="be.gaudry.model.brolmeter.EMeterType" not-null="false" /›
  14. ‹/union-subclass›
  15. ‹/hibernate-mapping›

Ce qui nous intéresse est la ligne suivante:
  1. default-access="field"


Remarque: et JPA?


Depuis JPA 2.0, nous avons l’annotation @Access qui nous permet aussi de spécifier comment accéder aux champs.

Avatar :: Steph Un article de StephModifié 1 fois. (dernière modification le 05/10/2010 09:33:53 par Steph)



Source : indéterminée


Sélection, tri et recherche d'articles
FILTRER :
TRIER :1er critère : 2e critère :
CHERCHER : Dans les titres Dans le contenu


[Afficher les liens en fonction des critères du formulaire ci-dessus]

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 13/09/2004, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/ast-rf-464.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.