如何在spring boot controller中执行sql语句?

时间:2018-03-26 09:57:18

标签: java mysql spring spring-boot uuid

我想在spring boot controller类中执行sql语句,而不是在jpa存储库中定义任何方法。我想要使​​用的陈述是

SELECT UUID();

此声明与数据库相关,并且与特定实体无关。

如果任何人可以通过

为上述声明的执行提供解决方案,那就太好了
  1. spring controller class
  2. jpa存储库(如果推荐)
  3. 更新

    控制器:

    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @RequestMapping(value = "/UUID", method = RequestMethod.GET)
    public ResponseEntity<String> getUUID() {
        String uuid = getUUID();
        return buildGuestResponse(uuid);
    }
    
    public String getUUID(){
        UUID uuid = (UUID)jdbcTemplate.queryForObject("select UUID()", UUID.class);
        return uuid.toString();
    }
    

3 个答案:

答案 0 :(得分:5)

您可以在代码中使用JdbcTemplate。

配置类中需要的bean是: -

<form method="post" action="tea_appview.php">
<table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">
<!--      <table cellpadding="0" cellspacing="0" border="0" class="table table-bordered" id="example">  -->
    <thead>
        <tr>
            <th>appoinment ID</th>
            <th>Date</th>
            <th>time</th>
            <th>subject</th>
            <th>Appointment from [parent]</th>
            <th>Appointment to (teacher) </th>
            <th> accept/reject </th>
            <th>state</th>
            <th>comm</th>
        </tr>
    </thead>
    <tbody>
    <?php
        $query = mysqli_query($conn, "select * from `app` left join `par` on par.par_id=app.par_id left join `tea` on tea.tea_id=app.tea_id ORDER BY app_id DESC");
        if ($query === false) {
            throw new Exception(mysqli_error($conn));
        }
        while ($row = mysqli_fetch_array($query)) {
            $ann_id = $row['app_id'];
            $date = $row['date'];
            $msg = $row['time'];
            $username = $row['username'];
            $username = $row['p_username'];
            $sub = $row['sub'];
    ?>
        <tr>
            <td><?php echo $row['app_id'] ?></td>
            <td> <?php echo date('j/m/y', strtotime($row['date'])); ?></td>
            <td><?php echo $row['time'] ?></td>
            <td><?php echo $row['sub'] ?></td>
            <td><?php echo $row['p_username'] ?></td>
            <td><?php echo $row['username'] ?></td>
            <td>
                <a href="tea_appview.php?app_id=<?php echo $row['app_id'] . "&" . "state=reject"; ?>" class="reject">reject</a>
                <a href="tea_appview.php?app_id=<?php echo $row['app_id'] . "&" . "state=accept"; ?>" class="accept">accept</a> 
            </td>
            <td><?php echo $row['state'] ?></td>
            <td><input type="text" name="comm">
                <input type="submit" name="submit" value="submit">
            </td>
        </tr>
        <?php
            //---------PROBLEM IS HERE-----------------------
            //if(isset($_GET['app_id'], $_POST['submit'])!="")
            if (isset($_GET['app_id']) && $_POST['submit'] != ""){
                $stmt = mysqli_prepare($conn, "UPDATE app SET comm = ? WHERE app_id = ?");
                mysqli_stmt_bind_param($stmt, "sd", $_GET['comm'], $_GET['app_id']);
                $stmt->execute();
                $stmt->close();
            }
            //-------------------------------
            if (isset($_GET['state'], $_GET['app_id'])) {
                $stmt = mysqli_prepare($conn, "UPDATE app SET state = ? WHERE app_id = ?");
                mysqli_stmt_bind_param($stmt, "sd", $_GET['state'], $_GET['app_id']);
                $stmt->execute();
                $stmt->close();
            }
        }
        ?>
    </tbody>
</table>

运行查询的代码是: -

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource)
{
    return new JdbcTemplate(dataSource);
}

或者可能是这样的: -

@Autowired
private JdbcTemplate JdbcTemplate;

public String getUUID(){
    UUID uuid = (UUID)jdbcTemplate.queryForObject("select UUID()", UUID.class);
    return uuid.toString();
}

答案 1 :(得分:2)

JEE applications中,在表示层(控制器或视图)上执行任何SQL(执行任何持久性)通常都是架构上糟糕的设计。

最佳选择是让控制器使用服务层,当服务层调用持久层时:获取,保存或更新数据。

无论如何,您可以使用Spring Data JDBC。类似的东西:

import org.springframework.jdbc.core.JdbcTemplate;

....
 UUID uuid = (UUID)jdbcTemplate.query("SELECT UUID()", UUID.class);
....

答案 2 :(得分:1)

我可以举一个小例子,我是如何使用spring数据在spring框架中执行此操作的。

控制器类:

@RestController
@RequestMapping("api/account")
public class AccountController {
  private AccountService accountService;

  @RequestMapping(
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE,
        path = "{id}"
  )
  public ResponseEntity getAccountId(@PathVariable("id") UUID id) {
    try {
        Account ac = accountService.findOne(id);
        return new ResponseEntity(ac, HttpStatus.OK);
    } catch (Exception ex) {
        return new ResponseEntity("Account not found.", HttpStatus.NOT_FOUND);
    }
}

在这个小例子中,我有AccountController和AccountService,它是一个扩展JpaRepository接口的接口。帐户对象是自制对象。通过使用JpaRepository接口,您不需要自己编写SQL语句。相反,您需要提供有效的模型对象和标识符(在我的例子中为UUID)。

以下是Account对象的一个​​小示例:

@Entity
public class Account {

  private @Id @GeneratedValue(generator = "uuid2") UUID id;
  private String firstName, lastName, description;

  private Account() {}

  public Account(String firstName, String lastName, String description) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.description = description;
  }
}  

有关如何使用弹簧数据的更多示例,我建议您按照website上的快速入门指南进行操作。

希望它有所帮助!