title: JPA Hibernate - How to save two objects from two entities that are connected
body: <p>I have two entities: Account and Profile. They are connected with an One To One relationship.</p>
  
  <p><strong>Account Entity:</strong></p>
  
  <pre><code>@Entity
  @Table(name = "account")
  public class Account {
  
      @Id
      @Column(name = "account_id")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @OneToOne
      private Profile profile;
  
      ...
  
  }
  </code></pre>
  
  <p><strong>Profile Enity:</strong></p>
  
  <pre><code>@Entity
  @Table(name = "profile")
  public class Profile {
  
      @Id
      @Column(name = "profile_id")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @OneToOne(mappedBy = "profile", cascade = CascadeType.ALL)
      private Account account;
  
      ...
  
  }
  </code></pre>
  
  <p>The problem is when I try to save in database, a new object from Account and a new object from Profile and connect them. Something like this:</p>
  
  <pre><code>Account account = new Account();
  Profile profile = new Profile();
  profile.setAccount(account);
  account.setProfile(profile);
  
  accountRepository.save(account);
  profileRepository.save(profile);
  </code></pre>
  
  <p>Of course this doesn't work. After searching for a solution I found that I must use persist method and Transactions. However I haven't found how to use them. I tried to use EntityManager and create a <code>persistence.xml</code> file, but spring doesn't find it (I put it in directory: src/main/resources/Meta-INF).</p>
  
  <p>My question is: Is there a simpler way to save both of the objects (without having to create new xml files etc.)? And if there isn't what exactly do I have to do, in order to make it work?</p>
  
  <p>I use spring with hibernate and mysql, in Netbeans with Maven.</p>