zoukankan      html  css  js  c++  java
  • Spring整合Hibernate实现Spring Data JPA (介绍和使用)

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

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

    直接上代码:

    pom.xml

    复制代码
            <!-- hibernate start -->
            <!-- spring data jpa  -->
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-jpa</artifactId>
                <version>2.1.3.RELEASE</version>
            </dependency>
            <!-- hibernate  -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.4.0.Final</version>
            </dependency>
            <!-- hibernate end  -->
    复制代码

    项目结构:

    the_data_jpa 包 里面的 各类 代码

    User

    复制代码
    package com.oukele.the_data_jpa.entity;
    
    
    import org.springframework.stereotype.Component;
    
    import javax.persistence.*;
    
    @Entity
    @Table(name = "user")
    public class User {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "Id")
        private int id;
    
        @Column(name = "userName")
        private String name;
        private String password;
    
        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 String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    复制代码

    UserDao

    复制代码
    package com.oukele.the_data_jpa.dao;
    
    import com.oukele.the_data_jpa.entity.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import java.util.List;
    
    public interface UserDao extends JpaRepository<User, Integer> {
    
        User findByNameAndPassword(String name,String password);
    
    
    }
    复制代码

    UserService

    复制代码
    package com.oukele.the_data_jpa.service;
    
    import com.oukele.the_data_jpa.dao.UserDao;
    import com.oukele.the_data_jpa.entity.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserService {
        @Autowired
        private UserDao userDao;
    
        public User findNameAndPassword(String name,String password){
            return userDao.findByNameAndPassword(name, password);
        }
        
        public List<User> list(){
            List<User> list = userDao.findAll();
            return list;
        }
    }
    复制代码

    SpringConfig

    复制代码
    package com.oukele.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 javax.sql.DataSource;
    import java.beans.PropertyVetoException;
    import java.util.Properties;
    
    @Configuration//声明当前配置类
    @ComponentScan(basePackages = "com.oukele.the_data_jpa")// 扫描当前包 使用 spring 注解
    @PropertySource("classpath:jdbc.properties")//加载 资源文件
    @EnableJpaRepositories(basePackages = "com.oukele.the_data_jpa.dao")//扫描 使用 jpa 注解的接口
    public class SpringConfig {
        
    
        //配置数据源
        @Bean
        DataSource dataSource(Environment env) throws PropertyVetoException {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(env.getProperty("jdbc.driver"));
            dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
            dataSource.setUser(env.getProperty("jdbc.user"));
            dataSource.setPassword(env.getProperty("jdbc.password"));
            return  dataSource;
        }
    
    //    @Bean
    //    public JdbcTemplate jdbcTemplate() {
    //        JdbcTemplate jdbcTemplate = new JdbcTemplate();
    //        jdbcTemplate.setDataSource(dataSource1);
    //        return jdbcTemplate;
    //    }
    
        @Bean
        public PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        //SqlSessionFactory
        @Bean
        LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource){
    
            LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
            bean.setDataSource(dataSource);
            //加载 实体类
            bean.setPackagesToScan("com.oukele.the_data_jpa.entity");
            //设置 适配器
            bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    
            Properties properties = new Properties();
            //更新表结构
            properties.setProperty("hibernate.hbm2ddl.auto", "update");
            //设置方言
            properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            bean.setJpaProperties(properties);
    
            return bean;
        }
    
    }
    复制代码

    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 oukele
    2 oukele - oukele

    jdbc.properties文件:

    jdbc.driver=org.mariadb.jdbc.Driver
    jdbc.url=jdbc:mariadb://localhost:3306/test
    jdbc.user=oukele
    jdbc.password=oukele
  • 相关阅读:
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    12.20++对王建民老师的评价+个人期末总结
    12.19
    12.18
    12.17
    12.16
  • 原文地址:https://www.cnblogs.com/nongzihong/p/10520991.html
Copyright © 2011-2022 走看看