Blog index

#{} is used as a placeholder for a PreparedStatement in JDBC. PreparedStatement is a PreparedStatement in JDBC.

PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?" ); PSTMT. SetBigDecimal (1, 153833.00) PSTMT. SetInt (2, 110592)Copy the code

1. Suppose

So how does #{} in Mybatis accomplish the effect of precompilation? #{} #{} #{} #{} #{} #{} Placeholder.

2. Verify

Let’s write an example to debug. Let’s use a query as an example

@Data

public class A {

private Integer id;

private Integer age;

private String name;

private Date createTime;

}

Copy the code

The Mapper is as follows


@Mapper

public interface ADAO {

@Select("SELECT * FROM A WHERE id = #{id}")

A selectA(int id);

}

Copy the code

The test class ADAOTest


@RunWith(SpringRunner.class)

@SpringBootTest

public class ADAOTest {

@Autowired

private ADAO adao;

@Test

public void selectA() {

A a = adao.selectA(2);

System.out.println(a);

}

Copy the code

@select Execution principle

Here only in key areas on a breakpoint, org. Apache. Ibatis. Builder. SqlSourceBuilder# parse

Are placeholders done? Replacement, the next step is to obtain a PreparedStatement, in org. Apache. Ibatis. Executor. SimpleExecutor# prepareStatement.

The core steps are highlighted here, so if you’re interested, you can click on a breakpoint to see the details

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { Statement stmt; Connection connection = getConnection(statementLog); PrepareStatement (SQL) STMT = handler.prepare(Connection, transaction.getTimeout()); // This step performs the fill parameter stmt.setint (1," XXX "); handler.parameterize(stmt); return stmt; }Copy the code

The last query execution org. Apache. Ibatis. Executor. Statement. PreparedStatementHandler# query


public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {

PreparedStatement ps = (PreparedStatement) statement;

ps.execute();

return resultSetHandler.<E> handleResultSets(ps);

}

Copy the code

3. Summary

The mybatis custom placeholder #{} was replaced with a JDBC placeholder.

So, in fact, can be summarized, in fact, all ORM framework, the underlying principle is the JDBC standard.

So whether it is placeholder in Mybatis or placeholder in JPA, the final execution process is resolved into? This placeholder, don’t ask why, ask this is the standard.