1112_Springboot+Mybaits+Mysql資料庫增刪改查操作——上路
Springboot+Mybaits+Mysql資料庫增刪改查操作
2017.11.03 16:37* 字數 754 閱讀 414評論 0喜歡 4
最近在老師的建議下,參加了一個學習小組,主要了解Spring Cloud微服務架構的應用開發,在初次搭建好環境後,這一次使用Spring boot+Mybatis完成對資料庫的一些簡單操作,作為新手,下面就是我整個做的過程,查閱了許多網上的資料,這裡面很多都是學習別人的東西,自己說的也可能不專業,權當自己記錄複習。
1.任務要求
image.png
image.png
2.工程建立
springboot工程建立就不說了,這裡主要說一下pom.xml檔案新增的依賴,如下:
-
<dependencies>
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-web</artifactId>
-
</dependency>
-
<!--mybatis-->
-
<dependency>
-
<groupId>org.mybatis.spring.boot</groupId>
-
<artifactId>mybatis-spring-boot-starter</artifactId>
-
<version>1.3.1</version>
-
</dependency>
-
<!--pagehelper-->
-
<dependency>
-
<groupId>com.github.pagehelper</groupId>
-
<artifactId>pagehelper-spring-boot-starter</artifactId>
-
<version>1.2.1</version>
-
</dependency>
-
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
-
<dependency>
-
<groupId>org.projectlombok</groupId>
-
<artifactId>lombok</artifactId>
-
</dependency>
-
</dependencies>
還有就是application.yml檔案的資料庫配置:
-
spring:
-
application:
-
name: mysql-service
-
datasource:
-
driver-class-name: com.mysql.jdbc.Driver
-
url: jdbc:mysql://localhost:3306/spring-c?useUnicode=true&characterEncoding=UTF-8
-
username: root
-
password: hui19970201
3.應用檔案建立及說明
新建一個應用,目錄結構如下:
image.png
entity層
(1)根據要求在entity層建立User實體類,內容如下:
-
@Getter
-
@Setter
-
public class User {
-
private String userId;
-
private String userCode;
-
@Max(value = 100, message = "年齡不能大於100歲")
-
@Min(value = 18, message = "必須年滿18歲!")
-
private int age;
-
@Pattern(regexp = "[a-za-z0-9._%+-][email protected][a-za-z0-9.-]+\\.[a-za-z]{2,4}", message = "郵件格式錯誤")
-
private String mail;
-
@Length(min = 11, max = 11, message = "手機號長度必須為11位")
-
private String phone;
-
private int groupId;
-
private Date createTime;
-
private String createBy;
-
private Date modifiedTime;
-
private String modifiedBy;
-
}
(2)根據要求在entity層建立JsonResult實體類,內容如下:
-
@Data
-
public class JsonResult {
-
private Long total;
-
private String message;
-
private boolean status;
-
private Object data;
-
public JsonResult(String message, boolean status) {
-
this.message = message;
-
this.status = status;
-
}
-
public JsonResult(Long total, String message, boolean status) {
-
this.total = total;
-
this.message = message;
-
this.status = status;
-
}
-
public JsonResult(String message, boolean status, Object data) {
-
this.message = message;
-
this.status = status;
-
this.data = data;
-
}
-
public JsonResult(Long total, String message, boolean status, Object data) {
-
this.total = total;
-
this.message = message;
-
this.status = status;
-
this.data = data;
-
}
-
}
(3)一些解釋
首先是用來lombok的註解@Data,@Getter,@Setter減少了程式碼了,就不用那麼多的get和set方法了,當然你也可以使用IDE的generate來生成,隨自己喜好就行,如果使用的是IDEA,這裡注意引入依賴之後還需要下載lombok的外掛,重啟就能生效了;然後就是用Validator,主要是校驗使用者提交的資料的合理性,這裡大家可以百度一下具體的用法,下面是一些常見的註解及實際用法(複製別人的):
-
@null 驗證物件是否為空
-
@notnull 驗證物件是否為非空
-
@asserttrue 驗證 boolean 物件是否為 true
-
@assertfalse 驗證 boolean 物件是否為 false
-
@min 驗證 number 和 string 物件是否大等於指定的值
-
@max 驗證 number 和 string 物件是否小等於指定的值
-
@decimalmin 驗證 number 和 string 物件是否大等於指定的值,小數存在精度
-
@decimalmax 驗證 number 和 string 物件是否小等於指定的值,小數存在精度
-
@size 驗證物件(array,collection,map,string)長度是否在給定的範圍之內
-
@digits 驗證 number 和 string 的構成是否合法
-
@past 驗證 date 和 calendar 物件是否在當前時間之前
-
@future 驗證 date 和 calendar 物件是否在當前時間之後
-
@pattern 驗證 string 物件是否符合正則表示式的規則
-
@Email 驗證郵箱
-
實際例子:
-
@size (min=3, max=20, message="使用者名稱長度只能在3-20之間")
-
@size (min=6, max=20, message="密碼長度只能在6-20之間")
-
@pattern (regexp="[a-za-z0-9._%+-][email protected][a-za-z0-9.-]+\\.[a-za-z]{2,4}", message="郵件格式錯誤")
-
@Length(min = 5, max = 20, message = "使用者名稱長度必須位於5到20之間")
-
@Email(message = "比如輸入正確的郵箱")
-
@NotNull(message = "使用者名稱稱不能為空")
-
@Max(value = 100, message = "年齡不能大於100歲")
-
@Min(value= 18 ,message= "必須年滿18歲!" )
-
@AssertTrue(message = "bln4 must is true")
-
@AssertFalse(message = "blnf must is falase")
-
@DecimalMax(value="100",message="decim最大值是100")
-
DecimalMin(value="100",message="decim最小值是100")
-
@NotNull(message = "身份證不能為空")
-
@Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份證格式錯誤")
dao層
程式碼如下:
-
@Mapper//這裡的Mapper是Mybatis自己定義的註解。
-
public interface UserDao {
-
//插入資料
-
@Insert("insert into user(userId,userCode,age,mail,phone,groupId," +
-
"createTime,createBy,modifiedTime,modifiedBy)" +
-
"values (#{userId,jdbcType=VARCHAR}, #{userCode,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}," +
-
"#{mail,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{groupId,jdbcType=INTEGER}," +
-
"#{createTime,jdbcType=TIMESTAMP}, #{createBy,jdbcType=VARCHAR}, #{modifiedTime,jdbcType=TIMESTAMP}," +
-
"#{modifiedBy,jdbcType=VARCHAR})")
-
void insertUser(User user);
-
//更新資料
-
@Update("update user set userId=#{userId,jdbcType=VARCHAR}," +
-
" userCode=#{userCode,jdbcType=VARCHAR}," +
-
" age=#{age,jdbcType=INTEGER}," +
-
" mail=#{mail,jdbcType=VARCHAR}," +
-
" phone=#{phone,jdbcType=VARCHAR}," +
-
" groupId=#{groupId,jdbcType=INTEGER}," +
-
" createTime=#{createTime,jdbcType=TIMESTAMP}," +
-
" createBy=#{createBy,jdbcType=VARCHAR}," +
-
" modifiedTime=#{modifiedTime,jdbcType=TIMESTAMP}," +
-
" modifiedBy=#{modifiedBy,jdbcType=VARCHAR} where userId=#{userId,jdbcType=VARCHAR}")
-
void updateUser(User user);
-
//根據userId刪除一個使用者的資料
-
@Delete("delete from user where useId = #{useId,jdbcType=VARCHAR}")
-
void deletdUserById(String userId);
-
//根據userCode刪除一個使用者的資料
-
@Delete("delete from user where userCode = #{userCode,jdbcType=VARCHAR}")
-
void deletdUserByCode(String userCode);
-
//根據userCode取出一個使用者的資料
-
@Select("select * from user WHERE userCode = #{userCode,jdbcType=VARCHAR}")
-
User getUserByCode(String userCode);
-
//根據userId取出一個使用者的資料
-
@Select("select * from user WHERE userId = #{userId,jdbcType=VARCHAR}")
-
User getUserById(String userId);
-
@Select("select userCode,age,phone,modifiedTime from user ORDER BY modifiedTime DESC")
-
List<User> getUserList();
-
}
這裡使用mybatis註解的方式@Insert、@Update、@Delete、@Select來進行資料庫的資料庫操作,當然也可使用Mapper對映檔案,我個人覺得簡單的sql操作使用註解,麻煩的還是使用Mapper檔案比較好。這裡推薦幾篇文章。
MyBatis 3(中文版) 第四章 使用註解配置SQL對映器
Mybatis中Mapper對映檔案詳解
service層
程式碼如下:
-
@Service
-
public class UserServices {
-
@Autowired
-
private UserDao userDao;
-
public JsonResult add(User user){
-
User User= userDao.getUserByCode(user.getUserCode());
-
if(User!=null){
-
return new JsonResult("userCode已存在",false);
-
}
-
user.setUserId(UUID.randomUUID().toString());
-
user.setCreateTime(new Date());
-
user.setModifiedTime(new Date());
-
userDao.insertUser(user);
-
return new JsonResult("success",true);
-
}
-
public JsonResult delete(String userId,String userCode){
-
User User=null;
-
if(userId==null&&userCode==null){
-
return new JsonResult("缺少引數userId或userCode",false);
-
}else if(userId==null){
-
User= userDao.getUserByCode(userCode);
-
if(User==null){
-
return new JsonResult("userCode不存在,無法刪除",false);
-
}
-
userDao.deletdUserByCode(userCode);
-
}else {
-
User= userDao.getUserById(userId);
-
if(User==null){
-
return new JsonResult("userId不存在,無法刪除",false);
-
}
-
userDao.deletdUserById(userId);
-
}
-
return new JsonResult("success",true);
-
}
-
public JsonResult update(User user){
-
User User= userDao.getUserById(user.getUserId());
-
if(User==null){
-
return new JsonResult("沒有此userId",false);
-
}
-
user.setModifiedTime(new Date());
-
userDao.updateUser(user);
-
return new JsonResult("success",true);
-
}
-
public JsonResult detail(String userId, String userCode){
-
User User=null;
-
if(userId==null){
-
User= userDao.getUserByCode(userCode);
-
}else if(userCode==null){
-
User= userDao.getUserById(userId);
-
}
-
System.out.println(User);
-
return new JsonResult("success",true,User);
-
}
-
public JsonResult list(int pageNum,int pageSize){
-
PageHelper.startPage(pageNum, pageSize);
-
List<User> list= userDao.getUserList();
-
//把list包裝成PageInfo物件才能序列化,該外掛也預設實現了一個PageInfo
-
PageInfo<User> pageInfo = new PageInfo<User>(list);
-
//得到總的資料條數
-
Long total=pageInfo.getTotal();
-
return new JsonResult(total,"success",true,list);
-
}
-
}
這裡主要看一下list()方法,這裡採用了pagehelper外掛,pageNum為頁面頁數,pageSize為一頁資料的數量,需要把把list包裝成PageInfo物件才能序列化,使用getTotal()方法得到資料的條數。pagehelper外掛的的依賴引入如下,一直遇到報空錯誤,更新一下版本就好了。
Spring Boot+Mybatis+Pagehelper分頁
controller層
程式碼如下:
-
@RestController //使用這個方法代表rest風格的控制器
-
public class UserController {
-
@Autowired
-
private UserServices userServices; //注入服務方法;
-
@RequestMapping(value = "/add", method= RequestMethod.POST)
-
public Object add(@Valid @RequestBody User user, BindingResult result){
-
if(result.hasErrors()){
-
String msg="";
-
List<FieldError> fieldErrors=result.getFieldErrors();
-
for (FieldError fieldError:fieldErrors){
-
msg+=fieldError.getDefaultMessage()+",";
-
}
-
return new JsonResult(msg.substring(0,msg.length()-1),false);
-
}
-
return userServices.add(user);
-
}
-
@RequestMapping(value = "/delete",method= RequestMethod.POST)
-
public Object delete(String userId,String userCode){
-
return userServices.delete(userId,userCode);
-
}
-
@RequestMapping(value = "/update",method= RequestMethod.POST)
-
public Object update(@RequestBody User user){
-
return userServices.update(user);
-
}
-
@RequestMapping(value = "/detail",method= RequestMethod.GET)
-
public Object detail(String userId,String userCode){
-
return userServices.detail(userId,userCode);
-
}
-
@RequestMapping(value = "/list",method= RequestMethod.GET)
-
public Object list(){
-
int pageNum=1;
-
int pageSize=5;
-
return userServices.list(pageNum,pageSize);
-
}
-
}
這裡的@RequestBody代表引數的傳入得是json格式,Validator註解@Valid說明需要檢查的物件,如果有錯誤,錯誤結果都會傳入BindingResult,裡面就是具體的用法了。
59. Spring Boot Validator校驗【從零開始學Spring Boot】
程式入口
-
@SpringBootApplication()
-
public class mysqlApplication {
-
public static void main(String[] args){
-
SpringApplication.run(mysqlApplication.class,args);
-
}
-
}
4.測試
測試採用google瀏覽器的postman外掛來發送get/post請求,部分結果如下:
add
add_failed
add_success
detail
detail_get
detail_result
list
list
------------------------------------
Mapper
-----------------------------------
@Mapper
public interface DemoMapper {
//增
@Insert("INSERT INTO demo(name,age)VALUES(#{name},#{age})")
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //獲取插入後自動生成的主鍵,keyProperty對應類屬性名,keyColumn對應資料庫欄位名
int add(Demo demo);
//刪
@Delete("DELETE FROM demo WHERE id=#{id}")
boolean deleteById(int id);
//查
@Select("SELECT * FROM demo WHERE id=#{id}")
Demo findById(int id);
@Select("SELECT * FROM demo WHERE login=#{login} AND password=#{password}")
Demo findByObject(@Param("login") String login,@Param("password") String password);
//改,注意:需要指定引數對映@Param,如不指定,可按下面的方法執行
@Update("UPDATE demo SET name=#{name} WHERE id =#{id}")
boolean updateById(@Param("name") String name,@Param("id") int id);
@Update("UPDATE demo SET name=#{name} WHERE id =#{id}")
boolean update_2ById(Demo demo);
//批量增
@InsertProvider(type = LoginProvider.class,method = "insert")
int insert(@Param("demoList")List<Demo> demoList);
//批量刪
@DeleteProvider(type = LoginProvider.class,method = "delete")
boolean delete(@Param("demoList")List<Demo> demoList);
//批量查
@Select("SELECT * FROM demo")
List<Demo> find();
@SelectProvider(type = LoginProvider.class,method = "find2")
List<Demo>find2(@Param("demoList")List<Demo> demoList);
//批量改
@UpdateProvider(type = LoginProvider.class,method = "update")
boolean update(@Param("demoList")List<Demo> demoList);
}