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>

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

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

</dependency>

<dependency>

<groupId>org.spring work.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:

  datasource:

    driverClassName: com.mysql.jdbc.Driver

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

    username : root

    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.queryFor (sql, rowMapper,id);

}

       2)Service

声明为:@Service 引入dao

@Resource

private DemoDao demoDao;



public void getById(Long id){

 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 work对JDBC、ORM的支持一样,Spring Data会让数据的访问变得更加方便。

2.Jpa

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

3.Hibernate

          JPA是一种规范,而Hibernate是它的一种实现。除了Hibernate,还有Eclipse (曾经的 top ),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<T, ID extends Serializable> { }

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 接口提供了最基本的对实体类的添删改查操作

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

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

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

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

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

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

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

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

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

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

PagingAndSortingRepository接口

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

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

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

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

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

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

 

 

      1. 引入Maven依赖-mysql,springdatajpa
<dependency>

<groupId>mysql</groupId>

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

</dependency>



<dependency>

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

    <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>
      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  (可以不设置,用默认的)

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

# Specify the DBMS

spring.jpa.data  = 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  #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. 创建实体类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.faster .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 org.spring work.data.jpa.repository.JpaRepository;



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



public interface UserRepository extends JpaRepository<User, Long>{

public User getByName(String name);

}

 

  1. 创建service类。
package cn.itsource.springboot.datajpa.service;



import org.spring work.beans.factory.annotation.Autowired;

import org.spring work.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);

}



}

 

 

  1. 创建restful controller。
  2. 
    package cn.itsource.springboot.datajpa.controller;
    
    
    
    import org.spring work.beans.factory.annotation.Autowired;
    
    import org.spring work.web.bind.annotation.PathVariable;
    
    import org.spring work.web.bind.annotation.RequestMapping;
    
    import org.spring work.web.bind.annotation.RequestMethod;
    
    import org.spring work.web.bind.annotation.ResponseBody;
    
    import org.spring work.web.bind.annotation.RestController;
    
    
    
    import cn.itsource.springboot.datajpa.domain.User;
    
    import cn.itsource.springboot.datajpa.service.UserService;
    
    
    
    @RestController
    
    public class UserController {
    
    
    
    @Autowired
    
    private UserService userService;
    
    
    
    @RequestMapping(value = \"/user/{id}\", method = RequestMethod.GET)
    
    @ResponseBody
    
    public User get(@PathVariable Long id) {
    
    User user = userService.get(id);
    
    System.out.println(\"user=\" + user);
    
    return user;
    
    }
    
    
    
    @RequestMapping(value = \"/user/name/{name}\", method = RequestMethod.GET)
    
    @ResponseBody
    
    public User get(@PathVariable String name) {
    
    User user = userService.getByName(name);
    
    System.out.println(\"user=\" + user);
    
    return user;
    
    }
    
    
    
    @RequestMapping(value = \"/user/add\", method = RequestMethod.GET)
    
    @ResponseBody
    
    public User add() {
    
    User user = new User();
    
    user.setName(\"itsource\");
    
    user = userService.save(user);
    
    return user;
    
    }
    
    
    
    @RequestMapping(value = \"/user/update\", method = RequestMethod.GET)
    
    @ResponseBody
    
    public User update() {
    
    User user = new User();
    
    user.setId(2L);
    
    user.setName(\"源码时代\");
    
    user = userService.update(user);
    
    return user;
    
    }
    
    
    
    @RequestMapping(value = \"/user/delete\", method = RequestMethod.GET)
    
    @ResponseBody
    
    public String delete() {
    
    userService.delete(2L);
    
    return \"success\";
    
    }
    
    }

     

  1. 启动类
package cn.itsource.springboot.datajpa;



import org.spring work.boot.SpringApplication;

import org.spring work.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication

public class App {

public static void main(String[] args) {

SpringApplication.run(App.class, args);

}

}

 

  1. 测试;

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

 

  1. 注意事项

JSON转换异常处理:

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

@Entity

@Table(name=\"t_user\")

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

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

public class User implements Serializable{....}

 

② 增加Jackson配置类

package cn.itsource.springboot.datajpa.config;

import com.faster .jackson.databind. Mapper;

import com.faster .jackson.datatype.hibernate4.Hibernate4Module;

import org.spring work.context.annotation.Configuration;

import org.spring work.http.converter.HttpMessageConverter;

import org.spring work.http.converter.json.MappingJackson2HttpMessageConverter;

import org.spring work.web.servlet.config.annotation.WebMvcConfigurerAdapter;



import java.util.List;

/**

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

 * 会遇到SerializationFeature.FAIL_ON_EMPTY_BEANS异常

 * @author nixianhua

 *

 */

@Configuration

public class JacksonConfiguration extends WebMvcConfigurerAdapter {

    @Override

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

        converters.add(jacksonMessageConverter());

        super.configureMessageConverters(converters);

    }



    private MappingJackson2HttpMessageConverter jacksonMessageConverter() {

        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

         Mapper mapper = new  Mapper();

        mapper.registerModule(new Hibernate4Module());

        messageConverter.set Mapper(mapper);

        return messageConverter;

    }

}

 

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

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

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

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

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

    

   <dependency>

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

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

</dependency>

<!-- mysql 数据库驱动. -->

<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

 

  1. 编写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...



}

 

  1. 编写UserMapper;

注解方式 :

package cn.itsource.springboot.mybatis.mapper;



import java.util.List;



import org.apache.ibatis.annotations.Select;



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

@Mapper

public interface 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 id);



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

String getNameById(long id);

}

 

方式:

package cn.itsource.springboot.mybatis.mapper;



import java.util.List;



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

public interface UserMapper {

List<User> likeName(String name);

User getById(long id);

String getNameById(long id);

}

 

然后在resources下增加mapper. 文件

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



<?  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=\"cn.itsource.springboot.mybatis.mapper.UserMapper\">

<select parameterType=\"string\" resultType=\"User\" id=\"likeName\"> 

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

</select>

<select parameterType=\"long\" resultType=\"User\" id=\"getById\"> 

select * from t_user where id = #{id}

</select>

<select parameterType=\"long\" resultType=\"string\" id=\"getNameById\"> 

select name from t_user where id = #{id}

</select>

<insert parameterType=\"User\" id=\"save\" keyColumn=\"id\"

keyProperty=\"id\" useGeneratedKeys=\"true\"> 

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

</insert>

</mapper>



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

## Mybatis config

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

mybatis.mapperLocations=classpath:mapper/*. 



#Yaml 配置



# Mybatis配置

mybatis:

  typeAliasesPackage: cn.itsource.domain

  mapperLocations: classpath:cn/itsource/dao/mapper/*. 

 

 

  1. 编写UserService
package cn.itsource.springboot.mybatis.service;



import org.spring work.beans.factory.annotation.Autowired;

import org.spring work.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);

}

}

 

  1. 编写UserController;
package cn.itsource.springboot.mybatis.controller;



import org.spring work.beans.factory.annotation.Autowired;

import org.spring work.web.bind.annotation.PathVariable;

import org.spring work.web.bind.annotation.RequestMapping;

import org.spring work.web.bind.annotation.ResponseBody;

import org.spring work.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.spring work.beans.factory.annotation.Autowired;

import org.spring work.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);

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

return new PageInfo<>(users);

}

}

 

 

完成CRUD

略....

1.事务控制

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

2.JUnit测试

① 添加spring-boot-starter-test

<dependency>

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

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

</dependency>

 

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


//Spring测试环境

@RunWith(SpringJUnit4ClassRunner.class)

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

@SpringBootTest(classes = App.class)

public class UserServiceTest {



@Autowired

private UserService userService;



@Test

public void testGet() throws Exception {

User user = 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的规则使用。

收藏 打印