title: Create new Entity Object in Spring Boot
body: <p>I'm hoping someone could shed some more light on my confusion with JPA entities in a Spring Boot project. I've heard that one should never call <code>new</code> in a Spring project. I understand that this is to allow Spring to manage all of the beans, and getting a bean can be done through injection or through the application context explicitly.</p>
  
  <p>However, it's not clear to me how to get a new JPA Entity. If I have a class annotated with <code>@Entity</code> and a repository class that handles my data access, how do I obtain a new entity object in my service layer?</p>
  
  <p>I've included <code>@EntityScan</code> in my application's main class so I would assume that Spring is aware of the entity. But when I try to get it through the ApplicationContext an exception is raised. This makes sense because I don't believe the <code>@Entity</code> annotated classes are Spring Beans, and I don't think it would be correct to also annotate it with <code>@Component</code>. Any clarification would be greatly appreciated.</p>
  
  <p>I'm currently using the <code>new</code> keyword and creating the entity objects myself in the service layer. A very simple example is below:</p>
  
  <h3>entities/User.java</h3>
  
  <pre><code>@Entity
  @Table(name = "users")
  public class User {
      @Id
      private Long id;
      private String username;
  
      // Getters &amp; Setters ...
  }
  </code></pre>
  
  <h3>repositories/UserRepository.java</h3>
  
  <pre><code>@Repository
  public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
      User findByUsername(String username);
  }
  </code></pre>
  
  <h3>services/UserServiceImpl.java</h3>
  
  <pre><code>@Service
  public class UserServiceImpl implements UserService {
      UserRepository userRepository;
  
      @Autowired
      public UserServiceImpl(UserRepository userRepository) {
          this.userRepository = userRepository;
      }
  
      public void createAndSaveUser(String username) {
          User user = new User();
          user.setUsername(username);
  
          userRepository.save(user);
      }
  }
  </code></pre>
  
  <p>And we could assume that there was some other controller classes that would utilize the service layer.</p>
  
  <p>In this example I am explicitly calling the <code>new</code> keyword in the service class method <code>createAndSaveUser</code>. Is this the correct way to do it or should I be getting some prototype bean from Spring that maps to my JPA entity?</p>