Spring Data JPA是Spring基于Hibernate开发的一个JPA框架。如果用过Hibernate或者MyBatis的话,就会知道对象关系映射(ORM)框架有多么方便。

但是Spring Data JPA框架功能更进一步,为我们做了 一个数据持久层框架几乎能做的任何事情。下面来逐步介绍它的强大功能。

直接上代码:

pom.xml

  1. <!-- hibernate start -->
  2. <!-- spring data jpa -->
  3. <dependency>
  4. <groupId>org.springframework.data</groupId>
  5. <artifactId>spring-data-jpa</artifactId>
  6. <version>2.1.3.RELEASE</version>
  7. </dependency>
  8. <!-- hibernate -->
  9. <dependency>
  10. <groupId>org.hibernate</groupId>
  11. <artifactId>hibernate-core</artifactId>
  12. <version>5.4.0.Final</version>
  13. </dependency>
  14. <!-- hibernate end -->

项目结构:

the_data_jpa 包 里面的 各类 代码

User

  1. package com.oukele.the_data_jpa.entity;
  2.  
  3. import org.springframework.stereotype.Component;
  4.  
  5. import javax.persistence.*;
  6.  
  7. @Entity
  8. @Table(name = "user")
  9. public class User {
  10.  
  11. @Id
  12. @GeneratedValue(strategy = GenerationType.IDENTITY)
  13. @Column(name = "Id")
  14. private int id;
  15.  
  16. @Column(name = "userName")
  17. private String name;
  18. private String password;
  19.  
  20. public int getId() {
  21. return id;
  22. }
  23.  
  24. public void setId(int id) {
  25. this.id = id;
  26. }
  27.  
  28. public String getName() {
  29. return name;
  30. }
  31.  
  32. public void setName(String name) {
  33. this.name = name;
  34. }
  35.  
  36. public String getPassword() {
  37. return password;
  38. }
  39.  
  40. public void setPassword(String password) {
  41. this.password = password;
  42. }
  43. }

UserDao

  1. package com.oukele.the_data_jpa.dao;
  2.  
  3. import com.oukele.the_data_jpa.entity.User;
  4. import org.springframework.data.jpa.repository.JpaRepository;
  5.  
  6. import java.util.List;
  7.  
  8. public interface UserDao extends JpaRepository<User, Integer> {
  9.  
  10. User findByNameAndPassword(String name,String password);
  11.  
  12. }

UserService

  1. package com.oukele.the_data_jpa.service;
  2.  
  3. import com.oukele.the_data_jpa.dao.UserDao;
  4. import com.oukele.the_data_jpa.entity.User;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.jpa.repository.Query;
  7. import org.springframework.stereotype.Service;
  8.  
  9. import java.util.List;
  10.  
  11. @Service
  12. public class UserService {
  13. @Autowired
  14. private UserDao userDao;
  15.  
  16. public User findNameAndPassword(String name,String password){
  17. return userDao.findByNameAndPassword(name, password);
  18. }
  19.  
  20. public List<User> list(){
  21. List<User> list = userDao.findAll();
  22. return list;
  23. }
  24. }

SpringConfig

  1. package com.oukele.the_data_jpa;
  2.  
  3. import com.mchange.v2.c3p0.ComboPooledDataSource;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.ComponentScan;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.PropertySource;
  8. import org.springframework.core.env.Environment;
  9. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  10. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  11. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  12. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
  13. import org.springframework.transaction.PlatformTransactionManager;
  14.  
  15. import javax.sql.DataSource;
  16. import java.beans.PropertyVetoException;
  17. import java.util.Properties;
  18.  
  19. @Configuration//声明当前配置类
  20. @ComponentScan(basePackages = "com.oukele.the_data_jpa")// 扫描当前包 使用 spring 注解
  21. @PropertySource("classpath:jdbc.properties")//加载 资源文件
  22. @EnableJpaRepositories(basePackages = "com.oukele.the_data_jpa.dao")//扫描 使用 jpa 注解的接口
  23. public class SpringConfig {
  24.  
  25. //配置数据源
  26. @Bean
  27. DataSource dataSource(Environment env) throws PropertyVetoException {
  28. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  29. dataSource.setDriverClass(env.getProperty("jdbc.driver"));
  30. dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
  31. dataSource.setUser(env.getProperty("jdbc.user"));
  32. dataSource.setPassword(env.getProperty("jdbc.password"));
  33. return dataSource;
  34. }
  35.  
  36. // @Bean
  37. // public JdbcTemplate jdbcTemplate() {
  38. // JdbcTemplate jdbcTemplate = new JdbcTemplate();
  39. // jdbcTemplate.setDataSource(dataSource1);
  40. // return jdbcTemplate;
  41. // }
  42.  
  43. @Bean
  44. public PlatformTransactionManager transactionManager(DataSource dataSource) {
  45. return new DataSourceTransactionManager(dataSource);
  46. }
  47.  
  48. //SqlSessionFactory
  49. @Bean
  50. LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource){
  51.  
  52. LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
  53. bean.setDataSource(dataSource);
  54. //加载 实体类
  55. bean.setPackagesToScan("com.oukele.the_data_jpa.entity");
  56. //设置 适配器
  57. bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
  58.  
  59. Properties properties = new Properties();
  60. //更新表结构
  61. properties.setProperty("hibernate.hbm2ddl.auto", "update");
  62. //设置方言
  63. properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
  64. bean.setJpaProperties(properties);
  65.  
  66. return bean;
  67. }
  68.  
  69. }

