spring boot 高级 ——持久化
阅读原文时间:2021年04月25日阅读:3

Spring boot 持久化

  1. 引入

  Spring Boot就数据库持久化支持,支持原生Jdbc,也支持Mybatis和JPA。

2.Spring boot JdbcTemplate

引入spring-boot-starter-jdbc

那么只需要在需要使用的类中加入:

@Resource

private JdbcTemplate jdbcTemplate;

3.引入Maven依赖-mysql,jdbc

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<dependency>

&nbsp;&nbsp;&nbsp;&nbsp;<groupId>org.springframework.boot</groupId>

&nbsp;&nbsp;&nbsp;&nbsp;<artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

</dependency>

4.数据库信息配置

在application.properties文件中配置mysql连接配置文件

########################################################

###datasource

########################################################



spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.url = jdbc:mysql://localhost:3306/test

spring.datasource.username = root

spring.datasource.password = root

Yaml 方式

spring:

&nbsp;&nbsp;datasource:

&nbsp;&nbsp;&nbsp;&nbsp;driverClassName: com.mysql.jdbc.Driver

&nbsp;&nbsp;&nbsp;&nbsp;url : jdbc:mysql://localhost:3306/spring-boot-demo?useUnicode=true&characterEncoding=utf-8

&nbsp;&nbsp;&nbsp;&nbsp;username : root

&nbsp;&nbsp;&nbsp;&nbsp;password : root

5.代码示例

1) Dao

声明为:@Repository,引入JdbcTemplate

public Demo getById(long id){

String sql = "select *from Demo where id=?";

RowMapper<Demo> rowMapper = new BeanPropertyRowMapper<Demo>(Demo.class);

return jdbcTemplate.queryForObject(sql, rowMapper,id);

}

       2)Service

声明为:@Service 引入dao

@Resource

private DemoDao demoDao;



public void getById(Long id){

&nbsp;demoDao.getById(id);

}

     3)Controller

@Resource

private DemoService demoService;



@RequestMapping("/getById")

public Demo getById(long id){

return demoService.getById(id);

}

Springboot 测试

Spring boot-spring data Jpa

  1. Spring data jpa简介

1.Spring data

Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得数据库的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。此外,它还支持基于关系型数据库的数据服务,如Oracle RAC等。对于拥有海量数据的项目,可以用Spring Data来简化项目的开发,就如Spring Framework对JDBC、ORM的支持一样,Spring Data会让数据的访问变得更加方便。

2.Jpa

“规范”: 所谓的规范意指明文规定或约定俗成的标准。如:道德规范、技术规范,公司管理规范。那么“持久化规范”就是Sun针对持久化这一层操作指定的规范,如果没有指定JPA规范,那么新起的框架就随意按照自己的标准来了,那我们开发人员就没法把我们的经历全部集中在我们的业务层上,而是在想如何进行兼容,这种情况有点像Android开发,Android本身有官方的SDK,但是由于SDK过于开源了,结果导致很多厂商基于SDK二次开发,但是兼容性就不是很好,最好的例子就是Android的头像上传,就是一件很烦人的事情。好了,JPA就介绍到这里。

3.Hibernate

          JPA是一种规范,而Hibernate是它的一种实现。除了Hibernate,还有EclipseLink(曾经的 toplink),OpenJPA等可供选择,所以使用Jpa的一个好处是,可以更换实现而不必改动太多代码。

4.Spring data Jpa

Spring Data JPA能干什么

可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。

首先我们需要清楚的是Spring Data是一个开源框架,在这个框架中Spring Data JPA只是这个框架中的一个模块,所以名称才叫Spring Data JPA。如果单独使用JPA开发,你会发现这个代码量和使用JDBC开发一样有点烦人,所以Spring Data JPA的出现就是为了简化JPA的写法,让你只需要编写一个接口继承一个类就能实现CRUD操作了

       5)Spirng data jpa常用接口或类

Spring Data 的一个核心接口为我们提供了常用的接口

Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法 :

 public interface Repository { }

1. Repository是一个空接口,即是一个标记接口;

2. 若我们定义的接口继承了Repository,则该接口会被IOC容器识别为一个Repository Bean纳入到IOC容器中,进而可以在该接口中定义满足一定规范的方法。

