日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合

發布時間:2024/9/30 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、SpringBoot 簡介:

spring boot并不是一個全新的框架,它不是spring解決方案的一個替代品,而是spring的一個封裝。所以,你以前可以用spring做的事情,現在用spring boot都可以做。它是簡化Spring應用開發的一個框架,是整個Spring技術棧的一個大整合,是J2EE開發的一站式解決方案。使用springboot,你可以達到快速開發的目的,不像以前使用spring的時候,即使整合一個小小的web項目,也要進行很多相關的配置才能使用,效率低下。

二、搭建一個SpringBoot 入門程序:

1、創建一個maven工程:

2、導入springboot相關依賴:

<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><!-- 這個插件,可以將應用打包成一個可執行的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應用:

//@SpringBootApplication來標注一個主程序類,表明這是一個springBoot應用 @SpringBootApplication public class HelloSpringBoot {public static void main(String[] args){//spring應用啟動起來SpringApplication.run(HelloSpringBoot.class, args);} }

4、編寫相關的Controller:

@Controller public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello(){return "Hello World";} }

5、項目結構:

這樣,一個springboot的web項目就搭建好了,運行main主程序,就可以進行測試了,相比起之前spring的搭建過程,是不是快了很多?

三、SpringBoot與數據源:

1、SpringBoot與JDBC整合:

(1)導入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文件中進行數據源的相關配置:

spring:datasource:username: rootpassword: adminurl: jdbc:mysql://127.0.0.1:3306/jdbcdriver‐class‐name: com.mysql.jdbc.Driverschema:#指定數據庫的位置- classpath:employee.sql

(3)編寫數據庫建表語句,并引入application.yml文件中。

默認只需要將文件命名為 schema.sql,schema‐all.sql ,springboot就會自動讀取。
或者可以使用
schema:
‐ classpath:department.sql? 指定數據庫文件的位置。入步驟2。

(4)其他數據源的配置:

#數據源其他配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true

(5)操作數據庫:springboot自動配置了JdbcTemplate操作數據庫。

2、SpringBoot與Druid數據源整合:

(1)導入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指定數據源的類型:

spring:datasource: # 數據源基本配置username: rootpassword: admindriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/ssm_crudtype: com.alibaba.druid.pool.DruidDataSourceschema:#指定數據庫的位置- classpath:employee.sql

(3)導入Druid數據源:

//導入Configuration數據源 @EnableAutoConfiguration @Configuration public class DruidConfig {@ConfigurationProperties(prefix="spring.datasource")@Beanpublic DataSource druid(){return new DruidDataSource();}//配置Druid的監控//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", "");//默認就是允許所有訪問。//initParams.put("deny","");//拒絕訪問的ipbean.setInitParameters(initParams);return bean;}//2.配置一個監控的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 的工程結構部圖:

3、SpringBoot整合Mybatis:

(1)導入mybatis的starter:

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency>

(2)配置數據源的相關屬性(前面1 2 的配置):

(3)給數據庫創建表:employee.sql 以及 department.sql 數據庫表:

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)創建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;} }

至此,準備工作就做好了。下面介紹springboot在mybatis中使用注解版和配置文件版對數據庫進行操作的方式。

(5)注解版:

//指定這是一個操作數據庫的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/*.xml

EmployeeMapper.xml 配置文件內容:

<?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 文件內容:

public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee); }

至此,SpringBoot整合Mybatis就完成了。

附與Mybatis整合的工程結構圖:

4、SpringBoot 整合SpringData JPA :

(1)導入SpringData JPA 的 maven starter:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>

(2)編寫一個實體類(bean)和數據表進行映射,并且配置好映射關系:

//使用JPA注解配置映射關系 @Entity//告訴JPA這是一個實體類(和數據表映射的表) @Table(name="tb1_user")//@Table來指定和哪個數據表對應,如果省略默認表名是user public class User {@Id//主鍵@GeneratedValue(strategy=GenerationType.IDENTITY)//自增主鍵private Integer id;@Column(name="last_name",length=50)//這是和數據表對應的一個列private String lastName;@Column//省略默認列名就是屬性名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接口來操作實體類對應的數據表(Repository):

//繼承JpaRepository來完成對數據庫的操作 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:#更新或者創建數據表結構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的整合就完成了。附工程結構圖:

總結

以上是生活随笔為你收集整理的SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。