<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.21version>
dependency>
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '用户名称',
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
@RestController
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/insertUser")
public String insertUser(String name,Integer age){
int update = jdbcTemplate.update("insert into users values(null,?,?);", name, age);
return update > 0 ? "success" : "false";
}
}
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.1.1version>
dependency>
public class UserEntity {
private String userName;
private Integer age;
private Integer id;
//GET...SET...省略
}
public interface UserMapper {
@Select("select id as id,name as userName,age as age from users where id = #{id};")
UserEntity selectByUserId(@Param("id") Integer id);
}
@RestController
public class UserService {
@Autowired
private UserMapper userMapper;
@RequestMapping("/mybatisFindById")
public UserEntity mybatisFindById(Integer id){
return userMapper.selectByUserId(id);
}
}
@MapperScan("com.sjyl.mapper")
来告诉spring接口mapper的扫包范围@SpringBootApplication
@MapperScan("com.sjyl.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
}
}
public interface UserMapper {
@Insert("Insert into users values (null,#{userName},#{age});")
int insertUser(@Param("userName") String userName,@Param("age") Integer age);
@Select("select id as id,name as userName,age as age from users where id = #{id};")
UserEntity selectByUserId(@Param("id") Integer id);
}
@RestController
public class UserService {
@Autowired
private UserMapper userMapper;
@RequestMapping("/mybatisFindById")
public UserEntity mybatisFindById(Integer id){
return userMapper.selectByUserId(id);
}
@RequestMapping("/insertUserMybatis")
public String insertUserMybatis(String userName,Integer age){
int insert = userMapper.insertUser(userName,age);
return insert > 0 ? "success" : "false";
}
}
测试连接:http://127.0.0.1:8080/insertUserMybatis?userName=%E5%BC%A0%E4%B8%89&age=21