Java Spring Boot是否提供查询构建器,例如php CodeIgniter查询构建器 [英] Does java spring boot provides query builder like php CodeIgniter query builder

查看:57
本文介绍了Java Spring Boot是否提供查询构建器,例如php CodeIgniter查询构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在春季启动中开发一个应用程序,该应用程序将在运行时创建动态表单并将其发布到我们的应用程序中,以JSON格式将表单数据发布到db(MySql)中.我们想要创建一个通用的api来处理所有动态表单的CRUD操作.

We are developing an application in spring boot, where we will be creating and publishing dynamic forms into our application at runtime to post the form-data into the db (MySql) in JSON format. We want to create a generic api to handle CRUD operations for all dynamic forms.

我们了解php代码点火器框架查询构建器,该构建器能够构建和执行查询.

We know about the php code-igniter framework query builder, which is capable to build and execute the queries.

https://www.codeigniter.com/userguide3/database /query_builder.html#inserting-data

例如:

$query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable

        $data = array(
    'title' => 'My title',
    'name' => 'My Name',
    'date' => 'My date'

); $ this-> db-> insert('mytable',$ data);

); $this->db->insert('mytable', $data);

在Java Spring Boot中,是否有任何方法(任何插件或Maven依赖项)执行相同的操作(与php代码点火器一样).

Is there any way (any plugin or maven dependency) to do the same (as php code-igniter) in java spring boot.

        Map<String, String> map = new TreeMap<>();
    map.put("name","User Name");
    map.put("dob", "30-3-1995");
    map.put("address", "Address Line");
    map.put("city", "Jaipur");
    /* insert into user table */
    db.insert("user",map);

推荐答案

有几种方法可以实现类似的功能:

There are few ways to achieve similar functionality:

  1. 使用Spring Data JPA (最常用)

此模块基于约定从该方法生成(或派生)查询,例如:

This module generates (or derives) queries from the method based on convention, for example:

interface UsersRepository extends CrudRepository<User, Long> {
  List<User> findByLastname(String lastname);
}

呼叫personRepository.findByLastName("Doe")可以转换为:

SELECT * FROM users WHERE last_name = 'Doe'

然而,为了使Spring做到这种魔术,它需要映射原始"对象返回的结果集.对对象的SQL查询.这就是ORM概念出现的地方.因此,您需要执行一个附加步骤:配置实体(将是您的对象)并在它们之间建立所需的关系.例如:

However, for Spring to do that sort of magic it needs to map the result set returned by a "raw" SQL query to an object. This is where the concept of ORM comes in. Because of that, you need to do an additional step: configure entities(that would be your objects) and set up the desired relationship between them. For example:

@Entity
@Table(name = "users")
public class User {
  @Id
  private String id;
  @Column(name = "first_name")
  private String firstName;
  @Column(name = "last_name")
  private String lastName;
  //constructor, getters and setters
}

现在,Spring知道如何将列映射到对象,并会自动为您生成查询.更准确地说,它是通过后台的(ORM框架)休眠来完成的,但不要让术语使您感到困惑.我建议您更多地搜索有关Spring Data JPA,JPA和Hibernate的信息,因为它不在本问题的讨论范围之内.

Now Spring knows how to map columns to an object and would generate query automatically for you. To be more precise, it's done by hibernate (that the ORM framework) under the hood, but don't let terminology confuse you. I would suggest googling a little bit about Spring Data JPA vs JPA vs Hibernate more since it's out of the scope of this question.

春季指南上有一个很好的初学者教程.您也可以在官方文档此处.

There is a good beginner tutorial available at Spring Guides. You can also read about it more in the official documentation here.

使用Spring JdbcTemplate

它可能与CodeIgniter的功能更相似,但jdbcTemplate并未使用内部API",而是使用了原始"代码. SQL语句:

It's probably more similar to what CodeIgniter does, but instead of using "internal API", jdbcTemplate uses "raw" SQL statements:

jdbcTemplate.query(
    "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
    (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
).forEach(customer -> log.info(customer.toString()));

但是,如您所见,它会返回一个需要手动映射域对象的结果集.

However, as you can see, it returns a result set where you need manually map your domain object.

可在春季指南中找到该代码示例. 此处.

The code example is available at Spring Guides. More documentation is available here.

还有其他选择,例如 jOOQ QueryDSL .

The are other alternatives such as jOOQ, MyBatis, and QueryDSL.

就我个人而言,除了"Spring Data JPA"之外,我没有遇到任何其他方法.在生产"中尽管我对前两个应用程序非常熟悉,但是我从事过的应用程序开发工作(可能是由于它更接近Java代码,并且在内部隐藏了许多SQL内部结构).由于其受欢迎程度,我建议您选择第一个,但最终取决于您.

Personally, I have not encountered any of the approaches except "Spring Data JPA" in "production" applications I worked on (probably due to the fact that it's closer to the Java code and hides a lot of SQL internals under the hood), although very familiar with the first two. I would recommend going with the first one due to its popularity, but it's ultimately up to you.

由于该答案超出了您决定选择哪个答案的范围,因此我会发布一些其他链接:

Since it's out of the scope of that answer to decide which one you should pick, I would post some additional links:

  • JPA vs Spring JdbcTemplate
  • Spring Data vs Spring Data JPA vs JdbcTemplate

更新 :(解决评论)

我仍然会争辩说,即使您的表单是动态的",您的表架构也是固定的".自然地.您可以:

I still would argue that even your forms are "dynamic", your table schema is "fixed" by nature. You can:

  1. 使用JPA实体来映射固定的"实体.字段(例如ID,时间戳等).创建dynamicForm字段作为该实体的一部分-它将包含json字符串->这将是"TEXT"在数据库中输入:

  1. Use JPA Entity to map "fixed" fields (such as id, timestamp maybe, etc.). Create dynamicForm field as a part of this Entity - it would contain a json string -> which would be "TEXT" type in DB:

@Entity
@Table(name = "forms")
public class FormEntity {
  @Id
  private String id;
  private LocalDateTime created;
  @Column(name = "dynamic_form")
  private String dynamicForm;
  //constructor, getters and setters
}

  • 在Java中,将地图(具有示例中的任何键值)创建为单独的类

  • In Java, create your map (with whatever key-values as in your example) as a separate class

    使用Jackson的ObjectMapper对其进行序列化以字符串化(可能是json).

    Serialize it using Jackson's ObjectMapper to string (which would be a json).

    将其映射到您实体的"dynamicForm",字段:

    Map it to your Entity's "dynamicForm" field:

    public class MyBusinessLogicService {
      public void processForm(Map<String, String> map) {
          FormEntity formEntity = new FormEntity();
          formEntity.setDynamicForm(objectMapper.writeValueAsString(yourMap));
          //.... setting other values
          formEntityRepository.save(formEntity);
      }
    }
    

  • 阅读表格时,您将反序列化dynamicForm字段.

    解决方案不受地图限制,但是您可以存储任何类型的对象.您这一方面的挑战将是要知道哪种类型的对象"是对象".存在于那里.如果是地图,您将不了解地图内部的键值.

    The solution is not limited by a map, but you can store any type of object. The challenge on your side would be to know what type of "object" is present in there. If it's a map, you would have no knowledge of the key-values that are inside of the map.

    这篇关于Java Spring Boot是否提供查询构建器,例如php CodeIgniter查询构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