title: How to implement ManyToMany relationship in MyBatis?
body: <p>I'm recently learning to develop Web Applications using Java frameworks.  </p>
  
  <p>The application is just a basic register/login/logout system. Guests can register an account and login as a <code>common user</code>. Besides <code>common user</code>, there're two other roles <code>super admin</code> and <code>admin</code>, with their respective permissions/previleges. </p>
  
  <p>An <code>Account</code> could own several <code>Role</code>s simultaneously, and of course a <code>Role</code> can be applied to many <code>Account</code>s. And that forms a many-to-many(or n-to-to) relationship between <code>Account</code> and <code>Role</code>.</p>
  
  <p>I've maintained three tables in my database:</p>
  
  <ul>
  <li>First, the <code>ACCOUNT</code> table, which stores information of an account except the account's roles;</li>
  <li>Second, the <code>ROLE</code> table, which stores information about how many <code>Role</code>s there are. Currently, there are only three, "Superuser", "Admin" and "Common User";</li>
  <li>Third one, the <code>ACCOUNT_ROLE</code> table, which stores the mapping between <code>ACCOUNT</code> and <code>ROLE</code>.</li>
  </ul>
  
  <p>I can implement this using Hibernate's <code>@ManyToMany</code> and <code>@JoinTable</code> annotations, if I do so, <strong>the third table can be automatically managed by Hibernate</strong>. For example, when I create an <code>Account</code> of <code>Common User</code>, hibernate will help me add an entry which contains the <code>AccountId</code> and <code>RoleId</code> into the third table; and when I delete this <code>Account</code>, hibernate will help me drop the corresponding entry in the third table.</p>
  
  <p>And, the question is <strong>How can I implement this many-to-many relationship in MyBatis?</strong></p>
  
  <p>I've read some materials introducing how to set up <code>one-to-one</code> or <code>one-to-many</code> relationship in MyBatis. But it seems that MyBatis doesn't have the <code>many-to-many</code> relationship like Hibernate. So what am I gonna do?</p>
  
  <p>My raw idea is <em>Manage The Third Table Manually</em>, which means:</p>
  
  <ul>
  <li>I have to add entries to the third table manually, when I create a new account</li>
  <li>I have to remove/update corresponding entries manually, when I delete/update an account</li>
  </ul>
  
  <p>Since I'm not really that familiar with MyBatis, this way is the only idea I can come up with now.</p>
  
  <p>I hope someone could give me some tips or ideas or concrete samples about rounding off this problem.</p>
  
  <p><em>PLUS</em>: I've the demo application's code on <a href="https://github.com/YigWoo/user-manage" rel="nofollow">github</a>, in case you need to see how this demo goes.
  Many thanks!</p>