什么是APJ与使用Spring Data JPA 基于Hibernate

目录结构

 

首先在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());
    }
}

 结果

 

posted on 2018-12-21 16:15  东子z  阅读(625)  评论(0编辑  收藏  举报

导航