Java 在 Spring Boot 中创建新的实体对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52818595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:37:36  来源:igfitidea点击:

Create new Entity Object in Spring Boot

javaspringhibernatespring-bootspring-data-jpa

提问by 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 newin 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.

我希望有人能更清楚地了解我在 Spring Boot 项目中对 JPA 实体的困惑。我听说永远不应该调用newSpring 项目。我理解这是为了让 Spring 管理所有的 bean,并且可以通过注入或通过应用程序上下文显式地获取 bean。

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

但是,我不清楚如何获得新的 JPA 实体。如果我有一个注释的类@Entity和一个处理我的数据访问的存储库类,我如何在我的服务层中获取一个新的实体对象?

I've included @EntityScanin 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 @Entityannotated 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.

我已经包含@EntityScan在我的应用程序的主类中,所以我假设 Spring 知道该实体。但是当我尝试通过 ApplicationContext 获取它时,会引发异常。这是有道理的,因为我不相信带@Entity注释的类是 Spring Bean,而且我认为用@Component. 任何澄清将不胜感激。

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

我目前正在使用new关键字并在服务层中自己创建实体对象。一个非常简单的例子如下:

entities/User.java

实体/用户.java

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

    // Getters & Setters ...
}

repositories/UserRepository.java

存储库/UserRepository.java

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

services/UserServiceImpl.java

服务/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 newkeyword 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?

在此示例中,我显式调用new了服务类方法中的关键字createAndSaveUser。这是正确的方法还是我应该从 Spring 获取一些映射到我的 JPA 实体的原型 bean?

采纳答案by 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 canbe autowired.

在 spring 中,您可以自动装配/注入 bean、组件或服务。然而,实体不应自动装配,因为这些交互是通过您的存储库完成的。您的存储库可以自动装配。

When you want to create a new instance of your entity you are allowedto 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.

当您想创建实体的新实例时,您可以调用new,因为这不需要由 spring 管理。您可以简单地使用自动装配的存储库将其保存在数据库中。这也适用于其他方式,因为显然您需要自动装配的存储库来检索您的实体。

So yes, your method is correct.

所以是的,你的方法是正确的。

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

我希望这对您来说更清楚,如果您有任何问题,请随时提问:)

回答by kj6682

It sounds good to me: you create your entity and then ask the repository to store it.. no problem with Spring.

这对我来说听起来不错:您创建了实体,然后要求存储库存储它...... Spring 没有问题。

have you checked this out? :

你检查过吗?:

http://spring.io/guides/gs/accessing-data-jpa/

http://spring.io/guides/gs/accessing-data-jpa/

have fun

玩得开心

回答by Vikash Kumar

Whatever you are doing is completely valid in spring. In example you have provided above I could figure out that you want your entity class object itself to store the values. Its absolutely correct. You have to use newkeyword to achieve that. If you still wish to not create a new object for your Entity you have another option to do it through Bean/POJO/VO classes and mapping your entity object with these classes.

无论你在做什么,在春天都是完全有效的。在上面提供的示例中,我可以确定您希望实体类对象本身存储值。它绝对正确。你必须使用new关键字来实现这一点。如果您仍然不希望为您的实体创建一个新对象,您还有另一种选择,通过 Bean/POJO/VO 类并将您的实体对象映射到这些类。

But Still i will tell that whatever you have done is completely fine.

但我仍然会告诉你,你所做的一切都很好。

Actually the object you are creating is for storing value purpose not just because you have some method is there in your class and so you are bound to create newObject to be able to call that method(As we do in normal java project).In spring that is handle by @Autowiredannotation to create object. Simple example is you will be auto-wiring your repositories in your service classes.

实际上,您正在创建的对象是用于存储值的目的,而不仅仅是因为您的类中有一些方法,因此您必须创建new对象才能调用该方法(就像我们在普通 Java 项目中所做的那样)。在 spring即通过@Autowired注解处理来创建对象。简单的例子是你将在你的服务类中自动连接你的存储库。

I hope this help.

我希望这会有所帮助。