springboot jpa

来源:互联网 发布:埃及恐怖袭击 知乎 编辑:程序博客网 时间:2024/05/18 00:01

使用示例

由于Spring-data-jpa依赖于Hibernate。如果您对Hibernate有一定了解,下面内容可以毫不费力的看懂并上手使用Spring-data-jpa。如果您还是Hibernate新手,您可以先按如下方式入门,再建议回头学习一下Hibernate以帮助这部分的理解和进一步使用。


工程配置


在pom.xml中添加相关依赖,加入以下内容:

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

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>SpringBootJPA</artifactId><version>0.0.1-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><!-- Inherit defaults from Spring Boot --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.4.0.RELEASE</version></parent><!-- Add typical dependencies for a web application --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- spring-boot-starter-test 模块 --><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-data-jpa</artifactId></dependency><!-- <dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.19</version></dependency> --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- 热部署 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency></dependencies><!-- Package as an executable jar --><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>



在application.properties中配置:数据库连接信息(如使用嵌入式数据库则不需要)、自动创建表结构的设置,例如使用mysql的情况如下:

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver#JPA Configuration:  spring.jpa.properties.hibernate.hbm2ddl.auto=updatespring.jpa.database=MySQLspring.jpa.show-sql=true  

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:

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

至此已经完成基础配置,如果您有在Spring下整合使用过它的话,相信你已经感受到Spring Boot的便利之处:JPA的传统配置在persistence.xml文件中,但是这里我们不需要。当然,最好在构建项目时候按照之前提过的最佳实践的工程结构来组织,这样以确保各种配置都能被框架扫描到。

创建实体


创建一个User实体,包含id(主键)、name(姓名)、age(年龄)属性,通过ORM框架其会被映射到数据库表中,由于配置了hibernate.hbm2ddl.auto,在应用启动的时候框架会自动去数据库中创建对应的表。

package com.example.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;@Entity@Table(name="users")public class User implements Serializable{/** *  */private static final long serialVersionUID = 8674052384230501437L;@Id@GeneratedValueprivate Integer id;@Columnprivate String name;<pre code_snippet_id="1842706" snippet_file_name="blog_20160821_4_6492707" name="code" class="html">       @Columnprivate Integer age;;
@Columnprivate String email;seter getter。。。}


创建数据访问接口


下面针对User实体创建对应的Repository接口实现对该实体的数据访问,如下代码:
package com.example.dao;import java.io.Serializable;import java.util.List;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.query.Param;import com.example.domain.User;public interface UserRepository extends JpaRepository<User, Serializable>{   List<User> findByName(String name);        List<User> findByAndAge(String name,Integer age);      @Query("from User u where u.name=:name")   User findUser(@Param("name") String name);}

在Spring-data-jpa中,只需要编写类似上面这样的接口就可实现数据访问。不再像我们以往编写了接口时候还需要自己编写接口实现类,直接减少了我们的文件清单。

下面对上面的UserRepository做一些解释,该接口继承自JpaRepository,通过查看JpaRepository接口的API文档,可以看到该接口本身已经实现了创建(save)、更新(save)、删除(delete)、查询(findAll、findOne)等基本操作的函数,因此对于这些基础操作的数据访问就不需要开发者再自己定义。

在我们实际开发中,JpaRepository接口定义的接口往往还不够或者性能不够优化,我们需要进一步实现更复杂一些的查询或操作。由于本文重点在spring boot中整合spring-data-jpa,在这里先抛砖引玉简单介绍一下spring-data-jpa中让我们兴奋的功能,后续再单独开篇讲一下spring-data-jpa中的常见使用。

在上例中,我们可以看到下面两个函数:

  • User findByName(String name)
  • User findByNameAndAge(String name, Integer age)

它们分别实现了按name查询User实体和按name和age查询User实体,可以看到我们这里没有任何类SQL语句就完成了两个条件查询方法。这就是Spring-data-jpa的一大特性:通过解析方法名创建查询

