spring boot并不是一个全新的框架,它不是spring解决方案的一个替代品,而是spring的一个封装。所以,你以前可以用spring做的事情,现在用spring boot都可以做。它是简化Spring应用开发的一个框架,是整个Spring技术栈的一个大整合,是J2EE开发的一站式解决方案。使用springboot,你可以达到快速开发的目的,不像以前使用spring的时候,即使整合一个小小的web项目,也要进行很多相关的配置才能使用,效率低下。
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的搭建过程,是不是快了很多?
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: root
password: admin
url: jdbc:mysql://127.0.0.1:3306/jdbc
driver‐class‐name: com.mysql.jdbc.Driver
schema:
#指定数据库的位置
- classpath:employee.sql
(3)编写数据库建表语句,并引入application.yml文件中。
默认只需要将文件命名为 schema.sql,schema‐all.sql ,springboot就会自动读取。 或者可以使用 schema: ‐ classpath:department.sql 指定数据库文件的位置。入步骤2。
(4)其他数据源的配置:
#数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: 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: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_crud
type: com.alibaba.druid.pool.DruidDataSource
schema:
#指定数据库的位置
- classpath:employee.sql
(3)导入Druid数据源:
//导入Configuration数据源
@EnableAutoConfiguration
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1.配置一个管理后台的Servlet
@Bean
public 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","");//拒绝访问的ip
bean.setInitParameters(initParams);
return bean;
}
//2.配置一个监控的filter
@Bean
public 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 mapper
PUBLIC "-//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: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/jpa
jpa:
hibernate:
#更新或者创建数据表结构
ddl-auto: create
#控制台显示sql
show-sql: true
(5)controller测试:
@RestController
public class UserController {
@Autowired
UserRepository 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的整合就完成了。附工程结构图:
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/114703.html原文链接:https://javaforall.cn