IntelliJ IDEA 新建Spring Boot项目
1.新建Spring Boot 项目
用IntelliJ IDEA新建一个Spring Boot 项目,选择Spring Initializr,如下图:
初始项目结构,各目录含义如下:
pom文件为依赖管理文件;
resources为资源文件夹;
statics为静态资源;
templates为模板资源;
application.properties为配置文件;
SpringbootApplication为程序的启动类;
在SpringBoot的启动类里,默认使用了一个注解@SpringBootApplication,有四种属性:
- exclude——根据Class对象来排除特定的类,不加入到Spring容器中,传入Class数组。
- excludeName——根据类名来排除特定的类,不加入到Spring容器中,传入参数是类的全限定名数组。
- scanBasePackages——指定自动扫描的包,参数是字符串数组。
- scanBasePackageClasses——指定自动扫描的包,参数是Class对象数组。
@SpringBootApplication这一个注解整合了三个注解的功能:@Configuration、@EnableAutoConfiguration、@ComponentScan
注意,@Configuration在@SpringBootConfiguration里面:
在SpringBoot中,被@Configuration注解的类是一个配置类,相当于Spring中的xml配置文件。
@EnableAutoConfiguration借助@Import注解使用AutoConfigurationImportSelector将所有符合自动配置条件的bean定义加载到Spring的IoC容器中。
@ComponentScan的作用是开启Spring的自定扫描功能,将范围内被@Component注解的类加载到容器中,并生成bean。可以通过basePackages等属性指定自动扫描的范围。如果不指定,则默认是从被@ComponentScan注解的类所在的package进行扫描,因此SpringBoot的启动类最好放在项目的root package下面,这样才能保证整个项目下的所有类都在扫描范围中。
2.运行简单项目
新建controller包,然后新建helloController.java文件,如下图所示,添加一个get请求地址:http://localhost:8088/test/hello,(默认端口为8080),这里在application.properties文件配置了端口配置:server.port=8088
运行程序,如下所示:
3.JPA实现CRUD功能
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>testone</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testone</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>-->
<!--持久层 JPA包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MYSQL 5.1.36-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- MariaDB驱动 -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<!-- spring热部署 -->
<!--<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>-->
</dependencies>
</plugin>
</plugins>
</build>
</project>
配置文件application.properties:
# 连接MariaDB数据库配置
spring.datasource.url=jdbc:mariadb://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.open-in-view=false
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
server.tomcat.access_log_enabled:true
server.tomcat.basedir:target/tomcat
server.port=8088
logging.level.root=info
Controller层:
HelloController.java文件
package com.example.testone.controller;
import com.alibaba.fastjson.JSON;
import com.example.testone.bean.UserGoodsInfo;
import com.example.testone.entity.Goods;
import com.example.testone.entity.User;
import com.example.testone.service.GoodsService;
import com.example.testone.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@Slf4j
@RestController
@RequestMapping(value = "/test")
public class HelloController {
//@Autowired
@Resource
private UserService userService;
@Resource
private GoodsService goodsService;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String helloworld(){
return "Hello World";
}
/**
* 新增User
* http://localhost:8088/test/addUser?name=Tom&interest=cakes
* @param name
* @param interest
* @return
*/
@RequestMapping(value = "/addUser", method = RequestMethod.GET)
public String addUser(@RequestParam("name") String name, @RequestParam("interest") String interest){
User u=userService.saveUser(name,interest);
if(u!=null){
return JSON.toJSONString(u);
}
return "failed to add a new user!";
}
/**
* 修改一条 user
* @param name
* @param id
* @return
*/
@RequestMapping(value = "/updateUser", method = RequestMethod.GET)
public String updateUser(@RequestParam("name") String name, @RequestParam("id") Integer id){
Boolean isok2=userService.updateUser(id,name);
if(isok2) {
return "succeed to modify a user's name !";
}
return "failed to modify a user!";
}
/**
* get 一条goods记录
* http://localhost:8088/test/getGoods?userId=6
* @param userId
* @return
*/
@RequestMapping(value = "/getGoods", method = RequestMethod.GET)
public String getGoods(@RequestParam("userId") Integer userId){
Goods g=goodsService.getByUserid(userId);
if(g!=null){
return JSON.toJSONString(g);
}
return "failed to get a goods which user_id="+userId;
}
/**
* 新增 Goods
* http://localhost:8088/test/addGoods?userId=1&title=abcde
* @param userId
* @param title
* @return
*/
@RequestMapping(value = "/addGoods", method = RequestMethod.GET)
public String addGoods(@RequestParam("userId") Integer userId, @RequestParam("title") String title){
Goods g=goodsService.saveGoods(userId,title);
if(g!=null){
return JSON.toJSONString(g);
}
return "failed to add a new goods!";
}
/**
* 同时新增 user 和 goods
* http://localhost:8088/test/addBoth?name=abc&interest=www&title=aaa
* @param name
* @param interest
* @param title
* @return
*/
@RequestMapping(value = "/addBoth", method = RequestMethod.GET)
public String addUserGood(@RequestParam("name") String name,
@RequestParam("interest") String interest,
@RequestParam("title") String title){
Boolean isok=goodsService.saveBoth(name,interest,title);
if(isok){
return "save both goods and user succeed!";
}
return "failed to add a new goods and user at the same time !";
}
/**
* 多表查询数据
* @param userId
* @return
*/
@RequestMapping(value = "/getUserGoods", method = RequestMethod.GET)
public String getUserGoods(@RequestParam("userId") Integer userId){
List<UserGoodsInfo> u =userService.getUserGoods(userId);
if(u!=null){
return JSON.toJSONString(u);
}
return "failed to get a UserGoods !";
}
/**
* 根据user_id删除一条记录
* @param userId
* @return
*/
@RequestMapping(value = "/delGoods", method = RequestMethod.GET)
public String delGoods(@RequestParam("userId") Integer userId){
Boolean isok =goodsService.delByid(userId);
if(isok){
return "delete goods with user_id="+userId+" succeed !";
}
return "failed to delete a goods with user_id="+userId;
}
}
service层,UserServiceImpl.java文件:
package com.example.testone.service.impl;
import com.example.testone.bean.UserGoodsInfo;
import com.example.testone.entity.User;
import com.example.testone.repository.UserRepository;
import com.example.testone.service.UserService;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.transaction.Transactional;
import java.util.List;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
//@Resource
private UserRepository userRepository;
public User findById(Integer id){
return userRepository.findById(id);
}
/**
* 新增一个 user
* @param name
* @param interest
* @return
*/
@Transactional(rollbackOn = Exception.class)
public User saveUser(String name,String interest){
try {
User u=new User();
u.setName(name);
u.setInterest(interest);
User uu=userRepository.save(u);//原生方法
log.info("saveUser: user="+ JSON.toJSONString(uu));
return uu;
}catch (Exception e){
log.error("saveUser error!",e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return null;
}
}
/**
* 修改一条user
* @param id
* @param name
* @return
*/
//@Transactional(rollbackOn = Exception.class)
public Boolean updateUser(Integer id,String name){
try {
User u = userRepository.findById(id);
if(u!=null){
u.setName(name);
User u_ = userRepository.save(u);
log.info("updateUser: user="+ JSON.toJSONString(u_));
return true;
}else
log.info("updateUser: no user! id="+id);
return false;
}
catch (Exception e){
log.error("updateUser error!",e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return false;
}
}
public List<UserGoodsInfo> getUserGoods(Integer id){
try {
List<UserGoodsInfo> u= userRepository.findUserGoodsInfo(id);
log.info("getUserGoods: data="+ JSON.toJSONString(u));
return u;
}
catch (Exception e){
log.error("getUserGoods error!",e.getMessage());
return null;
}
}
}
GoodsServiceImpl.java文件:
package com.example.testone.service.impl;
import com.alibaba.fastjson.JSON;
import com.example.testone.bean.UserGoodsInfo;
import com.example.testone.entity.Goods;
import com.example.testone.entity.User;
import com.example.testone.repository.GoodsRepository;
import com.example.testone.repository.UserRepository;
import com.example.testone.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.transaction.Transactional;
import java.util.List;
@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
private GoodsRepository goodsRepository;
@Autowired
private UserRepository userRepository;
/**
* 新增一个 goods
* @param user_id
* @param title
* @return
*/
@Transactional(rollbackOn = Exception.class)
public Goods saveGoods(Integer user_id, String title){
try{
Goods g=new Goods();
g.setUser_id(user_id);
g.setTitle(title);
return goodsRepository.save(g);//原生方法
}
catch (Exception e){
log.error("saveGoods error!",e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return null;
}
}
public Goods getByUserid(Integer userid){
return goodsRepository.findByUser_id(userid);
}
public Boolean delByid(Integer userid){
try{
Goods g=goodsRepository.findByUser_id(userid);
if(g!=null){
goodsRepository.delete(g);
log.info("delByid : delete goods with user_id ="+userid+" is succeed !");
return true;
}
log.info("delByid : goods with user_id ="+userid+" is null!");
return false;
}
catch(Exception e){
log.error("delByid : Exception = "+e.getMessage());
return false;
}
}
/**
* 同时保存两个表的数据
* @param name
* @param interest
* @param title
* @return
*/
@Transactional(rollbackOn = Exception.class)
public Boolean saveBoth(String name,String interest,String title){
try{
User u=new User();
u.setName(name);
u.setInterest(interest);
User user_=userRepository.save(u);
log.info("saveBoth: user="+ JSON.toJSONString(u));
if(u!=null&&u.getId()!=null&&u.getId()>0){
Goods g=new Goods();
g.setUser_id(user_.getId());
g.setTitle(title);
goodsRepository.save(g);//原生方法
log.info("addUserGood: Goods="+ JSON.toJSONString(g));
}
return true;
}
catch(Exception e){
log.error("saveBoth : Exception = "+e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return false;
}
}
}
数据层,UserRepository.java文件:
package com.example.testone.repository;
import com.example.testone.bean.UserGoodsInfo;
import com.example.testone.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import javax.transaction.Transactional;
import java.util.List;
public interface UserRepository extends CrudRepository<User,Long>{
/**
* 根据id查询数据
* @param id
* @return
*/
@Query(value = "select * from user where id=?1 ", nativeQuery = true)
User findById(Integer id);
/**
* 自定义查询,根据user_id联合查询两个表获取数据
* @param id
* @return
*/
@Query(value = "SELECT new com.example.testone.bean.UserGoodsInfo(u, g) FROM User u, Goods g WHERE u.id = g.user_id and u.id=?1")
public List<UserGoodsInfo> findUserGoodsInfo(Integer id);
}
GoodsRepository.java文件:
package com.example.testone.repository;
import com.example.testone.bean.UserGoodsInfo;
import com.example.testone.entity.Goods;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface GoodsRepository extends JpaRepository<Goods,Long>{
@Query(value = "select * from goods where user_id=?1 ", nativeQuery = true)
Goods findByUser_id(Integer user_id);
@Query(value = "SELECT new com.example.testone.bean.UserGoodsInfo(u, g) FROM User u, Goods g WHERE u.id = g.user_id and u.id=?1")
public List<UserGoodsInfo> findUserGoodsInfo1(Integer id);
}
Entity层,User.java文件:
package com.example.testone.entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String interest;
}
Goods.java文件:
package com.example.testone.entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name = "goods")
public class Goods {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer user_id;
private String title;
}
自定义数据bean,UserGoodsInfo.java文件:
package com.example.testone.bean;
import com.example.testone.entity.Goods;
import com.example.testone.entity.User;
import lombok.Data;
import java.io.Serializable;
@Data
public class UserGoodsInfo implements Serializable {
private Goods goods;
private User user;
public UserGoodsInfo(){}
public UserGoodsInfo(Goods goods){
this.goods=goods;
User user=new User();
this.user=user;
}
public UserGoodsInfo(User user){
this.user=user;
Goods goods=new Goods();
this.goods=goods;
}
public UserGoodsInfo(User user, Goods goods) {
this.user = user;
this.goods = goods;
}
}
数据库建表语句:
user表:
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(200) DEFAULT NULL unique COMMENT '用户名',
`interest` varchar(200) DEFAULT NULL COMMENT 'user 兴趣',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
goods表:
CREATE TABLE `goods` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL COMMENT 'userID',
`title` varchar(200) NOT NULL unique COMMENT '商品名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.新增一条记录到User表,浏览器添加测试地址:http://localhost:8088/test/addUser?name=Tom&interest=cakes
2.新增goods一条记录:http://localhost:8088/test/addGoods?userId=1&title=Tom_title
3.测试事务回滚,同时添加两条记录,user和goods,测试接口如下:
http://localhost:8088/test/addBoth?name=Nancy&interest=yoga&title=Tom_title
4.多表联合查询,测试地址:http://localhost:8088/test/getUserGoods?userId=1
Spring boot启动类中添加注解:@EnableTransactionManagement
4.JpaRepository与CrudRepository区别和联系
JpaRepository 继承 PagingAndSortingRepository,PagingAndSortingRepository 继承 CrudRepository。
CrudRepository 提供基本的增删改查;
PagingAndSortingRepository 提供分页和排序方法;
JpaRepository 提供JPA需要的方法;
CrudRepository和PagingAndSortingRepository由Spring Data提供;
JpaRepository 由Spring Data JPA提供,而Spring Data JPA又是Spring Data的一个子项目,这就是两者的关系。通常,最好的想法是使用CrudRepository或PagingAndSortingRepository,具体取决于是否需要排序和分页。如果可能,应该避免使用JpaRepository,因为它将存储库与JPA持久性技术联系起来,并且在大多数情况下,我们甚至可能不会使用它提供的额外方法。
CrudRepository提供基本的增删改查方法,如下所示:
package org.springframework.data.repository;
import java.util.Optional;
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S var1);
<S extends T> Iterable<S> saveAll(Iterable<S> var1);
Optional<T> findById(ID var1);
boolean existsById(ID var1);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> var1);
long count();
void deleteById(ID var1);
void delete(T var1);
void deleteAll(Iterable<? extends T> var1);
void deleteAll();
}
JpaRepository提供的主要方法:
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
List<T> findAll();
List<T> findAll(Sort var1);
List<T> findAllById(Iterable<ID> var1);
<S extends T> List<S> saveAll(Iterable<S> var1);
void flush();
<S extends T> S saveAndFlush(S var1);
void deleteInBatch(Iterable<T> var1);
void deleteAllInBatch();
T getOne(ID var1);
<S extends T> List<S> findAll(Example<S> var1);
<S extends T> List<S> findAll(Example<S> var1, Sort var2);
}
5.注解(annotations)详解
@ResponseBody:表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@esponsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@Responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用。
@Controller:用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。
@RestController:用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集。
@RequestMapping:提供路由信息,负责URL到Controller中的具体函数的映射。
@EnableAutoConfiguration:SpringBoot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。
@ComponentScan:其实很简单,@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中,你一定都有用过@Controller,@Service,@Repository注解,查看其源码你会发现,他们中有一个共同的注解@Component,没错@ComponentScan注解默认就会装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中。当然,这个的前提就是你需要在所扫描包下的类上引入注解。
@Configuration:相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。
@Import:用来导入其他配置类。
@ImportResource:用来加载xml配置文件。
@Autowired:自动导入依赖的bean
@Service:一般用于修饰service层的组件
@Repository:使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。
@Bean:用@Bean标注方法等价于XML中配置的bean。
@Value:注入Spring boot application.properties配置的属性的值。示例代码:
1 @Value(value = “#{message}”)
2 private String message;
@Inject:等价于默认的@Autowired,只是没有required属性;
@Component:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Bean:相当于XML中的,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。
@AutoWired:自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。当加上(required=false)时,就算找不到bean也不报错。
@Qualifier:当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:
1 @Autowired
2 @Qualifier(value = “demoInfoService”)
3 private DemoInfoService demoInfoService;
@Resource(name=”name”,type=”type”):没有括号内内容的话,默认byName。与@Autowired类似。
推荐阅读
-
IntelliJ IDEA 生成Spring Boot项目
-
IntelliJ IDEA 新建Spring Boot项目
-
IDEA 快速创建 Spring boot 2.x Hello world
-
IntelliJ IDEA 构建maven多模块工程项目
-
IntelliJ IDEA 构建 Maven 多模块工程项目
-
Spring Boot项目基于Spring Cloud Feign调用第三方外部接口
-
Spring Boot项目中实现文件上传功能的示例
-
Spring Boot 项目运行无异常停止
-
如何将项目迁移至 Spring Boot 2.0 ?
-
Spring Boot(二)——项目热部署与程序发布