Create new Entity Object in Spring Boot

Jon Catanio :

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 new 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.

However, it's not clear to me how to get a new JPA Entity. If I have a class annotated with @Entity and a repository class that handles my data access, how do I obtain a new entity object in my service layer?

I've included @EntityScan 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 @Entity annotated classes are Spring Beans, and I don't think it would be correct to also annotate it with @Component. Any clarification would be greatly appreciated.

I'm currently using the new keyword and creating the entity objects myself in the service layer. A very simple example is below:

entities/User.java

@Entity
@Table(name = "users")
public class User {
    @Id
    private Long id;
    private String username;

    // Getters & Setters ...
}

repositories/UserRepository.java

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
    User findByUsername(String username);
}

services/UserServiceImpl.java

@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);
    }
}

And we could assume that there was some other controller classes that would utilize the service layer.

In this example I am explicitly calling the new keyword in the service class method createAndSaveUser. Is this the correct way to do it or should I be getting some prototype bean from Spring that maps to my JPA entity?

Sven Hakvoort :

In spring you can autowire/inject your beans, components or services. However the entity should not be autowired since these interactions are done through your repository. Your repository can be autowired.

When you want to create a new instance of your entity you are allowed to call new, because this does not need to be managed by spring. You can simply use the autowired repository to save it in the database. This also works the other way around because obviously you would need the autowired repository to retrieve your entity.

So yes, your method is correct.

I hope this makes it clearer for you, if you have any questions feel free to ask :)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73940&siteId=1