1、使用idea创建springboot项目 选择web、mybatis
或者在pom.xml增加
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、编写Mapper
使用到的注解有:@Mapper
@Mapper
public interface User2Mapper {
/**
* 2017年7月6日12:31:11
* 根据id获得用户信息
*
* @param id
* @return User
*/
@Select("SELECT id,name,age FROM user WHERE id=#{id}")
User findById(@Param("id") Integer id);
/**
* 2017年7月6日12:31:11
* 新增用户信息
*
* @param user
* @return User
*/
@Transactional
@Insert("INSERT INTO user(name,age) VALUES(#{name},#{age})")
@Options(useGeneratedKeys = true,keyProperty = "id")
int insertUserInfo(User user);
@Update("UPDATE user SET name=#{name},age=#{age} WHERE id=#{id}")
int updateUserInfo(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
int deleteUserInfoById(Integer id);
}
//结果返回map
@Mapper
@Component
public interface BaseMapper {
@Select("select * from base_person where del_flag='0' and status2='0' limit 10")
@MapKey("id")
Map<Long, Map<String, Object>> queryBasePerson();
}
3、接口和接口实现
定义一个接口UserService
定义一个接口的实现使用注解@Service声明 Service
@Autowired 将定义好的Mapper注入
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Autowired
User2Mapper user2Mapper;
public List<User> findList() {
return userMapper.findUserInfo();
}
public User findById(Integer id){
return user2Mapper.findById(id);
}
@Transactional
@Override
public int insertUserInfo(User user) {
try {
User user1= new User();
user1.setName("1");
user1.setAge(1);
user2Mapper.insertUserInfo(user1);
return user2Mapper.insertUserInfo(user);
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
4、在Controller里面使用@Autowired 调用即可
5、在application.yml增加数据库配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/hshk
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
源码托管在:http://git.oschina.net/luweiwei/SpringbootMybatisDemo/tree/master