title: JPA/Hibernate: AttributeConverter does not convert a class
body: <p>There is a class <code>Order</code> with <code>inks</code> field which is a collection of 4 possible <code>Ink</code> constants: <code>Ink.YELLOW, Ink.MAGENTA, Ink.CYAN, Ink.BLACK</code>. <code>Inks</code> are converted into single <code>Integer</code> as a bit mask using each <code>Ink</code>'s position. For example <code>{ Ink.MAGENTA, Ink.CYAN } =&gt; 0110 =&gt; 6</code>.</p>
  
  <p>For some reason <code>AttributeConverter</code> receives empty <code>Inks</code> when saving entity to database and always produces <code>0</code> in database column. When it is run directly everything works just fine.</p>
  
  <p>I see the <code>AttributeConverter</code> is being run twice. <code>Inks</code> argument is empty only the second time. I believe something is wrong with mapping. </p>
  
  <p><strong>Order</strong></p>
  
  <pre><code>@Entity
  public class Order {
      @Id
      public int id;   
  
      @Convert(converter = InksConverter.class)
      public Inks inks = new Inks();
  
      //...
  }
  </code></pre>
  
  <p><strong>Inks</strong></p>
  
  <pre><code>public class Inks {
      private TreeSet&lt;Ink&gt; set = new TreeSet&lt;&gt;();
  
      public Inks(Ink... inks) {
          set.add(inks);
      }
  
      public void add(Ink... inks) {
          for (int i = 0; i &lt; inks.length; i++) set.add(inks[i]);
      }
  
      public int toInteger() {
          Integer i = 0;
          for (Ink ink : set) i |= (1 &lt;&lt; ink.id);
          return i;
      }
  
      public Inks fromInteger(int i) {   
          Inks inks = new Inks();
          Ink.set.forEach(ink -&gt; {
              if ((i &amp; (1 &lt;&lt; ink.id)) == 1) inks.add(ink);
          });
          return inks;
      }
  
      //...
  }
  </code></pre>
  
  <p><strong>InksConverter</strong></p>
  
  <pre><code>@Converter(autoApply = true)
  public class InksConverter implements AttributeConverter&lt;Inks, Integer&gt; {
  
      @Override
      public Integer convertToDatabaseColumn(Inks inks) {
          return inks.toInteger();
      }
  
      @Override
      public Inks convertToEntityAttribute(Integer i) {           
          return Inks.fromInteger(i);
      }
  }
  </code></pre>
  
  <p><strong>Saving order into database</strong></p>
  
  <pre><code>Session session = configuration.buildSessionFactory().openSession();
  Order order = new Order();
  order.inks.add(Ink.BLACK, Ink.CYAN);
  session.save(order);
  session.close();
  </code></pre>