一、MyBatis注解
MyBatis是一個基于ORM的資料通路層架構。
1.1 @Insert [/ɪnˈsɜːt/] 【插入】 : 插入sql , 和xml insert sql文法完全一樣
1.2 @Select [[sɪˈlekt]]【查詢】 : 查詢sql, 和xml select sql文法完全一樣
1.3 @Update [ /ˌʌpˈdeɪt/]【更新】 : 更新sql, 和xml update sql文法完全一樣
1.4 @Delete [/dɪˈliːt/]【删除】 : 删除sql, 和xml delete sql文法完全一樣
1.5 @Param [/ˌpærəˈm/]【參數】 : 入參
1.6 @Results [/rɪˈzʌlts/]【結果】 : 設定結果集合
[email protected] : 結果
1.8 @ResultMap : 引用結果集合
1.9 @SelectKey : 擷取最新插入id
具體使用:
(1)、@Select、@Results、@Result
/**
* 查詢所有
* @return Employee泛型集合
*/
@Select("select * from t_emp")
@Results(id = "empMap",value = {
@Result(column = "emp_id",property = "empId",id = true),
@Result(column = "emp_name",property = "empName"),
@Result(column = "emp_tel",property = "empTel"),
@Result(column = "emp_education",property = "empEducation"),
@Result(column = "emp_birthday",property = "empBirthday"),
@Result(column = "fk_dept_id",property = "dept"
,one = @One(select = "com.yingside.dao.DeptMapper.getById",
fetchType = FetchType.LAZY))
})
List<Employee> getAll();
(2)、@Delete、@Param、@ResultMap
/**
* 根據id查詢員工
* @param empId 員工主鍵id
* @return 員工對象
*/
@Select("select * from t_emp where emp_id=#{empId}")
@ResultMap(value="empMap")
Employee getById(@Param("empId") Integer empId);
(3)、@Insert、@SelectKey
/**
* 插入新員工資訊,并将最新id放入到員工對象在
* @param record 新員工對象
* @return 插入成功 1 失敗 0
*/
@Insert("insert into t_emp (emp_id, emp_name, emp_tel, " +
" emp_education, emp_birthday, fk_dept_id" +
" )" +
" values (#{empId}, #{empName}, #{empTel}, " +
" #{empEducation}, #{empBirthday}, #{fkDeptId}" +
" )")
@SelectKey(before = false,keyColumn = "emp_id",keyProperty = "empId",
statement = "select last_insert_id()",resultType = Integer.class)
int insert(Employee record);
(4)、@Delete、@Param
/**
* 根據員工id删除員工
* @param empId 員工主鍵id
* @return 删除成功 1 失敗 0
*/
@Delete("delete from t_emp where emp_id=#{empId}")
int deleteByPrimaryKey(@Param("empId") Integer empId);
(5)、@Update
/**
* 更新員工資訊
* @param record 員工對象
* @return 更新成功 1 失敗 0
*/
@Update("update t_emp" +
" set emp_name = #{empName,jdbcType=VARCHAR}," +
" emp_tel = #{empTel,jdbcType=VARCHAR}," +
" emp_education = #{empEducation,jdbcType=VARCHAR}," +
" emp_birthday = #{empBirthday,jdbcType=DATE}," +
" fk_dept_id = #{fkDeptId,jdbcType=INTEGER}" +
" where emp_id = #{empId,jdbcType=INTEGER}")
int update(Employee record);
當然最後别忘記了,寫完這些之後,在核心配置檔案中要把映射檔案給加上,之前使用的時候,找尋的是resouce xml的資源路徑,現在由于使用了注解,就隻有接口檔案了,所有配置相應的要做一個簡單的修改
<mappers>
<mapper class="com.yingside.dao.EmployeeMapper" />
</mappers>
二、Spring注解
Spring — 分層解決業務邏輯層與其他各層之間松耦合問題的javaSE/EE的一站式開源架構。
2.1 @Component [/kəmˈpəʊnənt/]【元件,組成部分,成分】
建立對象的注解,使用時隻需将該注解标注在相應類上即可。
沒有@Component之前
public class Student{
}
Spring配置檔案
有@Component之後
@Component --- 使用預設的對象名稱【類名,首字母小寫】
public class Student{
}
@Component(“stu”)---使用指定的對象名稱
public class Student{
}
2.2 @Repository [/rɪˈpɒzətri/]【資源庫】标注資料通路接口實作類,其功能與 @Component 相同。
2.3 @Service[ /ˈsɜːvɪs/]【服務】标注業務通路接口實作類,其功能與 @Component 相同。
2.4 @Controller[/kənˈtrəʊlər/]【控制器】标注控制層實作類,其功能與 @Component 相同。
2.5 @Autowired[ /ˈɔːtəʊˈwaɪəd/]【自動裝配】 完成 Bean 的自動注入工作。預設按照bytype
2.6 @Resource[/rɪˈsɔːs; rɪˈzɔːs/] 【資源類型】完成 Bean 的自動注入工作。預設按照byname
@autowired和@resource注解的差別?
(1)@Autowired與@Resource都可以用來裝配bean,都可以寫在字段或setter方法上
(2)@Autowired預設按類型裝配,預設情況下必須要求依賴對象存在,如果要允許null值,可以設定它的required屬性為false。如果想使用名稱裝配可以結合@Qualifier注解進行使用。
(3)@Resource,預設按照名稱進行裝配,名稱可以通過name屬性進行指定,如果沒有指定name屬性,當注解寫在字段上時,預設取字段名進行名稱查找。如果注解寫在setter方法上預設取屬性名進行裝配。當找不到與名稱比對的bean時才按照類型進行裝配。但是需要注意的是,如果name屬性一旦指定,就隻會按照名稱進行裝配。
推薦使用@Resource注解在字段上,這樣就不用寫setter方法了,并且這個注解是屬于J2EE的,減少了與Spring的耦合。
2.7 @Qualifier [/ˈkwɒlɪfaɪər/]【限定符 限定詞 修飾符】與 @Autowired 注解配合使用,會将預設的按 Bean 類型裝配修改為按 Bean 的執行個體名稱裝配,Bean 的執行個體名稱由 @Qualifier 注解的參數指定。
public interfase UserDao{
}
@Repository(“studentUsetDao”)
public class StudentUserDao implements UserDao{
}
@Repository(“personUsetDao”)
public class PersonUserDao implements UserDao{
}
//業務類
public class UserServiceImple{
@Autowired
@Qualifier(“personUsetDao”)
private UserDao userDao;
}
[email protected]開啟切面
2.9 @Before前置通知
2.10 @AfterReturning後置通知
2.11 @AfterThrowing異常通知
2.12 @Around環繞通知
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
package com.wangxing.spring.service;
import org.springframework.stereotype.Component;
//業務類
@Component("personService")
public class PersonService {
public void insertPerson(){
System.out.println("添加個人資訊的業務方法");
}
public void updatePerson(){
System.out.println("修改個人資訊的業務方法");
//int a=10/0;
}
public void deletePerson(){
System.out.println("删除個人資訊的業務方法");
}
public void selectPerson(){
System.out.println("查詢個人資訊的業務方法");
}
}
package com.wangxing.spring.service;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
//增強類
//@Aspect,表示這個系統需求類是一個切面
@Component
@Aspect
public class MyAvice {
//系統需求功能實作方法
//@Before("execution(* com.wangxing.spring.service.PersonService.selectPerson())")
//@AfterReturning("execution(* com.wangxing.spring.service.PersonService.deletePerson())")
//@AfterThrowing("execution(* com.wangxing.spring.service.PersonService.updatePerson())")
@After("execution(* com.wangxing.spring.service.PersonService.updatePerson())")
public void saveLog(){
System.out.println("記錄執行日志");
}
//執行環繞通知的系統需求功能實作方法
@Around("execution(* com.wangxing.spring.service.PersonService.insertPerson())")
public void testAround(ProceedingJoinPoint joinPoint) throws Throwable{
saveLog();
joinPoint.proceed(); // 調用真正的業務方法
saveLog();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--使用context命名空間,通知spring掃描指定目錄,進行注解的解析-->
<context:component-scan base-package="com.wangxing.spring.service"></context:component-scan>
<!--開啟aop注解-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
2.13 @Transactional [ /trænˈzækʃənəl/]【事務處理】開啟事務
package com.wangxing.spring.service;
import com.wangxing.spring.mapper.TransferMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.Map;
@Service("transferService")
@Transactional
public class TransferService {
@Autowired
private TransferMapper transferMapper;
/**
* 轉賬方法
* @throws Exception
*/
public void transfer()throws Exception{
Map<String,Object> liuneng=new HashMap<String,Object>();
liuneng.put("username","劉能");
liuneng.put("number",1000);
transferMapper.lessMoney(liuneng);
int a=10/0;
Map<String,Object> zhaosi=new HashMap<String,Object>();
zhaosi.put("username","趙四");
zhaosi.put("number",1000);
transferMapper.addMoney(zhaosi);
}
}
三、SpringMVC
SpringMVC — SpringMVC是web層的mvc開發架構,屬于Spring架構的WEB子產品中的一個部分。
3.1 @RequestMapping設定控制器類/請求處理方法的通路路徑
@RequestMapping的常用的屬性
value表示設定通路路徑[可以省略]
method–限制請求的通路方式【GET、POST…】
package com.wangxing.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping("/test1.do")
public ModelAndView testRequest(){
ModelAndView mav=new ModelAndView();
mav.addObject("info","hello,網星軟體");
mav.setViewName("test.jsp");
return mav;
}
}
[email protected] 定義在方法上擷取請求url路徑上的參數資料
@RequestMapping(value = "/get1/{username}/{password}",method = RequestMethod.GET)
public ModelAndView getReqParam1(@PathVariable("username")String name,
@PathVariable("password")String pass){
ModelAndView mav=new ModelAndView();
mav.addObject("username",name);
mav.addObject("password",pass);
mav.setViewName("test.jsp");
return mav;
}
3.3 @RequestParam 定義在方法上,擷取請求中通過key=value方式傳遞的參數資料
@RequestMapping(value = "/get2",method = RequestMethod.GET)
public ModelAndView getReqParam2(@RequestParam("username")String name, @RequestParam("password")String pass){
ModelAndView mav=new ModelAndView();
mav.addObject("username",name);
mav.addObject("password",pass);
mav.setViewName("test.jsp");
return mav;
}
3.4 @DateTimeFormat時間格式化
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date day;
3.5 @RequestBody注解接收來自請求體中的參數。
package com.wangxing.springmvc.controller;
import com.wangxing.springmvc.bean.UserBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping(value = "/test1.do")
@ResponseBody
public UserBean testRequest(){
UserBean user1=new UserBean();
user1.setUsername("zhangsan");
user1.setPassword("000000");
user1.setMyage(23);
user1.setMyaddress("西安");
return user1;
}