Spring - JPA - Hibernate如何使用EntityManager

问题描述 投票:1回答:3

我正在尝试使用以下技术堆栈构建REST应用程序:

  • 弹簧
  • VueJs
  • PSD(休眠)

这是我第一次总体上编写Sping应用程序和Web应用程序开发的经验。

我的DataBase中有4个表:

  • 语言
  • 句子
  • 规则
  • 用户

例如,在规则中有:

Rule create(EntityManagerFactory factory, String type, String hint, String help, Language language); 
List<Rule> readAll(EntityManagerFactory factory);
Rule readID(EntityManagerFactory factory, int id); 
void update(EntityManagerFactory factory, String type, String hint, String help, Language language);

所以有我的问题:

  1. 当我为每个表创建控制器时,我使用CRUD方法修改(或不修改)我的数据库,并返回我的HTMLVueJS部分的视图。但我的方法需要一个EntityManagerFactory,我应该在每个Controllers类中创建一个字段,或者这不是我应该怎么做的?
  2. 我需要创建一个bean文件并对其进行配置,还是persistence.xmlpom.xml就足够了?

谢谢

java spring hibernate jpa vue.js
3个回答
2
投票

似乎您的第一个问题可以分解为多个问题。

当我为每个表创建控制器时,我使用CRUD方法来修改(或不修改)我的数据库,并返回我的HTML和VueJS部分的视图。但我的方法需要一个EntityManagerFactory,我应该在每个Controllers类中创建一个字段,或者这不是我应该怎么做的?

由于您已经接受了建议使用spring-data-jpa的答案。您将处理实体和存储库。

实体是JPA托管bean,它将与您的数据库进行交互。

@Entity
@Table(name = "rule")
public class Rule {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    long id;
    String type;
    ...
    @OneToOne
    @JoinColumn(...)
    Language language;
}

存储库将提供对数据库执行操作所需的所有必要操作。使用JPA,您可以创建一个扩展CrudRepository的接口,它将为您提供一些免费的CRUD操作。 findOne(/* id */)delete()save()

@Repository
public interface RuleRepository extends CrudRepository<Rule, Long> {

     // You can easily specify custom finders
     public List<Rule> findByType(String type);

}

但我的方法需要一个EntityManagerFactory,我应该在每个Controllers类中创建一个字段,或者这不是我应该怎么做的?

通常不赞成将请求/响应对象作为JPA实体。请参阅should i use jpa entity in rest request and/or response的链接答案

您可以采取多种方法来获取控制器请求并将响应发送到客户端项目。

@Controller
public class RuleController {
    @Autowired
    private RuleRepository ruleRepository;

    // Approach 1: Use Request Parameters - enforce inputs
    @PostMapping("/rule/:id")
    public Rule postWithRequestParams(@PathParam("id") Long id, 
                    @RequestParam("type") String type, 
                    @RequestParam("hint") String hint, 
                    @RequestParam("languageField1") String languageField1) {
        Rule inputRule = new Rule(id, type, hint, new Language(languageField1));

        Rule responseRule = ruleRepository.save(inputRule);
        return responseRule; // I would imagine you would want to set up a model for the response itself
    }



    // Approach 2: Use RequestBody - serialize Rule from the request
    @PostMapping("/rule/:id")
    public Rule postWithRequestParams(@PathParam("id") Long id, @RequestBody Rule inputRule) {
        Rule responseRule = ruleRepository.save(inputRule);
        return responseRule;
    }

我是否需要创建一个bean文件并对其进行配置,或者persistence.xml和pom.xml是否足够?

如果您已将spring-boot-starter-data-jpa添加为依赖项,则已经为您完成了很多bean配置。

在你的main/src/resources(你应该有一个application.propertiesapplication.yml

spring.datasource.url= # JDBC url of the database.
spring.datasource.username= # Login user of the database.
spring.datasource.password= # Login password of the database.

Spring为你做了很多神奇而繁重的工作。


2
投票

如果您使用的是spring Boot,那么您不需要实体管理器。您需要做的就是在属性文件中定义数据源。并在我们的Configuration类中创建一个Bean,就像:

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource datasource() {
    return DataSourceBuilder.create().build();
}

现在你可以用存储库处理的其他东西。它们将是:

import org.springframework.data.repository.CrudRepository;

public interface RuleRepository extends CrudRepository<Rule, Long>  {

}

在您的控制器中,您将使用它:

@Autowired
private RuleRepository ruleRepository;

@Get
@Path("/getRule/:id")
public Rule find(@PathParam("id")Long id){
    return ruleRepository.findOne(id);
}

我在gradle项目中使用的这些依赖项。你会发现相同的Maven版本:

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile group: 'mysql', name: 'mysql-connector-java'

0
投票

你肯定需要看看Spring Boothttp://start.spring.io),它允许更容易启动Web应用程序开发。至于持久层,你可以使用Spring Data JPA(已经包含Hibernate)模块,它也可以很容易地与Spring Boot集成。 Spring Data的优点已经默认编写了大多数查询,如save(), remove(), find()等。您只需要定义将由Spring Data使用的对象。

更新:请参阅我的Spring Boot REST API示例here

© www.soinside.com 2019 - 2024. All rights reserved.