代码之家  ›  专栏  ›  技术社区  ›  Iraponti

Spring-JPA-Hibernate如何使用EntityManager

  •  1
  • Iraponti  · 技术社区  · 7 年前

    我正在努力建造 REST 使用以下技术堆栈的应用程序:

    • 春天
    • VueJs
    • JPA(休眠)

    这是我第一次全面地编写Sping应用程序和web应用程序开发。

    我的数据库中有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方法修改(或不修改)我的数据库,并返回 HTML VueJS 部分但是我的方法需要一个EntityManagerFactory,我应该在每个Controllers类中创建一个字段,还是不应该这样做?
    2. 我是否需要创建一个bean文件并对其进行配置,或者 persistence.xml pom.xml 够了吗?

    谢谢

    3 回复  |  直到 7 年前
        1
  •  2
  •   shinjw    7 年前

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

    当我为每个表创建控制器时,我使用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文件并配置它或持久性。xml和pom。xml足够了吗?

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

    在您的 main/src/resources (您应该有 application.properties application.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.
    

    春天为你们们带来了很多魔力和沉重的负担。

        2
  •  2
  •   Jayesh Choudhary    7 年前

    如果您使用的是spring Boot,则不需要实体管理器。您只需定义 数据来源 在属性文件中。并在配置类中创建一个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'
    
        3
  •  0
  •   Malakai ssk    7 年前

    你一定要看看 Spring Boot ( http://start.spring.io ),它可以更轻松地启动web应用程序开发。至于持久层,您可以使用 Spring Data JPA (已经包括Hibernate)模块,该模块也可以轻松地与Spring Boot集成。默认情况下已经编写的Spring数据的美妙之处大多数查询如下 save(), remove(), find() 等等您只需要定义将由弹簧数据使用的对象。

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