springboot+mybatis整合(入门)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值