Spring JDBCTemplate:如何从Spring Controller调用MySQL模式中的View

时间:2017-12-06 16:10:30

标签: spring jdbctemplate

我在MySQL架构中有一个View已经执行了以下操作: 我的问题是如何使用jdbctemplate调用该视图?

    // insert person into database
    jdbcTemplate.update(
        "INSERT INTO Person (FirstName, LastName, Address, Phone, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?)",
        person.getFirstName(), person.getLastName(), person.getAddress(), person.getPhone(), person.getCity(), person.getState(), person.getZipCode()
    );

    // get this persons generated id from the DB
    int personId = jdbcTemplate.queryForObject(
        "SELECT Id FROM Person WHERE FirstName=? AND LastName=?", new Object[]{person.getFirstName(), person.getLastName()}, int.class);

    // create user account for person
    jdbcTemplate.update(
        "INSERT INTO User (person_Id, active, username, password) VALUES (?, ?, ?, ?)",
        personId, 1, username, password
    );

    int userId = jdbcTemplate.queryForObject(
        "SELECT user_id FROM User WHERE username=? AND password=?", new Object[]{username, password}, int.class);

    // finally add role to user
    // by default, all users are set to Customer roles.
    jdbcTemplate.update(
        "INSERT INTO User_role (user_id, role_id) VALUES (?, ?)",
        userId, Role.CUSTOMER_ROLE
    );

1 个答案:

答案 0 :(得分:0)

在选择数据时,可以像在JDBC中的任何其他表一样访问

Views。所以,像下面这样的东西对我们来说很好。

 int personId = jdbcTemplate.queryForObject(
        "SELECT Id FROM Our_View WHERE FirstName=? AND LastName=?", new Object[]{person.getFirstName(), person.getLastName()}, int.class);

但是,对于Mysql中的Updatable和Insertable视图,请参阅here