public class Customer {
private long id;
private String firstName, lastName;
public Customer(long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
控制器:
@Controller
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
Customer customer;
@RequestMapping("/hello")
public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
model.addAttribute("name", name);
return "hello";
}
@RequestMapping("/getMock")
public String getMock(Model model) {
JdbcTemplate mock = Mockito.mock(JdbcTemplate.class);
List fakeList = new ArrayList<>();
fakeList.add(new Customer(1l, "sth", "sth2"));
Mockito.when(mock.query(any(String.class), any(RowMapper.class))).thenReturn(fakeList);
List<Customer> mockResult = mock.query(
"SELECT id, first_name, last_name FROM customers",
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
);
String result = null;
for(Customer customer : mockResult) result += (customer.toString() + "<br>");
model.addAttribute("mockString", result);
return "hello";
}
@RequestMapping("/getDatabase")
public String getDatabase(Model model) {
List<Customer> list = jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers",
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
);
String result = null;
for (Customer customer : list) result += (customer.toString() + "<br>");
model.addAttribute("databaseString", result);
return "hello";
}