亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring+JPA如何集成Hibernate

發布時間:2021-11-23 11:21:34 來源:億速云 閱讀:207 作者:小新 欄目:數據庫

這篇文章主要介紹Spring+JPA如何集成Hibernate,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

1.JPA簡介

 Java Persistence API (JPA),為開發人員提供了一種對象/關系映射(O-R Mapping)工具,用來管理 Java 應用中的關系數據。JPA是EJB3.0的一部分,現在公認為ORM行業標準。JPA本身只是一個規范,而不是產品; 它本身不能進行持續性或其他任何東西。JPA只是一組接口,需要一個實現。JPA允許通過標準的XML格式和注解格式聲明,用于定義Java類如何映射到關系數據庫表的映射規則。。JPA也定義了在對數據庫中的對象處理查詢和事務運行時的EntityManager的API。JPA定義一個對象級查詢語言,JPQL,以允許從所述數據庫中的對象的查詢。JPA常用的解決方案:

    EclipseLink (Eclipse)
    Hibernate (RedHat)
    Open JPA (Apache)
    DataNucleus
    Ebean (SourceForge)
    TopLink Essentials (Glassfish)
    TopLink (Oracle)
    Kodo (Oracle)
JPA 規范也不是一成不變的。從2006年的JPA1.0,到2009年JPA2.0,最后到2013年JPA2.1。版本之間的特性具體參照

https://en.wikibooks.org/wiki/Java_Persistence/What_is_JPA%3F

https://en.wikipedia.org/wiki/Java_Persistence_API

2.Spring Hibernate JPA整合

準備

表
CREATE TABLE `Employee` (
  `id` int(11) unsigned NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `role` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.1項目結構

Spring+JPA如何集成Hibernate

2.2 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework</groupId>
    <artifactId>gs-relational-data-access</artifactId>
    <version>0.1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h3database</groupId>
            <artifactId>h3</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>1.1.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

使用了platform-bom,方便了包的依賴管理。

依賴樹結構

Spring+JPA如何集成Hibernate

2.3 persistence.xml

<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="JPAExamples">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    </persistence-unit>
</persistence>

2.4 spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!--數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/exampledb"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="persistenceXmlLocation" value="META-INF/persistence.xml"/>
        <property name="persistenceUnitName" value="JPAExamples"/>
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
        <property name="jpaDialect" ref="jpaDialect"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="generateDdl" value="false" />
        <property name="database" value="MYSQL"/>
    </bean>

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

    <bean id="entityManager" factory-bean="entityManagerFactory"  factory-method="createEntityManager"></bean>
    <!-- Jpa 事務管理器  -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
          p:entityManagerFactory-ref="entityManagerFactory" />
    <!-- 開啟注解事務 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

    <!-- 啟動對@AspectJ(面向切面)注解的支持 -->
    <aop:aspectj-autoproxy />

    <context:component-scan base-package="com.journaldev.spring.jpa"></context:component-scan>
</beans>

有的對象,不是必須的。為了保持完整性,做了保留。

可以配置entityManagerFactory的packagesToScan屬性,沒有配置也是可以的。

2.5 entity

package com.journaldev.spring.jpa.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
    @Id
    private int id;
    private String name;
    private String role;

    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 getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "{ID=" + id + ",Name=" + name + ",Role=" + role + "}";
    }
}

2.6 接口

public interface EmployeeDAO {
    //Create
    public void save(Employee employee);
    //Read
    public Employee getById(int id);
    //Update
    public void update(Employee employee);
    //Delete
    public void deleteById(int id);
    //Get All
    public List<Employee> getAll();
}

實現類

package com.journaldev.spring.jpa.dao;

import com.journaldev.spring.jpa.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.transaction.Transactional;

import java.util.List;

/**
 * Created by zhaoguoyu on 2016/6/22.
 */
@Transactional
@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
    @PersistenceContext
    EntityManager em;


    @Override
    public void save(Employee employee) {
        em.persist(employee);
    }

    @Override
    public Employee getById(int id) {
        return em.find(Employee.class, id);
    }

    public void update(Employee employee) {  
        em.merge(employee);
    }

    @Override
    public void deleteById(int id) {
        em.remove(this.getById(id));
    }

    @Override
    public List<Employee> getAll() {
        CriteriaBuilder builder =em.getCriteriaBuilder();
        final CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
        return this.em.createQuery(query).getResultList();
    }
}

2.7測試

測試類

import com.journaldev.spring.jpa.dao.EmployeeDAO;
import com.journaldev.spring.jpa.model.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;
import javax.annotation.Resource;

import java.util.Random;

/**
 * Created by zhaoguoyu on 2016/6/22.
 */
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class SpringJPATest extends AbstractTransactionalJUnit4SpringContextTests {

    @Resource
    private EmployeeDAO employeeDAO;

    @Test
    public void testSave(){
        Employee emp = new Employee();
        int rand = new Random().nextInt(1000);
        emp.setId(rand);
        emp.setName("Pankaj");
        emp.setRole("Java Developer");
        employeeDAO.save(emp);
    }
    @Test
    public void testUpdate(){
        Employee emp = new Employee();
        int rand = new Random().nextInt(1000);
        emp.setId(rand);
        emp.setName("Pankaj");
        emp.setRole("Java Developer");
        employeeDAO.save(emp);
        emp.setName(emp.getName()+"_update");
        employeeDAO.update(emp);
    }
}

OR

import com.journaldev.spring.jpa.dao.EmployeeDAO;
import com.journaldev.spring.jpa.model.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Random;

/**
 * Created by zhaoguoyu on 2016/6/22.
 */
public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        final EmployeeDAO employeeDAO = ctx.getBean(EmployeeDAO.class);
        Employee emp = new Employee();
        int rand = new Random().nextInt(1000);
        emp.setId(rand);
        emp.setName("Pankaj");
        emp.setRole("Java Developer");
        employeeDAO.save(emp);

        Employee employee = employeeDAO.getById(rand);
        employee.setName(employee.getName() +"_update");
        employeeDAO.update(employee);
    }
}

有一點需要說明。默認使用的日志是logback.號稱比log4j更優秀的一款。

默認的日志配置logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>
    <logger name="org.hibernate" level="debug" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <root level="error">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

以上是“Spring+JPA如何集成Hibernate”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

江川县| 马龙县| 盐山县| 木兰县| 方正县| 宁明县| 阜平县| 五莲县| 丰都县| 常德市| 建平县| 远安县| 湛江市| 寻甸| 德化县| 新和县| 双辽市| 深圳市| 望奎县| 明水县| 庆阳市| 肇州县| 平安县| 南开区| 漳浦县| 南溪县| 陆川县| 陆良县| 临夏市| 镇巴县| 邮箱| 额济纳旗| 乐安县| 盐山县| 东辽县| 禹城市| 广宗县| 石屏县| 洱源县| 神池县| 浮山县|