除了通过解析方法名来创建查询外,它也提供通过使用@Query 注解来创建查询,您只需要编写JPQL语句,并通过类似“:name


单元测试
在完成了上面的数据访问接口之后,按照惯例就是编写对应的单元测试来验证编写的内容是否正确。这里就不多做介绍,主要通过数据操作和查询来反复验证操作的正确性e”来映射@Param指定的参数,就像例子中的第三个findUser函数一样。

package com.example;import java.util.List;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.example.dao.UserRepository;import com.example.domain.User;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes=Application.class)// 指定spring-boot的启动类//@SpringApplicationConfiguration(classes = Application.class)// public class ApplicationTests {@Autowired    private UserRepository userRepository;@Test    public void save() throws Exception {        userRepository.save(new User("AAA","AAA@qq.com",10));        userRepository.save(new User("BBB","AAA@qq.com", 20));        userRepository.save(new User("CCC","AAA@qq.com", 30));        userRepository.save(new User("DDD","AAA@qq.com", 40));        userRepository.save(new User("EEE","AAA@qq.com", 50));        userRepository.save(new User("FFF","AAA@qq.com", 60));        userRepository.save(new User("GGG","AAA@qq.com", 70));        userRepository.save(new User("HHH","AAA@qq.com", 80));        userRepository.save(new User("III","AAA@qq.com", 90));        userRepository.save(new User("JJJ","AAA@qq.com", 100));    }@Test public void findAll(){List<User> users = userRepository.findAll();System.out.println(users);}@Test public void findByName(){List userlist = userRepository.findByName("AAA");System.out.println(userlist);}@Test public void findUser(){User user = userRepository.findUser("AAA");System.out.println(user);}@Test public void findByNameAndAge(){List userlist = userRepository.findByAndAge("FFF",60);System.out.println(userlist);}@Test public void delete(){userRepository.delete(userRepository.findByName("AAA"));findAll();}@Test public void deleteAll(){userRepository.deleteAll();}}

package com.example;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;@ServletComponentScan@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

更改数据源

<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.19</version></dependency>

# 数据库访问配置# 主数据源,默认的#spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=root # 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,log4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据#spring.datasource.useGlobalDataSourceStat=true#JPA Configuration:  spring.jpa.properties.hibernate.hbm2ddl.auto=updatespring.jpa.database=MySQLspring.jpa.show-sql=true  

注入数据源

package com.example.configuration;import java.sql.SQLException;import javax.sql.DataSource;import org.springframework.boot.bind.RelaxedPropertyResolver;import org.springframework.context.EnvironmentAware;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.env.Environment;import org.springframework.transaction.annotation.EnableTransactionManagement;import com.alibaba.druid.pool.DruidDataSource;@Configuration@EnableTransactionManagementpublic class DataBaseConfiguration implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver;    @Override    public void setEnvironment(Environment env) {        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");    }        @Bean(destroyMethod = "close", initMethod = "init")    public DataSource writeDataSource() throws SQLException {        System.out.println("注入druid!!!");                       DruidDataSource dataSource = new DruidDataSource();        dataSource.setUrl(propertyResolver.getProperty("url"));        dataSource.setUsername(propertyResolver.getProperty("username"));//用户名        dataSource.setPassword(propertyResolver.getProperty("password"));//密码        dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));        dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));        dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));        dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));        dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));        dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));        dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis")));        dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));        dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow")));        dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle")));        dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn")));        dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements")));        dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));        //配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙        dataSource.setFilters(propertyResolver.getProperty("filters"));        return dataSource;    }}

测试 查看控制台输出是否有

注入druid!!!2016-08-21 13:47:24.166  INFO 6052 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited


转http://blog.didispace.com/springbootdata2/?utm_source=tuicool&utm_medium=referral

http://www.cnblogs.com/cl2Blogs/p/5679653.html



0 0
原创粉丝点击