3. 实际上也可以通过@RepositoryDefinition,注解来替代继承Repository接口。

4. 查询方法以find | read | get开头;

5. 涉及查询条件时,条件的属性用条件关键字连接,要注意的是条件属性以首字母大写。

6.使用@Query注解可以自定义JPQL语句实现更灵活的查询。

List<User> getByNameOrAge(String name,Integer age);

select * from t_user where name=? or age=?

CrudRepository 接口提供了最基本的对实体类的添删改查操作

&nbsp;--T save(T entity);//保存单个实体&nbsp; &nbsp;

&nbsp;&nbsp;--Iterable<T> save(Iterable<? extends T> entities);//保存集合&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--T findOne(ID id);//根据id查找实体&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--boolean exists(ID id);//根据id判断实体是否存在&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--Iterable<T> findAll();//查询所有实体,不用或慎用!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--long count();//查询实体数量&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--void delete(ID id);//根据Id删除实体&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--void delete(T entity);//删除一个实体&nbsp; &nbsp;

&nbsp;&nbsp;--void delete(Iterable<? extends T> entities);//删除一个实体的集合&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;

&nbsp;&nbsp;--void deleteAll();//删除所有实体,不用或慎用!&nbsp; &nbsp;

PagingAndSortingRepository接口

该接口提供了分页与排序功能 &nbsp;&nbsp;

&nbsp;--Iterable<T> findAll(Sort sort); //排序 &nbsp;&nbsp;&nbsp;

--Page<T> findAll(Pageable pageable); //分页查询(含排序功能)

JpaRepository:查找所有实体,排序、查找所有实体,执行缓存与数据库同步

JpaSpecificationExecutor:不属于Repository体系,实现一组 JPA Criteria 查询相关的方法,封装  JPA Criteria 查询条件。通常使用匿名内部类的方式来创建该接口的对象。

自定义 Repository:可以自己定义一个MyRepository接口 extends JpaRepository。

  1. 1. 1. 引入Maven依赖-mysql,springdatajpa

    mysql

    mysql-connector-java

        org.springframework.boot

        spring-boot-starter-data-jpa

  2. 1. 1. 配置jdbc spring data jpa

在application.properties文件中配置mysql连接配置文件

#tomcat server port

server.port=80



########################################################

###datasource

########################################################

spring.datasource.url = jdbc:mysql://localhost:3306/test

spring.datasource.username = root

spring.datasource.password = root

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.max-active=20

spring.datasource.max-idle=8

spring.datasource.min-idle=8

spring.datasource.initial-size=10



########################################################

### Java Persistence Api&nbsp;&nbsp;(可以不设置,用默认的)

########################################################

# Specify the DBMS

spring.jpa.database = MYSQL

# Show or not log for each sql query

spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)

spring.jpa.hibernate.ddl-auto = update

# Naming strategy

#[org.hibernate.cfg.ImprovedNamingStrategy &nbsp;#org.hibernate.cfg.DefaultNamingStrategy]

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# stripped before adding them to the entity manager)

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
  1. 1. 1. 代码示例

  2. 创建实体类User。

    package cn.itsource.springboot.datajpa.domain;

    import java.io.Serializable;

    import javax.persistence.Column;

    import javax.persistence.Entity;

    import javax.persistence.GeneratedValue;

    import javax.persistence.Id;

    import javax.persistence.Table;

    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

    @Entity

    @Table(name="t_user")

    //加上json转换时忽略的属性,否则出错

    @JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})

    public class User implements Serializable{

    @Id

    @GeneratedValue

    private Long id;

    @Column

    private String name;

    //Getter/setter

    }

(2) 创建repository操作持久化接口(继承自JpaRepository)。

import&nbsp;org.springframework.data.jpa.repository.JpaRepository;



import&nbsp;cn.itsource.springboot.datajpa.domain.User;



