目录结构

首先在Maven项目中添加依赖包

<!-- https://mvnrepository.com/artifact/org.springframework.data/
spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.3.RELEASE</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/
hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
JPA是Java Persistence API的简称,中文名Java持久层API,
是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。 
Sun引入新的JPA ORM规范出于两个原因:其一,简化现有Java EE和Java SE应用开发工作;其二,
Sun希望整合ORM技术,实现天下归一。

优势在于:
1.开发者面向JPA规范的接口,但底层的JPA实现可以任意切换:觉得Hibernate好的,可以选择Hibernate JPA实现;觉得TopLink好的,可以选择TopLink JPA实现。
2.这样开发者可以避免为使用Hibernate学习一套ORM框架,为使用TopLink又要再学习一套ORM框架。

在项目中使用方式为:在实体类中,使用 @Entity 、 @Table 、@Id 与 @Column 等注解。

  • book.java
  • package the_data_jpa.entity;
    
    import javax.persistence.*;
    
    @Entity
    @Table(name = "book")//数据表名
    public class Book {
    @Id
    @GeneratedValue//数据库字段名
    private int id; private String name;
    private float price; public int getId() {
    return id;
    } public void setId(int id) {
    this.id = id;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    } public float getPrice() {
    return price;
    } public void setPrice(float price) {
    this.price = price;
    } @Override
    public String toString() {
    return "Book{" +
    "id=" + id +
    ", name='" + name + '\'' +
    ", price=" + price +
    '}';
    }
    }

BookDAO

我们只需要使用

Hibernate 查询语句HQL基本语法

package the_data_jpa.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import the_data_jpa.entity.Book; import java.util.List; public interface BookDAO extends JpaRepository<Book, Integer> { Book findByNameAndPrice(String name, float price); List<Book> findByNameOrPrice(String name, float price); Book findByName(String name); @Query("select id, name, price from Book as s where s.name like 'w%'")
Book findwoyebuzhidaozenmshuo(); }

SpringConfig

package the_data_jpa;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties; @Configuration
@ComponentScan(basePackages = "the_data_jpa")//扫描当前包
@PropertySource("classpath:jdbc.properties")//加载外部文件
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "the_data_jpa.dao")
public class SpringConfig {
@Bean
DataSource dataSource(Environment env) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("driver"));
dataSource.setJdbcUrl(env.getProperty("url"));
dataSource.setUser(env.getProperty("name"));
dataSource.setPassword(env.getProperty("password"));
return dataSource;
} @Bean
PlatformTransactionManager transactionManager (DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} // SqlSessionFactory
@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory (DataSource dataSource) {
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(dataSource);
bean.setPackagesToScan("the_data_jpa.entity");
bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.show_sql", "true");//开启手动输入sql
properties.setProperty("hibernate.format_sql", "true");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
bean.setJpaProperties(properties); return bean;
} }

BookService

package the_data_jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import the_data_jpa.dao.BookDAO;
import the_data_jpa.entity.Book; import java.util.List;
import java.util.Optional; @Service
public class BookService {
@Autowired
private BookDAO bookDAO; public Optional<Book> getBookById() {
Optional<Book> book = bookDAO.findById(3);
System.out.println(book);
return book;
} public Book findBookByCond(String name, float price) {
return bookDAO.findByNameAndPrice(name, price);
} public Book findByName(String name) {
return bookDAO.findByName(name);
} public Book findFuzzy() {
return bookDAO.findwoyebuzhidaozenmshuo();
} public List<Book> listCond(String name, float price) {
return bookDAO.findByNameOrPrice(name, price);
} }

Main

package the_data_jpa;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import the_data_jpa.entity.Book; import java.sql.SQLException;
import java.util.List; public class Main {
public static void main(String[] args) throws SQLException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); BookService bean = context.getBean(BookService.class);
List<Book> book = bean.listCond("Java EE", 44);
System.out.println(book);
//System.out.println(war_and_peace.getPrice());
}
}

 结果

