title: How to generate a value for a column in a JPA entity, while querying the database?
body: <p>I have an entity that looks like this:</p>
  
  <pre><code>@Entity
  @Table(uniqueConstraints={@UniqueConstraint(columnNames={"slug"})})
  public class BlogPost {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      @Column
      private String title;
  
      @Column
      private String slug;    
  }
  </code></pre>
  
  <p>I would like to generate the value of <strong>slug</strong> before persisting by doing the following:</p>
  
  <ul>
  <li>Transforming the <strong>title</strong> from e.g. <em>Blog Post Title</em> to <em>blog-post-title</em> </li>
  <li>Making sure that <em>blog-post-title</em> is unique in table BlogPost, and if it's not unique, I want to append some suffix to the title so it becomes e.g. <em>blog-post-title-2</em></li>
  </ul>
  
  <p>Since I need this on a lot of entities, my original idea was to create an EntityListener which would do this at <em>@PrePersist</em>. However, documentation generally states that I should not call EntityMan­ager or Query methods and should not access any other entity objects from lifecycle callbacks. I need to do that in order to make sure that my generated slug is indeed unique.</p>
  
  <p>I tried to be cheeky, but it is indeed very hard to autowire a repository into an EntityListener with Spring anyway.</p>
  
  <p>How should I best tackle this problem?</p>
  
  <p>Thanks!</p>