public&nbsp;interface&nbsp;UserRepository extends&nbsp;JpaRepository<User, Long>{

public&nbsp;User getByName(String name);

}
  1. 创建service类。

    package cn.itsource.springboot.datajpa.service;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.stereotype.Service;

    import cn.itsource.springboot.datajpa.dao.UserRepository;

    import cn.itsource.springboot.datajpa.domain.User;

    @Service

    public class UserService {

    @Autowired

    private UserRepository userRepository;

    public User get(Long id){

    return userRepository.getOne(id);

    }

    public User getByName(String name){

    return userRepository.getByName(name);

    }

    public User save(User user){

    return userRepository.save(user);

    }

    public User update(User user) {

    return userRepository.save(user);

    }

    public void delete(Long id){

    userRepository.delete(id);

    }

    }

  2. 创建restful controller。

  3. package cn.itsource.springboot.datajpa.controller;

    import&nbsp;org.springframework.beans.factory.annotation.Autowired;
    
    import&nbsp;org.springframework.web.bind.annotation.PathVariable;
    
    import&nbsp;org.springframework.web.bind.annotation.RequestMapping;
    
    import&nbsp;org.springframework.web.bind.annotation.RequestMethod;
    
    import&nbsp;org.springframework.web.bind.annotation.ResponseBody;
    
    import&nbsp;org.springframework.web.bind.annotation.RestController;
    
    
    
    import&nbsp;cn.itsource.springboot.datajpa.domain.User;
    
    import&nbsp;cn.itsource.springboot.datajpa.service.UserService;
    
    
    
    @RestController
    
    public&nbsp;class&nbsp;UserController {
    
    
    
    @Autowired
    
    private&nbsp;UserService userService;
    
    
    
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    
    @ResponseBody
    
    public&nbsp;User get(@PathVariable&nbsp;Long id) {
    
    User user&nbsp;= userService.get(id);
    
    System.out.println("user="&nbsp;+ user);
    
    return&nbsp;user;
    
    }
    
    
    
    @RequestMapping(value = "/user/name/{name}", method = RequestMethod.GET)
    
    @ResponseBody
    
    public&nbsp;User get(@PathVariable&nbsp;String name) {
    
    User user&nbsp;= userService.getByName(name);
    
    System.out.println("user="&nbsp;+ user);
    
    return&nbsp;user;
    
    }
    
    
    
    @RequestMapping(value = "/user/add", method = RequestMethod.GET)
    
    @ResponseBody
    
    public&nbsp;User add() {
    
    User user&nbsp;= new&nbsp;User();
    
    user.setName("itsource");
    
    user&nbsp;= userService.save(user);
    
    return&nbsp;user;
    
    }
    
    
    
    @RequestMapping(value = "/user/update", method = RequestMethod.GET)
    
    @ResponseBody
    
    public&nbsp;User update() {
    
    User user&nbsp;= new&nbsp;User();
    
    user.setId(2L);
    
    user.setName("源码时代");
    
    user&nbsp;= userService.update(user);
    
    return&nbsp;user;
    
    }
    
    
    
    @RequestMapping(value = "/user/delete", method = RequestMethod.GET)
    
    @ResponseBody
    
    public&nbsp;String delete() {
    
    userService.delete(2L);
    
    return&nbsp;"success";
    
    }
    
    }
  4. 启动类

    package cn.itsource.springboot.datajpa;

    import org.springframework.boot.SpringApplication;

    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication

    public class App {

    public static void main(String[] args) {

    SpringApplication.run(App.class, args);

    }

    }

  5. 测试;

启动项目分别测试对应的Restful接口功能。

  1. 注意事项

JSON转换异常处理:

① 在Domain类中排除注入的特殊属性hibernateLazyInitializer和handler

@Entity

@Table(name="t_user")

//加上json转换时忽略的属性,否则出错

@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})

public class User implements Serializable{....}

② 增加Jackson配置类

package&nbsp;cn.itsource.springboot.datajpa.config;

import&nbsp;com.fasterxml.jackson.databind.ObjectMapper;

import&nbsp;com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;

import&nbsp;org.springframework.context.annotation.Configuration;

import&nbsp;org.springframework.http.converter.HttpMessageConverter;

import&nbsp;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import&nbsp;org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;



import&nbsp;java.util.List;

/**

&nbsp;* 防止在使用jpa/hibernate,如果实体字段上加有FetchType.LAZY,并使用jackson序列化为json串时,

&nbsp;* 会遇到SerializationFeature.FAIL_ON_EMPTY_BEANS异常

&nbsp;* @author&nbsp;nixianhua

&nbsp;*

&nbsp;*/

@Configuration

