6 Replies Latest reply on Nov 17, 2005 11:20 AM by yeroc

    Mapping a Boolean

    yeroc

      Hello EJB3 gurus...

      Can anyone tell me how I go about mapping a Boolean field in an EJB3 CMP entity bean? I'm trying to map to a database column that's CHAR(1) containing Y/N/null. As far as I can tell the EJB3 spec doesn't address this. Hibernate allows the developer to specify a strategy for mapping object types like this but how do I do this within the EJB3 standard? This seems like something so ridiculously common that I must be missing something?

      Thanks,
      Corey

        • 1. Re: Mapping a Boolean
          patrick_ibg

          I don't think this is possible with the straight EJB3 persistence annotations, but you can use Hibernate Annotations extensions (@Formula should do the trick).

          • 2. Re: Mapping a Boolean
            patrick_ibg

            Forgot to qualify that @Formula will only map one way. You can still use Hibernate UserTypes with annotations... again, this is not standard EJB3.

            Finally, you could do this programmatically:

            @Entity
            public class Foo {
            
            private String bar ;
            private Boolean isBar ;
            
            public String getBar () { return this.bar ; }
            public void setBar (String s) {
             if (s != null) {
             if (s.equalsIgnoreCase ("Y"))
             isBar = Boolean.TRUE ;
             else
             isBar = Boolean.FALSE ;
             }
             isBar = null ;
             bar = s ;
            }
            
            @Transient
            public Boolean getIsBar () { return this.isBar ; }
            public void setIsBar (Boolean isBar) { this.isBar = isBar ; }
            
            }
            




            • 3. Re: Mapping a Boolean
              patrick_ibg

              eek.

              make that
              if (s != null) {
              ...
              }
              else
              isBar = null ;
              this.bar = s ;

              • 4. Re: Mapping a Boolean
                patrick_ibg

                Sorry, had a long day...

                Also, on setIsBar, you'd need to properly set the value of bar.

                • 5. Re: Mapping a Boolean
                  epbernard

                  use @Type(type="yes_no"), not @Formula

                  • 6. Re: Mapping a Boolean
                    yeroc

                    Thanks Emmanual. I guess there's no standard way of doing this. :(