title: A column in MySQL should automatically hash an inserted value (Using Hibernate and Java)
body: <p>I have some Objects in Java, using hibernate, for example:</p>
  
  <pre><code>@Entity
  class User {
  
      @Id
      private int id;
  
      @Column
      private String name;
  
      @Column
      private String pw;
  
      public User() {}
  
      public String getName() { return name; }
      public void setName(String name) { this.name = name;}
      public String getPw() { return pw; }
      public void setPw(String pw) { this.pw = pw; }
  }
  </code></pre>
  
  <p>When I instantiate a new User Object, I hash a String manually like this</p>
  
  <pre><code>User user1 = new User();
  user1.setPw(hashPw("MyPassword"));
  </code></pre>
  
  <p>It works fine, but what I want is to use the setter just like</p>
  
  <pre><code>user1.setPw("MyPassword")
  </code></pre>
  
  <p>And I want the Database to automatically hash the String with the SHA-512 algorithm (Or any you would recommend which can also be used in Java).</p>
  
  <p>I would like to tell the database when it gets created, that this column has to be hashed.</p>
  
  <p>I built the database completely with hibernate, which I'm new to.
  ATM I save the hashes in a char(128) column, not nullable, using utf8 character set.</p>
  
  <p>EDIT:</p>
  
  <p>Best would be a way with annotations in hibernate/jpa in the java code.</p>
  
  <p>EDIT:</p>
  
  <p>First step in my application is to fill the database with data. After that, I will only use the objects, maybe without changing any of their values ever again, so I need the hashing step when I insert the real data (test data atm) for the first time. I already tried the Formula annotation like this:</p>
  
  <pre><code>// ...
  @Formula("SHA2(pw,512)")
  private String pw;
  // ...
  </code></pre>
  
  <p>but after that, the column was missing complete.</p>
  
  <p>EDIT:</p>
  
  <p>I'll try to show how I imagine a possible solution:</p>
  
  <ol>
  <li>Instantiate a new User Object user1</li>
  <li>Set UNHASHED password like user1.setUnhashedPassword("MyPassword");</li>
  <li>Open a new Session</li>
  <li>Begin Transaction</li>
  <li>Save Object user1</li>
  <li>end transaction</li>
  <li>close session</li>
  <li>Getting data from database</li>
  <li>Print column "Hashed_Password"</li>
  </ol>
  
  <p>All this, without having any hashing logic in my java code.</p>