public&nbsp;class&nbsp;JacksonConfiguration extends&nbsp;WebMvcConfigurerAdapter {

&nbsp;&nbsp;&nbsp;&nbsp;@Override

&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;configureMessageConverters(List<HttpMessageConverter<?>> converters) {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;converters.add(jacksonMessageConverter());

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super.configureMessageConverters(converters);

&nbsp;&nbsp;&nbsp;&nbsp;}



&nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;MappingJackson2HttpMessageConverter jacksonMessageConverter() {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MappingJackson2HttpMessageConverter messageConverter&nbsp;= new&nbsp;MappingJackson2HttpMessageConverter();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ObjectMapper mapper&nbsp;= new&nbsp;ObjectMapper();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mapper.registerModule(new&nbsp;Hibernate4Module());

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messageConverter.setObjectMapper(mapper);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;messageConverter;

&nbsp;&nbsp;&nbsp;&nbsp;}

}
  1. 1. Spring boot-mybatis
    1. 集成Mybatis
  2. 新建maven project;

新建一个maven project,取名为:spring-boot-mybatis

  1. 在pom.xml文件中引入相关依赖;

(1)基本依赖,jdk版本号;

(2)mysql驱动,mybatis依赖包,mysql分页PageHelper:

&nbsp;&nbsp;&nbsp;<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- mysql&nbsp;数据库驱动. -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>



<!-- spring-boot mybatis依赖 -->

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.3.0</version>

</dependency>



<!-- spring boot mybatis 分页插件 -->

<dependency>

<groupId>com.github.pagehelper</groupId>

<artifactId>pagehelper-spring-boot-starter</artifactId>

<version>1.2.2</version>

</dependency>
  1. 创建启动类App.java

    @SpringBootApplication

    @MapperScan("cn.itsource.springboot.mybatis.mapper")

    public class App

    {

        public static void main( String[] args )

        {

            SpringApplication.run(App.class, args);

        }

    }

//这里和以往不一样的地方就是MapperScan的注解,这个是会扫描该包下的接口

  1. 在application.properties添加配置文件;

    #tomcat server port

    server.port=80

    ########################################################

    ###datasource

    ########################################################

    spring.datasource.url = jdbc:mysql://localhost:3306/test

    spring.datasource.username = root

    spring.datasource.password = root

    spring.datasource.driverClassName = com.mysql.jdbc.Driver

    spring.datasource.max-active=20

    spring.datasource.max-idle=8

    spring.datasource.min-idle=8

    spring.datasource.initial-size=10

  2. 编写User测试类;

    package cn.itsource.springboot.mybatis.domain;

    import java.io.Serializable;

    public class User implements Serializable {

    private static final long serialVersionUID = -2107513802540409419L;

    private Long id;

    private String name;

    getter/setter…

    }

  3. 编写UserMapper;

注解方式 :

package&nbsp;cn.itsource.springboot.mybatis.mapper;



import&nbsp;java.util.List;



import&nbsp;org.apache.ibatis.annotations.Select;



import&nbsp;cn.itsource.springboot.mybatis.domain.User;

@Mapper

public&nbsp;interface&nbsp;UserMapper {

@Select("select * from t_user t_user name = #{name}")

List<User> likeName(String name);



@Select("select * from t_user where id = #{id}")

User getById(long&nbsp;id);



@Select("select name from t_user where id = #{id}")

String getNameById(long&nbsp;id);

}

XML方式:

package&nbsp;cn.itsource.springboot.mybatis.mapper;



import&nbsp;java.util.List;



import&nbsp;cn.itsource.springboot.mybatis.domain.User;

public&nbsp;interface&nbsp;UserMapper {

List<User> likeName(String name);

User getById(long&nbsp;id);

String getNameById(long&nbsp;id);

}

然后在resources下增加mapper.xml文件

/cn/itsource/springboot/mybatis/mapper/UserMapper.xml



<?xml&nbsp;version="1.0"&nbsp;encoding="UTF-8"&nbsp;?>

<!DOCTYPE&nbsp;mapper

&nbsp;&nbsp;PUBLIC&nbsp;"-//mybatis.org//DTD Mapper 3.0//EN"

&nbsp;&nbsp;"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper&nbsp;namespace="cn.itsource.springboot.mybatis.mapper.UserMapper">

<select&nbsp;parameterType="string"&nbsp;resultType="User"&nbsp;id="likeName">&nbsp;

