目录结构

首先在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. 解决Python中出现的问题: “You are using pip version 9.0.1, however version 19.2.3 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command.”

    1. 一开始我在使用Pycharm时,导入numpy库,发现导入错误: Non-zero exit code (1) 2. 于是我通过更新的方法来解决,哪知道在更新的时候也出现了错误,错误如下图: 这 ...

  2. Ubuntu安装截图软件shutter

    参考链接: Ubuntu 安装和配置shutter截图软件 解决shutter不能编辑的问题:https://itsfoss.com/shutter-edit-button-disabled/ 安装前 ...

  3. 最近在研究IO

    import java.io.File; import java.io.IOException; public class Demo11_1 { public static void main(Str ...

  4. 获取DataFrame列名的3种方法

    df= pd.DataFrame({'a': range(10, 20), 'b': range(20, 30)}) df 1.链表推倒式 [column for column in df][a,b] ...

  5. springAOP分析

    参考https://www.cnblogs.com/liuyk-code/p/9886033.html 在springboot中自动引入了配置文件AopAutoConfiguration @Confi ...

  6. Non-standard serial port baud rate setting

    ////combuad_recv.cpp #include <stdio.h> /*标准输入输出定义*/ #include <stdlib.h> /*标准函数库定义*/ #in ...

  7. 【原创】洛谷 LUOGU P3373 【模板】线段树2

    P3373 [模板]线段树 2 题目描述 如题,已知一个数列,你需要进行下面两种操作: 1.将某区间每一个数加上x 2.将某区间每一个数乘上x 3.求出某区间每一个数的和 输入输出格式 输入格式: 第 ...

  8. node中从express到koa再到koa2的发展历程

    koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本. 历史 1. Express Express是第一代最流行的web框架,它对Node.js的http进行了封 ...

  9. Django Admin中增加导出CSV功能

    参考: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html 在使用Django Admin时, ...

  10. vue子组件通知父组件使用方法

    vue子组件通知父组件使用方法 <template> <mt-field placeholder="验证码" v-model="getverifycod ...