javascript
SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合
一、SpringBoot 簡介:
spring boot并不是一個全新的框架,它不是spring解決方案的一個替代品,而是spring的一個封裝。所以,你以前可以用spring做的事情,現(xiàn)在用spring boot都可以做。它是簡化Spring應(yīng)用開發(fā)的一個框架,是整個Spring技術(shù)棧的一個大整合,是J2EE開發(fā)的一站式解決方案。使用springboot,你可以達到快速開發(fā)的目的,不像以前使用spring的時候,即使整合一個小小的web項目,也要進行很多相關(guān)的配置才能使用,效率低下。
二、搭建一個SpringBoot 入門程序:
1、創(chuàng)建一個maven工程:
2、導(dǎo)入springboot相關(guān)依賴:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zwp</groupId><artifactId>springboot-test</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-test</name><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build> <plugins><!-- 這個插件,可以將應(yīng)用打包成一個可執(zhí)行的jar包 --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins></build> </project>3、編寫一個主程序;啟動Spring Boot應(yīng)用:
//@SpringBootApplication來標(biāo)注一個主程序類,表明這是一個springBoot應(yīng)用 @SpringBootApplication public class HelloSpringBoot {public static void main(String[] args){//spring應(yīng)用啟動起來SpringApplication.run(HelloSpringBoot.class, args);} }4、編寫相關(guān)的Controller:
@Controller public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello(){return "Hello World";} }5、項目結(jié)構(gòu):
這樣,一個springboot的web項目就搭建好了,運行main主程序,就可以進行測試了,相比起之前spring的搭建過程,是不是快了很多?
三、SpringBoot與數(shù)據(jù)源:
1、SpringBoot與JDBC整合:
(1)導(dǎo)入maven依賴:
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>(2)在application.yml文件中進行數(shù)據(jù)源的相關(guān)配置:
spring:datasource:username: rootpassword: adminurl: jdbc:mysql://127.0.0.1:3306/jdbcdriver‐class‐name: com.mysql.jdbc.Driverschema:#指定數(shù)據(jù)庫的位置- classpath:employee.sql(3)編寫數(shù)據(jù)庫建表語句,并引入application.yml文件中。
默認(rèn)只需要將文件命名為 schema.sql,schema‐all.sql ,springboot就會自動讀取。
或者可以使用
schema:
‐ classpath:department.sql? 指定數(shù)據(jù)庫文件的位置。入步驟2。
(4)其他數(shù)據(jù)源的配置:
#數(shù)據(jù)源其他配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true(5)操作數(shù)據(jù)庫:springboot自動配置了JdbcTemplate操作數(shù)據(jù)庫。
2、SpringBoot與Druid數(shù)據(jù)源整合:
(1)導(dǎo)入Druid 的 maven的依賴:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version></dependency>(2)在application.yml文件使用type指定數(shù)據(jù)源的類型:
spring:datasource: # 數(shù)據(jù)源基本配置username: rootpassword: admindriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/ssm_crudtype: com.alibaba.druid.pool.DruidDataSourceschema:#指定數(shù)據(jù)庫的位置- classpath:employee.sql(3)導(dǎo)入Druid數(shù)據(jù)源:
//導(dǎo)入Configuration數(shù)據(jù)源 @EnableAutoConfiguration @Configuration public class DruidConfig {@ConfigurationProperties(prefix="spring.datasource")@Beanpublic DataSource druid(){return new DruidDataSource();}//配置Druid的監(jiān)控//1.配置一個管理后臺的Servlet@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean =new ServletRegistrationBean(new StatViewServlet(), "/druid/*");Map<String,String> initParams=new HashMap<>();initParams.put("loginUsername", "root");initParams.put("loginPassword", "admin");initParams.put("allow", "");//默認(rèn)就是允許所有訪問。//initParams.put("deny","");//拒絕訪問的ipbean.setInitParameters(initParams);return bean;}//2.配置一個監(jiān)控的filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean =new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParams=new HashMap<>();initParams.put("exclusions", "*.js,*.css,/druid/*");bean.setInitParameters(initParams);//攔截所有請求bean.setUrlPatterns(Arrays.asList("/*"));return bean;} }至此,SpringBoot與Druid的整合就完成了。
附 1 和 2 的工程結(jié)構(gòu)部圖:
3、SpringBoot整合Mybatis:
(1)導(dǎo)入mybatis的starter:
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency>(2)配置數(shù)據(jù)源的相關(guān)屬性(前面1 2 的配置):
(3)給數(shù)據(jù)庫創(chuàng)建表:employee.sql 以及 department.sql 數(shù)據(jù)庫表:
SET FOREIGN_KEY_CHECKS=0;-- ---------------------------- -- Table structure for employee -- ---------------------------- DROP TABLE IF EXISTS `employee`; CREATE TABLE `employee` (`id` int(11) NOT NULL AUTO_INCREMENT,`lastName` varchar(255) DEFAULT NULL,`email` varchar(255) DEFAULT NULL,`gender` int(2) DEFAULT NULL,`d_id` int(11) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; SET FOREIGN_KEY_CHECKS=0;-- ---------------------------- -- Table structure for department -- ---------------------------- DROP TABLE IF EXISTS `department`; CREATE TABLE `department` (`id` int(11) NOT NULL AUTO_INCREMENT,`departmentName` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;(4)創(chuàng)建JavaBean :
public class Employee {private Integer id;private String lastName;private Integer gender;private String email;private Integer did;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getDid() {return did;}public void setDid(Integer did) {this.did = did;} } public class Department {private Integer id;private String departmentName;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;} }至此,準(zhǔn)備工作就做好了。下面介紹springboot在mybatis中使用注解版和配置文件版對數(shù)據(jù)庫進行操作的方式。
(5)注解版:
//指定這是一個操作數(shù)據(jù)庫的mapper @Mapper public interface DepartmentMapper {@Select("select * from department where id =#{id}")public Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);@Options(useGeneratedKeys=true,keyProperty="id")@Insert("insert into department(department_name) values(#{departmentName})")public int insertDept(Department department);@Update("update department set department_name=#{departmentName} where id=#{id}")public int updateDept(Department department); } @Mapper public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee);}(6)配置文件版:
在application.yml 文件中指定mybatis 配置文件的位置:
mybatis: # 指定全局配置文件的位置config-location: classpath:mybatis/mybatis-config.xml # 指定sql映射文件的位置mapper-locations: classpath:mybatis/mapper/*.xmlEmployeeMapper.xml 配置文件內(nèi)容:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="springbootmybaits1.mapper.EmployeeMapper"><select id="getEmpById" resultType="springbootmybaits1.bean.Employee">select * from employee where id = #{id}</select><insert id="insertEmp">insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{did})</insert> </mapper>EmployeeMapper.java 文件內(nèi)容:
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee); }至此,SpringBoot整合Mybatis就完成了。
附與Mybatis整合的工程結(jié)構(gòu)圖:
4、SpringBoot 整合SpringData JPA :
(1)導(dǎo)入SpringData JPA 的 maven starter:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>(2)編寫一個實體類(bean)和數(shù)據(jù)表進行映射,并且配置好映射關(guān)系:
//使用JPA注解配置映射關(guān)系 @Entity//告訴JPA這是一個實體類(和數(shù)據(jù)表映射的表) @Table(name="tb1_user")//@Table來指定和哪個數(shù)據(jù)表對應(yīng),如果省略默認(rèn)表名是user public class User {@Id//主鍵@GeneratedValue(strategy=GenerationType.IDENTITY)//自增主鍵private Integer id;@Column(name="last_name",length=50)//這是和數(shù)據(jù)表對應(yīng)的一個列private String lastName;@Column//省略默認(rèn)列名就是屬性名private String email;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;} }(3)編寫一個Dao接口來操作實體類對應(yīng)的數(shù)據(jù)表(Repository):
//繼承JpaRepository來完成對數(shù)據(jù)庫的操作 public interface UserRepository extends JpaRepository<User, Integer>{}(4)基本的配置JpaProperties 和 application.yml 文件:
spring:datasource:username: rootpassword: admindriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/jpajpa:hibernate:#更新或者創(chuàng)建數(shù)據(jù)表結(jié)構(gòu)ddl-auto: create#控制臺顯示sqlshow-sql: true(5)controller測試:
@RestController public class UserController {@AutowiredUserRepository userRespository;@GetMapping("/user/{id}")public User getUser(@PathVariable("id") Integer id){User user=userRespository.findOne(id);return user;}@GetMapping("/user")public User insertUser(User user){User save=userRespository.save(user);return save;} }(6)至此,SpringBoot 整合SpringData JPA的整合就完成了。附工程結(jié)構(gòu)圖:
總結(jié)
以上是生活随笔為你收集整理的SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JPA规范:一对多、一对一、多对多的双向
- 下一篇: 二维矩阵中的最大矩形面积--java实现