目錄
SpringBoot
controller層
1、@Controller
@Controller 用來響應頁面,表示當前的類為控制器。
2、@RestController
@RestController 是@ResponseBody和@Controller的結合
表明當前類是控制器且返回的是一組數據,不是頁面
@ResponseBody
表示該方法的返回結果直接寫入HTTP response body中
一般在異步獲取數據時使用,在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上@responsebody后返回結果不會被解析
為跳轉路徑,而是直接寫入HTTP response body中。比如異步獲取json數據,加上@responsebody后,會直接返回json數據。
3、@Autowired
這個注解的作用是將其他的類,接口引入,類似於之前的類的初始化等,用這個注解,類中或接口的方法就可以直接調用了。
4、@RequestMapping
當前台界面調用Controller處理數據時候告訴控制器怎么操作
作用:URL映射。
RequestMapping是一個用來處理請求地址映射的注解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。
該注解有六個屬性:
params:指定request中必須包含某些參數值是,才讓該方法處理。
headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。
value:指定請求的實際地址,指定的地址可以是URI Template 模式
method:指定請求的method類型, GET、POST、PUT、DELETE等
consumes:指定處理請求的提交內容類型(Content-Type),如application/json,text/html;
produces:指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回
5、@GetMapping
@RequestMapping(method = RequestMethod.GET)的簡寫
作用:對應查詢,表明是一個查詢URL映射
6、@PostMapping
@RequestMapping(method = RequestMethod.POST)的簡寫
作用:對應增加,表明是一個增加URL映射
7、@PutMapping
@RequestMapping(method = RequestMethod.PUT)的簡寫
作用:對應更新,表明是一個更新URL映射
8、@DeleteMapping
@RequestMapping(method = RequestMethod.DELETE)的簡寫
9、@RequestBody和@RequestParam
兩個注解都是用於方法中接收參數使用的,兩者也有一定的區別。
@RequestBody這個一般處理的是在ajax請求中聲明contentType: “application/json; charset=utf-8”時候。也就是json數據或者xml(我沒用過這個,用的是json)
@RequestParam這個一般就是在ajax里面沒有聲明contentType的時候,為默認的。。。urlencode格式時,用這個。
@RequestBody可以直接將頁面中的參數封裝成實體類中的數據傳輸給后天
service層
1.@service
用於標注業務層組件
2.@Component
泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。
dao層
1.@Repository
是用來注解接口,@Repository注解可以標記在任何的類上,用來表明該類是用來執行與數據庫相關的操作(即dao對象),並支持自動處理數據庫操作產生的異常
實體類注解
@Entity實體類注解
@Table(name ="數據庫表名"),這個注解也注釋在實體類上,對應數據庫中相應的表。
@Id、@Column注解用於標注實體類中的字段,pk字段標注為@Id,其余@Column。
SpringJPA主鍵生成策略
數據庫使用Oracle,常用的就是UUID和整形自增。
UUID能達到全局唯一,而且不受數據庫限制,比如Oracle的自增就要用序列來做。但是存儲控件需求會更多,另外性能上不及整形。
整形自增MySQL中只要設置一個整形列即可,Oracle中需要建立一個SEQUENCE。
public enum GenerationType {
TABLE,
SEQUENCE,
IDENTITY,
AUTO;
private GenerationType() {
}
}
GenerationType源碼
從源碼中可以看出JPA提供的四種標准主鍵策略TABLE,SEQUENCE,IDENTITY,AUTO
TABLE:使用一個特定的數據庫表格來保存主鍵。
SEQUENCE:根據底層數據庫的序列來生成主鍵,條件是數據庫支持序列。 這個值要與generator一起使用,generator 指定生成主鍵使用的生成器(可能是orcale中自己編寫的序列)。
IDENTITY:主鍵由數據庫自動生成(主要是支持自動增長的數據庫,如mysql)
AUTO:主鍵由程序控制,也是GenerationType的默認值。
不寫GeneratedValue注解時即為GenerationType.AUTO 這時主鍵生成是根據數據庫hibernate_sequence里的next_val來生成但我想用自已規則來生成自己的ID查了半天的資料終於解決這個問題。
建議oracle可采用UUID,需求場景需要也可使用整型自增
mysql采用整形,業務中可便於排序,把握先后
UUID:
@Id
@GeneratedValue(generator = "faceset_generator")
@GenericGenerator(name = "faceset_generator", strategy = "uuid")
主鍵自增為1,並且在MySQL時,不用序列,直接指定GenerationType.IDENTITY即可。
mysql整型自增:
@Id
@GenericGenerator(strategy = "GenerationType.IDENTITY")
SpringDataJpa-主鍵生成策略詳解:參考文章最后:SpringDataJpa-主鍵生成策略
配置
1.@Configuration,@Bean
可理解為用spring的時候xml里面的<beans>標簽,用@Configuration注解該類,等價 與XML中配置beans
@Bean是一個方法級別上的注解,主要用在@Configuration注解的類里,也可以用在@Component注解的類里。添加的bean的id為方法名
例如:
@Configuration
public class ExampleConfiguration {
@Value("com.mysql.jdbc.Driver")
private String driverClassName;
@Value("jdbc://xxxx.xx.xxx/xx")
private String driverUrl;
@Value("${root}")
private String driverUsername;
@Value("123456")
private String driverPassword;
@Bean(name = "dataSource")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(driverUrl);
dataSource.setUsername(driverUsername);
dataSource.setPassword(driverPassword);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
注:在項目中
@Autowired
private DataSource dataSource;
的時候,這個dataSource就是我們在ExampleConfiguration中配的DataSource。
事務注解
在Spring中,事務有兩種實現方式,分別是編程式事務管理和聲明式事務管理兩種方式
編程式事務管理: 編程式事務管理使用TransactionTemplate或者直接使用底層的PlatformTransactionManager。對於編程式事務管理,spring推薦使用TransactionTemplate。
聲明式事務管理: 建立在AOP之上的。其本質是對方法前后進行攔截,然后在目標方法開始之前創建或者加入一個事務,在執行完目標方法之后根據執行情況提交或者回滾事務,通過@Transactional就可以進行事務操作,更快捷而且簡單。推薦使用
啟動類
@SpringBootApplication:
啟動注解,@SpringBootApplication是一個復合注解,包括@ComponentScan, 和@SpringBootConfiguration,@EnableAutoConfiguration
@SpringBootConfiguration繼承自@Configuration,二者功能也一致,標注當前類是配置類,並會將當前類內聲明的一個或多個以@Bean注解標記的方法的實例納入到srping容器中,並且實例名就是方法名。
@EnableAutoConfiguration的作用啟動自動的配置,@EnableAutoConfiguration注解的意思就是Springboot根據你添加的jar包來配置你項目的默認配置,比如根據spring-boot-starter-web ,來判斷你的項目是否需要添加了webmvc和tomcat,就會自動的幫你配置web項目中所需要的默認配置。在下面博客會具體分析這個注解,快速入門的demo實際沒有用到該注解。
@ComponentScan,掃描當前包及其子包下被@Component,@Controller,@Service,@Repository注解標記的類並納入到spring容器中進行管理。是以前的<context:component-scan>(以前使用在xml中使用的標簽,用來掃描包配置的平行支持)。
@ServletComponentScan:
在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通過@WebServlet、@WebFilter、@WebListener注解自動注冊,無需其他代碼。
@MapperScan("com.Vm.server") :
@MapperScan注解只會掃描包中的接口,不會掃描類,掃描指定包中的接口
@EnableScheduling:
spring自帶的定時服務
public class ScheduledTasks {
@Scheduled(fixedRate = 1000 * 30) //每30秒執行一次
public void reportCurrentTime(){
System.out.println ("Scheduling Tasks Examples: The time is now " + dateFormat ().format (new Date ()));
}
}
Mybatis
//Mapper中的namespace用於綁定Dao接口的,即面向接口編程。
//namespace:一般是dao接口所在的路徑+接口名稱
<mapper namespace="com.VmService.dao.IBlackDao">
//resultMap屬性:type為java實體類;id為此resultMap的標識。
//id和result標簽是最簡單的映射,id為主鍵映射;result其他基本數據庫表字段到實體類屬性的映射。
<resultMap id="BlackBean" type="com.VmService.model.BlackBean">
<id column="ID" property="id"/>
<id column="IM" property="im"/>
</resultMap>
//進行SQL語句查找
<select id="selectAllBlackList" resultMap="BlackBean">
SELECT
id as id,
im as im,
FROM
t_blacklist t1
ORDER BY
id DESC
</select>
SpringDataJpa-主鍵生成策略
一、SpringDataJpa標准用法
spring data jpa 的標准主鍵生成策略主要有四種,分別是:
public enum GenerationType {
TABLE, //使用一個額外的數據庫表來保存主鍵
SEQUENCE,//使用序列的方式,且其底層數據庫要支持序列,一般有postgres、Oracle等
IDENTITY,//主鍵由數據庫生成,一般為自增型主鍵,支持的有MySql和Sql Server
AUTO//由程序來決定主鍵規則
}
主鍵的生成規則主要由注解 @GeneratedValue 來說明,其源碼如下:
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface GeneratedValue {
GenerationType strategy() default AUTO;
String generator() default "";
}
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="payablemoney_seq")
@SequenceGenerator(name="payablemoney_seq", sequenceName="seq_payment")
使用的具體例子為:
假設有一個表示人臉圖片集合的類為FaceSet,其主鍵為facesetToken,則表示如下
@Entity(name = "face_set")
public class FaceSet{
}
- Sequence
@SequenceGenerator 中的 sequenceName 為序列的名稱,需要與@GeneratedValue 中的generator對應
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="faceset_generator")
@SequenceGenerator(name="faceset_generator", sequenceName="faceset_seq")
@Column(name = "faceset_token", unique = true)
private String facesetToken;
- Auto
如果不指定具體的生成規則,則默認為AUTO,即下列兩種情況等價
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String facesetToken;
@Id
private String facesetToken;
二、Hibernate主鍵策略生成
hibernate-5.0.12.Final版本的默認工廠中有14種生成策略,具體可見org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory
public DefaultIdentifierGeneratorFactory() {
register( "uuid2", UUIDGenerator.class );
register( "guid", GUIDGenerator.class ); // can be done with UUIDGenerator + strategy
register( "uuid", UUIDHexGenerator.class ); // "deprecated" for new use
register( "uuid.hex", UUIDHexGenerator.class ); // uuid.hex is deprecated
register( "assigned", Assigned.class );
register( "identity", IdentityGenerator.class );
register( "select", SelectGenerator.class );
register( "sequence", SequenceStyleGenerator.class );
register( "seqhilo", SequenceHiLoGenerator.class );
register( "increment", IncrementGenerator.class );
register( "foreign", ForeignGenerator.class );
register( "sequence-identity", SequenceIdentityGenerator.class );
register( "enhanced-sequence", SequenceStyleGenerator.class );
register( "enhanced-table", TableGenerator.class );
}
public void register(String strategy, Class generatorClass) {
LOG.debugf( "Registering IdentifierGenerator strategy [%s] -> [%s]", strategy, generatorClass.getName() );
final Class previous = generatorStrategyToClassNameMap.put( strategy, generatorClass );
if ( previous != null ) {
LOG.debugf( " - overriding [%s]", previous.getName() );
}
}
對幾種比較常用的類型進行說明:
- uuid
采用128位的uuid算法生成主鍵,uuid被編碼為一個32位16進制數字的字符串。
當使用strategy為uuid時,使用的時hibernate自己定義的UUID生成算法,此策略已過時,其具體實現參照org.hibernate.id. UUIDHexGenerator, 生成的字符串如402880876359adeb016359ae27190000
當使用strategy為uuid2時,此為此版本推薦使用的uuid生成算法,其默認采用標准的生成策略StandardRandomStrategy,實現為使用jdk自帶的uuid生成方法,生成的字符串如
4af17c8e-8317-43e9-aff9-12d5590a71c6
@Id
@GeneratedValue(generator = "faceset_generator")
@GenericGenerator(name = "faceset_generator", strategy = "uuid")
- assigned
插入主鍵時,由程序來指定。相當於JPA中的AUTO。
@Id
@GeneratedValue(generator = "faceset_generator")
@GenericGenerator(name = "faceset_generator", strategy = "assigned")
- sequence
@Id
@GeneratedValue(generator = "faceset_generator")
@GenericGenerator(name = "faceset_generator", strategy = "sequence",
parameters = { @Parameter(name = "sequence", value = "faceset_seq") })
- guid
采用數據庫底層的guid算法機制,對應MYSQL的uuid()函數,SQL Server的newid()函數,ORACLE的rawtohex(sys_guid())函數等
三、通過@GenericGenerator自定義主鍵生成策略
常用數據庫支持生成規則如下:
數據庫 | 支持的策略 |
---|---|
Postgres | GenerationType.TABLE GenerationType.AUTO GenerationType.IDENTITY GenerationType.SEQUENCE |
Oracle | GenerationType.TABLE GenerationType.AUTO GenerationType.SEQUENCE 不支持GenerationType.IDENTITY |
Mysql | GenerationType.TABLE GenerationType.AUTO GenerationType.IDENTITY 不支持GenerationType.SEQUENCE |