什麼是APJ與使用Spring Data JPA 基於Hibernate

目錄結構java

 

首先在Maven項目中添加依賴包spring

<!-- 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框架。sql

在項目中使用方式爲:在實體類中,使用 @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框架

咱們只須要使用ide

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;
    }

}

BookServicethis

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);
    }

}

Mainurl

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

 結果spa

相關文章
相關標籤/搜索