springboot+mybatis整合(入門)

來源:互聯網
上載者:User

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

@Mapperpublic 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);}

3、介面和介面實現
定義一個介面UserService
定義一個介面的實現使用註解@Service聲明 Service
@Autowired 將定義好的Mapper注入

@Servicepublic 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.