什么是APJ与使用Spring Data JPA 基于Hibernate的更多相关文章

  1. java(样品集成框架spring、spring mvc、spring data jpa、hibernate)

    这是你自己的参考springside集成框架的开源项目.主要的整合spring.spring mvc.spring data jpa.hibernate几个框架,对于这些框架中仍然感觉更舒适sprin ...

  2. spring data jpa、Hibernate开启全球唯一UUID设置

    spring data jpa.Hibernate开启全球唯一UUID设置 原文链接:https://www.cnblogs.com/blog5277/p/10662079.html 原文作者:博客园 ...

  3. 转:spring data jpa、 hibernate、 jpa 三者之间的关系

    原文链接:spring data jpa. hibernate. jpa 三者之间的关系 spring data jpa hibernate jpa 三者之间的关系 JPA规范与ORM框架之间的关系是 ...

  4. 用Spring Data JPA 基于内存存储pojo的简单案例

    poject结构如下: Customer.java类是一个pojo类,代码如下: package hello; import javax.persistence.Entity; import java ...

  5. jdbc、jpa、spring data jpa、hibernate、mybatis之间的关系及区别

    基础概念 jdbc(Java DataBase Connectivity)是java连接数据库操作的原生接口.JDBC对Java程序员而言是API,对实现与数据库连接的服务提供商而言是接口模型.作为A ...

  6. 简述 JPA 与 Spring Data JPA 与 Hibernate

    1.JPA是什么?以及相关概述 JPA的是 Java Persistence API 的简写,是Sun官方提出的一种ORM规范! Sun提出此规范有2个原因: 1.简化现有Java EE和Java S ...

  7. spring data jpa、 hibernate、 jpa 三者之间的关系

    http://www.cnblogs.com/xiaoheike/p/5150553.html JPA规范与ORM框架之间的关系是怎样的呢? JPA规范本质上就是一种ORM规范,注意不是ORM框架-- ...

  8. spring data jpa 、hibernate、jpa之间的关系

    引用:http://blog.csdn.net/u014421556/article/details/52635000 hibernate作为JPA的实现.   JPA规范与ORM框架之间的关系   ...

  9. javaweb各种框架组合案例(六):springboot+spring data jpa(hibernate)+restful

    一.介绍 1.springboot是spring项目的总结+整合 当我们搭smm,ssh,ssjdbc等组合框架时,各种配置不胜其烦,不仅是配置问题,在添加各种依赖时也是让人头疼,关键有些jar包之间 ...

随机推荐

  1. web开发:javascript之dom与bom

    一.节点认知 二.文档结构 三.文档节点操作 四.事件target 五.BOM操作 一.节点认知 - dom与dom属性 <!DOCTYPE html> <html> < ...

  2. Hadoop_27_MapReduce_运营商原始日志增强(自定义OutputFormat)

    1.需求: 现有一些原始日志需要做增强解析处理,流程: 1. 从原始日志文件中读取数据(日志文件:https://pan.baidu.com/s/12hbDvP7jMu9yE-oLZXvM_g) 2. ...

  3. [Abp vNext微服务实践] - vue-element-admin管理Identity

    一.简介 abp vNext微服务框架中已经提供通用权限和用户角色管理模块,管理UI使用的是MVC模式,不适用于国内主打的MVVM开发模式.在前端框架选型后笔者决定改造abp vNext微服务框架中原 ...

  4. hbase实践之rowkey设计

    rowkey设计的重要性 rowkeys是HBase表设计中唯一重要的一点. rowkey设计要求 唯一性 存储特性 按照字典顺序排序存储 查询特性 由于其存储特性导致查询特性: 查询单个记录: 查定 ...

  5. .configurable:可配执行 .enumerble:枚举性 .writable:可读写性 .value:数据值

    configurable:控制属性能否被删除,只有当属性的configurable特性的值为true时,该属性才能够被删除. 默认值为false,即不可删除) var person = {}; Obj ...

  6. BZOJ 3210: 花神的浇花集会 (切比雪夫距离)

    GXZlegend 切比雪夫和曼哈顿距离的互相转化看这里 传送门 CODE #include <bits/stdc++.h> using namespace std; #define LL ...

  7. HDU 6058 - Kanade's sum | 2017 Multi-University Training Contest 3

    /* HDU 6058 - Kanade's sum [ 思维,链表 ] | 2017 Multi-University Training Contest 3 题意: 给出排列 a[N],求所有区间的 ...

  8. VUE:Select2

    <template> <div> <ul class="skill"> <li v-for='item of list' v-on:cli ...

  9. Codeforces Round #456 (Div. 2) B题

    B. New Year's Evetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputout ...

  10. Linux之静态库

    命名规则: lib + 库的名字 + .a 制作步骤 生成对应.o文件  .c à .o 将生成的.o文件打包   ar rcs + 静态库的名字(libMytest.a) + 生成的所有的.o 发布 ...