美文网首页程序员
3.Spring Boot的数据访问

3.Spring Boot的数据访问

作者: 落叶飞逝的恋 | 来源:发表于2017-10-20 21:25 被阅读100次

Spring Data项目是Spring用来解决数据访问问题的一揽子解决方案。包含了大量了关系型数据库及非关系型数据库的解决方案。

1.Spring Data主要的包含的子项目

  • Spring Data Commons - Core Spring concepts underpinning every Spring Data project.

  • Spring Data Gemfire - Provides easy configuration and access to GemFire from Spring applications.

  • Spring Data JPA - Makes it easy to implement JPA-based repositories.

  • Spring Data KeyValue - Map-based repositories and SPIs to easily build a Spring Data module for key-value stores.

  • Spring Data LDAP - Provides Spring Data repository support for Spring LDAP.

  • Spring Data MongoDB - Spring based, object-document support and repositories for MongoDB.

  • Spring Data REST - Exports Spring Data repositories as hypermedia-driven RESTful resources.

  • Spring Data Redis - Provides easy configuration and access to Redis from Spring applications.

  • Spring Data for Apache Cassandra - Spring Data module for Apache Cassandra.

  • Spring Data for Apache Solr - Spring Data module for Apache Solr.

2.Spring Data Commons

Spring Data Commons是以上子项目的底层。它提供了统一的API。并且封装了Spring Data Repository抽象类。

不同的子项目在分别实现了自己的Repository。比如Spring Data JPA是JpaRepository。Spring Data MongoDB是MongoRepository等等。

Spring Data还是提供了根据属性进行计数、删除、查询等方法。

3.Spring Data Jpa(重点)

JPA即 Java Persistence API。JPA是基于O/R映射的标准规范。JPA主要实现由:Hibernate、EclipseLink、OpenJPA等实现。

  • 1.创建数据库
CREATE DATABASE IF NOT EXISTS springbootstudy CHARSET utf8 COLLATE utf8_general_ci;
  • 2.创建表
CREATE TABLE person(
 id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
 NAME VARCHAR(50) NOT NULL DEFAULT '' COMMENT '姓名',
 age TINYINT NOT NULL DEFAULT 0 COMMENT '年龄',
 gmt_create DATE COMMENT '创建时间',
 gmt_modified DATE COMMENT '更新时间'
)ENGINE=INNODB 

3.1 Spring Boot的支持

1.JDBC的配置

查看spring-boot-starter-data-jpa的pom文件可以看到该jar需要依赖于spring-boot-starter-jdbc。而Spring Boot对于JDBC的自动配置在org.springframework.boot.autoconfigure.jdbc包中。

通过查看DataSourceProperties类,得知通过spring.datasource为前缀的属性自动配置JDBC

Spring Boot对于JPA的自动配置放置在org.springframework.boot.autoconfigure.orm.jpa里。使用spring.jpa前缀进行配置。也通过源码看到Spring Boot默认的JPA的实现是Hibernate

3.2 实战代码配置

  • 配置spring.datasource
spring.datasource.username=root
spring.datasource.data-password=xxxx
spring.datasource.url=jdbc:mysql://localhost:3306/springdbootstudy?serverTimezone=Asia/Shanghai
spring.datasource.driverClassName = com.mysql.jdbc.Driver
  • 配置spring.jpa
# hibernate提供了根据实体类自动维护数据库表结构的功能。而none代表不做任何处理
spring.jpa.hibernate.ddl-auto=none
#显示真实的sql
spring.jpa.show-sql=true
#让控制台输出的json字符串格式更加美观
spring.jackson.serialization.indent-output=true
  • 1.创建person实体类
@Entity //@Entity注解指明这是一个和数据库表影射的实体类
@Table(name = "person")//@Table代表类名称和数据库表名称一致。

public class Person implements Serializable {

    private static final long serialVersionUID = -6082167954080285357L;

    /**
     * 自增id
     */
    @Id  //@Id注解指明这个属性映射为数据库的主键
    @GeneratedValue(strategy = GenerationType.AUTO) //@GeneratedValue注解默认使用主键生成方式为自增
    private long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 创建时间
     */
    @Column(name = "gmt_create")//@Cloumn注解来表明映射属性名和字段名。不注解的表明属性名称跟数据库表字段名称一致。
    private Date create;

    /**
     * 更新时间
     */
    @Column(name = "gmt_modified")
    private Date modified;

    //省略getter/setter
    
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", create=" + create +
                ", modified=" + modified +
                '}';
    }
}
  • 2.创建repository
public interface PersonRepository extends JpaRepository<Person, Long> {

    /**
     * 常规查询。根据属性名称来定义查询方法
     *
     * @param name
     * @return
     */
    List<Person> findByName(String name);

    /**
     * 查询多个属性之间用And连接
     *
     * @param name
     * @param age
     * @return
     */
    List<Person> findByNameAndAge(String name, String age);

    /**
     * 通过名称Like查询
     *
     * @param name
     * @return
     */
    List<Person> findByNameLike(String name);

    /**
     * 使用@Query查询,参数按照名称绑定
     *
     * @param name
     * @param age
     * @return
     */
    @Query("select p from Person p where p.name= :name and p.age= :age")
    Person withNameAndAgeQuery(@Param("name") String name, @Param("age") Integer age);
}
  • 测试
   @RequestMapping("save")
    public String insert() {
        String msg = null;
        try {
            Person p = new Person();
            p.setName("张三");
            p.setAge(18);
            p.setCreate(new Date());
            personRepository.save(p);
            msg = "成功";
        } catch (Exception ex) {
            msg = ex.getMessage();
        }
        return msg;
    }

    @RequestMapping("find")
    public String find() {
        try {
            //List<Person> ss=personRepository.findByName("张三");
//List<Person> ss=personRepository.withNameAndAge("张三",19);
//            for (Person p:ss){
//                System.out.println(p.toString());
//            }
            Person p = personRepository.withNameAndAgeQuery("张三", 18);
            System.out.println(p.toString());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return "sa";
    }

相关文章

网友评论

    本文标题:3.Spring Boot的数据访问

    本文链接:https://www.haomeiwen.com/subject/qshbuxtx.html