Main ( 测试 类)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.oukele.the_data_jpa;
 
import com.oukele.the_data_jpa.entity.User;
import com.oukele.the_data_jpa.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import java.util.List;
 
public class Main {
 
    public static void main(String[] args) {
 
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService service = context.getBean(UserService.class);
        
        User user = service.findNameAndPassword("oukele","oukele");
        System.out.println(user.getName());
         
        List<User> list = service.list();
        for (User user1 : list) {
            System.out.println(user1.getName()+" - "+user1.getPassword());
        }
    }
}

测试结果:

  1. 1 oukele
  2. 2 oukele - oukele

jdbc.properties文件:

  1. jdbc.driver=org.mariadb.jdbc.Driver
  2. jdbc.url=jdbc:mariadb://localhost:3306/test
  3. jdbc.user=oukele
  4. jdbc.password=oukele

Spring整合Hibernate实现Spring Data JPA (介绍和使用)的更多相关文章

  1. Spring整合Hibernate实现Spring Data JPA (简单使用)

    直接上代码: pom.xml <!-- hibernate start --> <!-- spring data jpa --> <dependency> < ...

  2. 【SSH框架】系列之 Spring 整合 Hibernate 框架

    1.SSH 三大框架整合原理 Spring 与 Struts2 的整合就是将 Action 对象交给 Spring 容器来负责创建. Spring 与 Hibernate 的整合就是将 Session ...

  3. springboot:spring data jpa介绍

    转载自:https://www.cnblogs.com/ityouknow/p/5891443.html 在上篇文章springboot(二):web综合开发中简单介绍了一下spring data j ...

  4. spring boot(五)Spring data jpa介绍

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  5. Spring Data JPA介绍与简单案例

    一.Spring Data JPA介绍 可以理解为JPA规范的再次封装抽象,底层还是使用了Hibernate的JPA技术实现,引用JPQL(Java Persistence Query Languag ...

  6. Spring 整合 Hibernate

    Spring 整合 Hibernate •Spring 支持大多数流行的 ORM 框架, 包括 Hibernate JDO, TopLink, Ibatis 和 JPA. •Spring 对这些 OR ...

  7. Spring整合Hibernate笔记

    1. Spring 指定datasource a) 参考文档,找dbcp.BasicDataSource i. c3p0 ii. dbcp <bean id="dataSource&q ...

  8. Spring(四):Spring整合Hibernate,之后整合Struts2

    背景: 上一篇文章<Spring(三):Spring整合Hibernate>已经介绍使用spring-framework-4.3.8.RELEASE与hibernate-release-5 ...

  9. Spring整合Hibernate的方法

    一.基本支持 Spring 支持大多数流行的 ORM 框架, 包括 Hibernate JDO, TopLink, Ibatis 和 JPA. Spring 对这些 ORM 框架的支持是一致的, 因此 ...

随机推荐

  1. Ubuntu 16.04简单配置备忘录

    1.几个安装包的地址 1.Linux QQ:https://im.qq.com/linuxqq/index.html 2.网易云音乐:http://s1.music.126.net/download/ ...

  2. Unique Word Abbreviation

    An abbreviation of a word follows the form <first letter><number><last letter>. Be ...

  3. JSP总结(jsp/EL表达式/核心标签)

    1.概念 jsp,即java Server Pages,java服务器页面. 2.简单介绍 小示例 <%@ page language="java" contentType= ...

  4. JS之理解继承

    JS之理解继承:https://segmentfault.com/a/1190000010468293 1.call继承,也叫借用构造函数.伪造对象或是经典继承.call继承回把父类的私有属性和方法继 ...

  5. Python中对 文件 的各种骚操作

    Python中对 文件 的各种骚操作 python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getc ...

  6. 剑指offer-二维数组中的查找-数组-python

    题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 ...

  7. Netty入门搭建

    什么是Netty Netty 是一个基于 JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞.基于事件驱动.高性能.高可靠性和高可定制性. 为什么选择netty而不是使用NIO 1.使用 ...

  8. css渐变色兼容性写法

    background: -webkit-linear-gradient(left, #0f0f0f, #0c0c0c, #272727); /* Safari 5.1 - 6.0 */ backgro ...

  9. Apache 安装后启动出现的错误

    错误信息 1: configure: error: APR not found 解决方法:yum install apr* -y 错误信息 2:httpd: apr_sockaddr_info_get ...

  10. Win10 + Ubuntu 安装教程(痛苦踩坑)

    今天搞了一天,痛苦万分,本文的教程基本适用大部分情况,现在记录下需要主义的几点: 一.制作ubuntu usb安装盘的时候,格式要选saw的,千万不要用usb-HDD+的 二.安装完后使用EasyBC ...