select * from t_user where name like concat('%',#{name},'%')

</select>

<select&nbsp;parameterType="long"&nbsp;resultType="User"&nbsp;id="getById">&nbsp;

select * from t_user where id = #{id}

</select>

<select&nbsp;parameterType="long"&nbsp;resultType="string"&nbsp;id="getNameById">&nbsp;

select name from t_user where id = #{id}

</select>

<insert&nbsp;parameterType="User"&nbsp;id="save"&nbsp;keyColumn="id"

keyProperty="id"&nbsp;useGeneratedKeys="true">&nbsp;

insert into t_user(name) values(#{name})

</insert>

</mapper>



最后需要在application.properties中增加别名包和mapper xml扫描包的配置

## Mybatis&nbsp;config

mybatis.typeAliasesPackage=cn.itsource.springboot.mybatis.domain

mybatis.mapperLocations=classpath:mapper/*.xml



#Yaml 配置



# Mybatis配置

mybatis:

&nbsp;&nbsp;typeAliasesPackage: cn.itsource.domain

&nbsp;&nbsp;mapperLocations: classpath:cn/itsource/dao/mapper/*.xml
  1. 编写UserService

    package cn.itsource.springboot.mybatis.service;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.stereotype.Service;

    import cn.itsource.springboot.mybatis.domain.User;

    import cn.itsource.springboot.mybatis.mapper.UserMapper;

    @Service

    public class UserService {

    @Autowired

    private UserMapper userMapper;

    public User get(Long id){

    return userMapper.getById(id);

    }

    }

  2. 编写UserController;

    package cn.itsource.springboot.mybatis.controller;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.web.bind.annotation.PathVariable;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.ResponseBody;

    import org.springframework.web.bind.annotation.RestController;

    import cn.itsource.springboot.mybatis.domain.User;

    import cn.itsource.springboot.mybatis.service.UserService;

    @RestController

    public class UserController {

    @Autowired

    private UserService userService;

    @RequestMapping("/user/{id}")

    @ResponseBody

    public User get(@PathVariable Long id) {

    return userService.get(id);

    }

    }

//运行访问:http://127.0.0.1/user/1  就可以看到返回的数据了

3.使用PageHelper分页

在application.properties中配置分页插件

#pagehelper.

pagehelper.autoDialect=true

pagehelper.closeConn=true

在调用mapper的前面开启分页功能

package cn.itsource.springboot.mybatis.service;



import java.util.List;



import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;



import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;



import cn.itsource.springboot.mybatis.domain.User;

import cn.itsource.springboot.mybatis.mapper.UserMapper;



@Service

public class UserService {

@Autowired

private UserMapper userMapper;



public User get(Long id){

return userMapper.getById(id);

}



public PageInfo<User> likeName(String name,Integer p) {

PageHelper.startPage(p, 1);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List<User> users = userMapper.likeName(name);

return new PageInfo<>(users);

}

}

完成CRUD

略….

1.事务控制

只需要在需要事务控制的方法或类(全部方法有效)上增加 @Transactional注解

2.JUnit测试

① 添加spring-boot-starter-test

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

</dependency>

② 添加测试类,类似于spring的测试,增加spring-boot的测试环境注解

//Spring测试环境

@RunWith(SpringJUnit4ClassRunner.class)

//SpringBoot测试,并指定启动类

@SpringBootTest(classes = App.class)

public&nbsp;class&nbsp;UserServiceTest {



@Autowired

private&nbsp;UserService userService;



@Test

public&nbsp;void&nbsp;testGet() throws&nbsp;Exception {

User user&nbsp;= userService.get(1L);

System.out.println(user.getName());

}

}

注意:在spring-boot-jpa的测试中,如果测试方法中使用的是 Repository.getOne方法,那么会报no Session异常,解决方法是在测试方法上增加@Transactional注解,如果使用的是findOne方法,那么不会有问题。 所以,一般建议都在test方法上增加 @Transactional注解。

注意:如果在测试方法执行完后要恢复测试前的数据,请在测试方法上增加@Rollback注解。

3.小结

本节综合集成了SpringWeb开发所需要的主要模块,从示例可以看出,spring-boot 大大简化了我们对于spring项目的开发,前提是要按照spring-boot的规则使用。