Hibernate Search & Bean Validation
Upcoming SlideShare
Loading in...5
×
 

Hibernate Search & Bean Validation

on

  • 4,632 views

 

Statistics

Views

Total Views
4,632
Views on SlideShare
4,430
Embed Views
202

Actions

Likes
3
Downloads
70
Comments
0

4 Embeds 202

http://chtijug.org 188
http://www.slideshare.net 11
http://webcache.googleusercontent.com 2
http://translate.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Hibernate Search & Bean Validation Hibernate Search & Bean Validation Presentation Transcript

  • Ch’ti JUG Hibernate Search et Bean Validation Emmanuel Bernard 21 septembre 2009 Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Emmanuel Bernard  Hibernate Search in Action  blog.emmanuelbernard.com  twitter.com/emmanuelbernard  lescastcodeurs.com Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Hibernate Core Emmanuel Bernard JBoss by Red Hat Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Performance  Transactional write behind  sophisticated snapshot comparison  load associated objects (join, subselect, batch)  batch changes / bulk operations  lazy collections / objects  prepared statements  pre-compiled queries  smart merge  ... Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Flexibility  Override any SQL  DDL generation optional  stored procedures  statistics  used named queries  stateless session  Bulk HQL  Database portability Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Tips  Use conversation scoped persistence contexts aka first level cache  do not 2nd level cache for everything • reference data  set everything as lazy and use queries  Stop maintaining your home-grown ORM Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG JSR-303 - Bean Validation Emmanuel Bernard JBoss by Red Hat Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG  Enable declarative validation in your applications  Constrain Once, Validate Anywhere Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Constraints  Constraint • restriction on a bean, field or property • not null, between 10 and 45, valid email...  How is that useful • give feedback to the user • ensure that a service will behave correctly • define service range of usability • avoid adding crap to the database • unless you like fixing the data manually Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Constraints in the Java Ecosystem  Where should they be applied Java Data Client Presentation Business Access Database Side Layer Layer Layer  How many model do I have? • 1 Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG What is the solution?  Uniform way to express a constraint • everybody speaks the same language • based on the domain model (JavaBeans™)  Standard way to validate constraints • one runtime engine • same validation implementations shared  Bridge for constraints out of Java™ land • API to access the constraint repository Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Declare a constraint public class Address { @NotNull @Size(max=30, message="longer than {max} characters") private String street1; ... @NotNull @Valid private Country country; } public class Country { @NotNull @Size(max=30) private String name; ... } Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Groups  Subset of constraints  Partial validation • screen of a wizard UI  Constraints applied in a given use case  Order constraint validations • which depends on other validations • when a constraint is resource/time intensive Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG interface Billable {} interface BuyInOneClick extends Billable, Default {} class User { @NotNull(groups=BuyInOneClick.class) PaymentMethod getDefaultCreditCard() {...} @NotNull //Default group String getUserName() {...} } @GroupSequence(sequence={Default.class, Heavy.class}) interface Complete {} Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Create your own constraint  Annotations with expressive names  List of ConstraintValidators  Constraint composition Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG @Constraint(validatedBy={ SizeValidatorForCollections.class), SizeValidatorForString.class } ) public @interface Size { String message() default "{constraint.size}"; Class<?>[] groups() default {}; Class<? extends ConstraintPayload> payload() default {}; //custom attributes int min() default 0; int max() default Integer.MAX_VALUE; } Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG public class SizeValidatorForString implements ConstraintValidator<Size, String> { public void initialize(Size annotation) {} public boolean isValid(String value, ConstraintValidatorContext context) {} } Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Composition  Reuse constraints  Expose meta-informations @NotNull @Size(min=5, max=5) @Constraint(validatedBy=FrenchZipCodeValidator. public @interface FrenchZipCode { String message() default "{constraint.frenchzi Class<?>[] groups() default {}; Class<? extends ConstraintPayload>[] payload() default {}; } Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Composition  Reuse constraints  Expose meta-informations @NotNull @Size(min=5, max=5) @Constraint(validatedBy=FrenchZipCodeValidator.class) public @interface FrenchZipCode { String message() default "{constraint.frenchzipcode}"; Class<?>[] groups() default {}; Class<? extends ConstraintPayload>[] payload() default {}; } Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG  Integration  - tools  - plain SE  - EE 6 Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Bootstrap API  extensible  support multiple implementations  type-safe  can override some attributes contextually  XML configuration optional • META-INF/validation.xml Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); ValidatorFactory vf = Validation.byDefaultProvider() .configure() .messageInterpolator( containerMI ) .traversableResolver( jpaTR ) .constraintValidatorFactory( webBeansDI ) .buildValidatorFactory(); ValidatorFactory vf = Validation .byProvider(HibernateValidationProvider.class) .configure() .messageInterpolator( containerMI ) .failFast() .enableLegacyConstraints() .buildValidatorFactory(); Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Message  Can be externalized  Internationalization  Interpolate constraint parameters • must be shorter than {min}  Custom MessageInterpolator strategy • Useful for application frameworks • Contextual data • Locale Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Manual validation  Get a Validator from a ValidatorFactory Set<ConstraintViolation<User>> errors = validator.validate(user); Set<ConstraintViolation<User>> errors = validator.validate(user, BuyInOneClick.class);  ConstraintViolation • error message / message template • invalid value • context Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Accessing the metadata  DDL generation, tools, JavaScript generators  Metadata API BeanDescriptor - validator.getConstraintsForClass(User PropertyDescriptor - beanDescr.getConstrainedPropertie ConstraintDescriptor - descr.getConstraintDescriptors( - constrDescr.getComposingConstra  Shines with: • composition • built-in annotations Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Accessing the metadata  DDL generation, tools, JavaScript generators  Metadata API BeanDescriptor - validator.getConstraintsForClass(User.class) PropertyDescriptor - beanDescr.getConstrainedProperties() ConstraintDescriptor - descr.getConstraintDescriptors() - constrDescr.getComposingConstraints()  Shines with: • composition • built-in annotations Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG JSF 2 integration  Zero conf  Validate input components • find property via Expression Language • call Bean Validation on input value • return localized error messages • use JSF user Locale • custom MessageInterpolator Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Java Persistence 2  On entity change • validation • can select the groups validated  Make use of a custom TraversableResolver • do not traverse associations Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Java EE 6  Validator as an injectable resource @Resource Validator validator; //or @Resource ValidatorFactory vf; Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Bean Validation  Status  Todo • Well... nothing  Give us feedback! Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Hibernate Validator 4  Bean Validation is in proposed final draft • RI available  Road Map • working on the TCK • backward compatible with legacy Hibernate Validator usage • some cool ideas out of the spec scope  License • ASL 2.0 Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Questions?  JCP.org • http://jcp.org/en/jsr/detail?id=303 • http://people.redhat.com/~ebernard/ validation  http://in.relation.to • Search for ‘Bean Validation’  Hibernate Validator • http://validator.hibernate.org  http://forum.hibernate.org/ viewforum.php?f=26 Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Hibernate Search Full-text search for Hibernate Apps Emmanuel Bernard JBoss by Red Hat Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG  Understand what full-text search does for you  Understand the magic sauce: analyzers  Full-text search and applications: how does it fit?  Bring the Wow! effect to existing applications Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG What is searching?  Searching is asking a question  Different ways to answer • Categorize data up-front • Offer a detailed search screen • Offer a simple search box Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • What is searching? Ch’ti JUG  Searching is asking a question  Different ways to answer • Categorize data up-front • Offer a detailed search screen • Offer a simple search box Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Human search in a relational world  where? • which columns, which tables  column != word • wildcard queries?  did you say “car” or “vehicle”?  cympausium or simposyum?  Order results by relevance  How to do that in SQL? Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Full Text Search  Search by word  Dedicated index • inverted indices (word frequency, position)  Very efficient  Full text products: • embedded in the database engine • black box / appliance • library embeddable like Lucene Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Some of the interesting problems  bring the “best” document first  recover from typos  recover from faulty orthography  find from words with the same meaning  find words from the same family  find an exact phrase  find similar documents Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Find by relevance  Best results first • very human sensitive  Prioritize some fields over others  The more matches, the better • for a given key word per document • for a given document the amount of matching key words  Similarity algorithm Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Extracting the quintessence  Word: Atomic information  Analyzer • Chunk / tokenize the text into individual words • Apply filters • remove common words • lower case  One tokenizer  Some filters Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Approximation Ch’ti JUG  Recover from typos and other approximations  Fuzzy search • query time operation • Levenshtein distance (edit distance) Hibernate Hibrenate Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG  n-gram • cut the word in parts of n characters • index each piece hibernate Index hib ibe ber ern nat ate Query ybe ber ern nat ybernat  Indexing + query time strategy • use a TokenFilter Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Demo Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Phonetic search  Is it “jiroscop” or “gyroscope” • not so useful in daily life  Several phonetic algorithms • Soundex • Metaphone (JRSKP) • mostly for latin languages  index the phonetic equivalent of a word  Indexing + query time strategy • use a TokenFilter Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Synonyms  Based on a synonym dictionary  index a reference word in the index like cherish car banger love auto jalopy I like to drive my auto around I love to drive my banger around I love to drive my auto around I cherish to drive my car around  Indexing + query time strategy • use a TokenFilter Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Words from the same family  love, lover, loved, loving  Brutal force • index all variations of a word  Stemming • Porter algorithm for English • Snowball Stemmer for most Indo-European languages  Indexing + query time strategy • use a TokenFilter Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG What’s the catch  Lucene is quite low level  Integration into an application model  Index synchronization  Object model conversion  Programmatic mismatch Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Integration into a Java SE / EE app  Hibernate Search bridges • Hibernate Core and Java Persistence • JBoss Cache & Infinispan (More to come) • Apache Lucene  Transparent index synchronization • event based  Metadata driven conversion • annotation based  Unified programmatic model • API • semantic Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG More on Hibernate Search  Asynchronous clustering (JMS, JGroups)  Projection  Filters  Index sharding  Custom DirectoryProvider (eg. JBoss Cache, Infinispan based)  JBoss Cache is full text searchable  Native Lucene access Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Asynchronous cluster  Search local / change sent to master  Asynchronous indexing (delay)  No front end extra cost / good scalability Slave Hibernate Database Lucene + Directory Search request Hibernate Search (Index) Copy Index update order Copy Hibernate Master Lucene + Directory Index update JMS Process Hibernate Search (Index) queue Master Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Summary  Search for humans  Full text tackles those problems • relevance • (human) fault tolerance • stemming and synonyms • incremental search  Barrier of entry has lowered: Go for it! • POJO based approach • infrastructural code tackled by frameworks • unified programmatic model 49 Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Questions?  http://search.hibernate.org  http://lucene.apache.org  Hibernate Search in Action • Manning  http://in.relation.to  http://blog.emmanuelbernard.com Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Licence  Les photos et logos appartiennent à leurs auteurs respectifs  Le contenu de la présentation est sous licence Creative Commons 2.0 France • Contrat Paternité • Pas d'Utilisation Commerciale • Pas de Modification  http://creativecommons.org/licenses/by-nc-nd/2.0/fr/ Copyright © Emmanuel Bernard – License Creative Commons 2.0 France
  • Ch’ti JUG Buffet  Merci pour votre attention  Merci à Norsys pour son sponsoring Copyright © Emmanuel Bernard – License Creative Commons 2.0 France