(四)springboot整合mybatis
1、以mysql為例,在pom檔案中新增如下依賴,依次為mybatis、jdbc、db pool依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency>
2、在application.properties 檔案中進行配置,springboot2.0會自動匹配jdbc連線,也可以通過spring.datasource.driver-class-name =com.mysql.jdbc.Driver 進行設定
#資料庫url spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 #使用者名稱、密碼 spring.datasource.username =root spring.datasource.password =root #如果不使用預設的資料來源 (com.zaxxer.hikari.HikariDataSource),配置為阿里資料來源 spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#輸出log到控制檯
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3、設定好之後,我們在資料庫中建立一個user表
CREATE TABLE `user` ( `id` int(15) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(80) DEFAULT NULL COMMENT `使用者姓名`, `phone` varchar(16) DEFAULT NULL COMMENT `使用者手機號`, `createTime` datetime DEFAULT NULL COMMENT `建立時間`, `age` int(4) DEFAULT NULL COMMENT `年齡`, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
4、寫一個domain物件用於dao層操作user表
package com.zc.mybatis.domain; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class User { private int id; private String name; private String phone; private int age; //設定日期格式 @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8") private Date createTime; ......省略get、set方法
5、建立介面類,用註解方式運算元據庫
/** * */ package com.zc.mybatis.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.zc.mybatis.domain.User; public interface UserMapper { //新增使用者
@Insert(“INSERT INTO user(name,phone,createTime,age) VALUES(#{name}, #{phone}, #{createTime},#{age})”)
@Options(useGeneratedKeys=true, keyProperty=”id”, keyColumn=”id”) //主鍵自增,生成的值將注入物件中
void insertUser(User user) throws Exception;
//查詢使用者 @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(int id); //查詢所有使用者 List<User> getUsers(); //更新使用者 @Update("UPDATE user SET name=#{name},phone=#{phone},createTime=#{createTime},age=#{age} WHERE id =#{id}") void updateUser(User user); //刪除使用者 @Delete("DELETE FROM user where id = #{id}") void deleteUserById(int id); }
6、建立對應的servce層,對應增刪改查對應寫出方法就可以了,我這裡只寫介面實現,其中需要注意的是,userMapper需要通過IOC注入進行使用
@Autowired private UserMapper userMapper; //增 @Override public int add(User user) { try { userMapper.insertUser(user); } catch (Exception e) { e.printStackTrace(); } int id = user.getId(); return id; } //查詢 @Override public User getUserById(int id) { User user = userMapper.getUserById(id); return user; } //查詢所有 @Override public List<User> getUsers() { List<User> users = userMapper.getUsers(); return users; } //刪除 @Override public void deleteUserById(Long id) { userMapper.deleteUserById(id); } //改 @Override public void updateUser(User user) { userMapper.updateUser(user); }
7、寫對應controller,然後返回json格式,就可以從頁面檢視了,通過localhost:8080/user/add新增資料到資料庫,然後訪問localhost:8080/user/getUsers
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("add") public int add() { User user = new User(); user.setAge(12); user.setName("張三"); user.setPhone("888888888"); user.setCreateTime(new Date()); int id = userService.add(user); return id; } @GetMapping("getUserById") public User getUser(int id) { User user = userService.getUserById(id); System.out.println(user.getCreateTime().toString()); return user; } @GetMapping("getUsers") public List<User> getUsers() { List<User> users = userService.getUsers(); User user = null; for (int i = 0; i < users.size(); i++) { user = users.get(i); System.out.println("使用者id:" + user.getId() + "姓名" + user.getName()); } return users; } @GetMapping("deleteUserById") public void deleteUserById(Long id) { User user = null; int userId = Integer.parseInt(id.toString()); user = userService.getUserById(userId); userService.deleteUserById(id); System.out.println("刪除使用者的使用者名稱為:" + user.getName()); } @GetMapping("addAcount") public void addAcount() { int id = userService.addAcount(); } }