SpringBoot 使用JPA操作数据库

来源:互联网 发布:宿州市淘宝运营招聘 编辑:程序博客网 时间:2024/06/07 18:16

Spring-data-jpa的出现使我们不需要编写sql语句就能实现对数据库简单的增删改查,使用也非常方便

第一步:编写一个继承自JpaRepository的接口就能完成数据访问

import com.oldbig.domain.Girl;import org.springframework.data.jpa.repository.JpaRepository;public interface GirlRepository extends JpaRepository<Girl,Integer>{}

第二步:在pom.xml中添加相关依赖:

<dependency    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>

第三步:配置我们的数据库
在application.xml中配置:

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverjpa.hibernate.ddl-auto=update

这里的jpa配置为hibernate的配置属性,这是由于jpa封装了hibernate的缘故,jpa.hibernate.ddl-auto有以下属性:
create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

第四步:创建实体类(对应我们的数据库中的表,里面的实例代表我们表中的行,必须要有@Entity注解,必须要有唯一主键)

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.validation.constraints.Min;@Entitypublic class Girl {    @Id    @GeneratedValue //自增    private Integer id ;    private String cupSize;    @Min(value = 18,message = "未成年少女禁止入内")    private Integer age;    // 省略构造函数    // 省略getter和setter}

这样点击运行项目,就会自动帮我们创建好对应的表
这里写图片描述

就能通过我们的数据库接口类GirlRepository来访问我们的数据库,这里在service通过@Autowired将其注入,就能直接操作数据库了:

@Servicepublic class GirlService {    @Autowired    private GirlRepository girlRepository;    public Integer getAge(Integer id) throws Exception{        Girl girl = girlRepository.findOne(id);        Integer age = girl.getAge();        return age;    }}

拓展:
一,拓展数据访问接口类的方法:

public interface GirlRepository extends JpaRepository<Girl,Integer>{    //通过年龄来查询    List<Girl> findByAge(Integer age);    //通过年龄和cupSize    List<Girl> findByAgeAndCupSize(Integer age,String cupSize);    //通过年龄或者cupSize    List<Girl> findByAgeOrCupSize(Integer age,String cupSize);    //启用order by    List<Girl> findByAgeOrderByCupSize(Integer age)    //启用 distinct 标志,消除重复匹配到的数据     List<Girl> findDistinctByAgeOrCupSize(Integer age) }
原创粉丝点击