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