Java经典框架之SpringDataJPA

发布时间:2024年01月03日

SpringDataJPA

Java 是第一大编程语言和开发平台。它有助于企业降低成本、缩短开发周期、推动创新以及改善应用服务。如今全球有数百万开发人员运行着超过 51 亿个 Java 虚拟机,Java 仍是企业和开发人员的首选开发平台。
??

课程内容的介绍

1. Spring整合Hibernate
2. Spring整合HibernateJPA
3. SpringDataJPA介绍
4. SpringBoot整合SpringDataJPA
??
Spring Data JPA:Spring Data JPA 是 Spring Data 项目下的一个模块。提供了一套基于 JPA标准操作数据库的简化方案。底层默认的是依赖 Hibernate JPA 来实现的。
Spring Data JPA 的技术特点:我们只需要定义接口并集成 Spring Data JPA 中所提供的接口就可以了。不需要编写接口实现类。
??

一、Spring整合Hibernate

1. 创建项目
创建一个普通的Maven项目即可。

? ?
2.添加相关的依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.7.Final</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
    </dependencies>
? ?
3. 添加相关的配置文件
添加数据库的配置文件和Spring的配置文件。
<?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:context="http://www.springframework.org/schema/context"
       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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!-- 引入db.properties文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 创建druid 的数据源 -->
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password"  value="${jdbc.password}" />
    </bean>

    <!-- 配置Hibernate的SessionFactory对象 -->
    <bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="sessionFactory">
        <!-- 关联数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置Hibernate的属性信息 -->
        <property name="hibernateProperties">
            <props>
                <prop key="show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <!-- 扫描路径 -->
        <property name="packagesToScan">
            <list>
                <value>com.bobo.pojo</value>
            </list>
        </property>
    </bean>

    <!-- 配置HibernateTemplate对象 -->
    <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!--  配置事务管理-->
    <bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 配置开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- 配置扫描路径 -->
    <context:component-scan base-package="com.bobo" />
</beans>
? ? ?
4. 创建POJO
和表结构中的t_user表对应即可。
package com.bobo.pojo;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="t_user")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer userId;

    @Column(name="user_name")
    private String userName;

    @Column(name="real_name")
    private String realName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

}
? ?
5. 创建持久层
定义持久层接口,定义要实现的相关的方法。
package com.bobo.dao;

import com.bobo.pojo.Users;

import java.util.List;

public interface IUserDao {

    void insertUsers(Users users);

    void updateUsers(Users users);

    void deleteUsers(Users users);

    Users selectUsersById(Integer userId);

    List<Users> selectUsersByName(String userName);

    List<Users> selectUsersByNameUseSQL(String userName);

    List<Users> selectUsersByNameUseCriteria(String userName);
}
package com.bobo.dao.impl;

import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class UserDaoImpl implements IUserDao {

    @Autowired
    private HibernateTemplate template;

    @Override
    public void insertUsers(Users users) {
        this.template.save(users);
    }

    @Override
    public void updateUsers(Users users) {
        this.template.update(users);
    }

    @Override
    public void deleteUsers(Users users) {
        this.template.delete(users);
    }

    @Override
    public Users selectUsersById(Integer userId) {
        return this.template.get(Users.class,userId);
    }

    @Override
    public List<Users> selectUsersByName(String userName) {
        // 我们要执行特殊的查询操作 我们需要获取对应的Session对象
        Session session = this.template.getSessionFactory().getCurrentSession();
        // 通过Session对象创建Query对象 HQL 语句
        Query query = session.createQuery(" from Users where userName = :abc");
        Query queryTemp = query.setString("abc", userName);
        return queryTemp.list();
    }

    @Override
    public List<Users> selectUsersByNameUseSQL(String userName) {
        // 我们要执行特殊的查询操作 我们需要获取对应的Session对象
        Session session = this.template.getSessionFactory().getCurrentSession();
        // 通过Session对象创建Query对象 SQL 语句
        Query query = session.createSQLQuery("select * from t_user where user_name = ?")
                .addEntity(Users.class)
                .setString(0, userName);
        return query.list();
    }

    @Override
    public List<Users> selectUsersByNameUseCriteria(String userName) {
        Session session = this.template.getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(Users.class);
        criteria.add(Restrictions.eq("userName",userName));
        return criteria.list();
    }
}
? ? ?
6. 单元测试
package com.bobo.test;

import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {

    @Autowired
    private IUserDao dao;

    @Test
    @Transactional
    @Rollback(false)
    public void testInsertUser(){
        Users user = new Users();
        user.setUserName("Tom");
        user.setRealName("张三丰");
        dao.insertUsers(user);
    }


    @Test
    @Transactional
    public void testQuery1(){
        Users users = this.dao.selectUsersById(22);
        System.out.println(users);
    }

    @Test
    @Transactional
    public void testQuery2(){
        List<Users> list = this.dao.selectUsersByNameUseSQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }


}
??

??

??

二、Spring整合HibernateJPA

现如今的ORM框架还是比较多的比如Hibernate,TopLink以及OpenJPA等等,为了简化ORM框架的使用,JPA随之产生。
JPA是Java Persistence API的简称,中文名Java持久层API,由 Sun 公司提供了一对对于持久层操作的标准(接口+文档),说白了就是在各种ORM框架之上封装了一套API实现统一操作。同时又依赖各种ORM框架去实现。hibernate3.2版本后提供了对JPA的实现。
??
1. 创建项目
创建一个普通的Maven项目即可。

? ??
2. 添加相关的依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.7.Final</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
    </dependencies>
? ?
3. 添加相关的配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
? ? ?
Spring的配置文件
<?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:context="http://www.springframework.org/schema/context"
       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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!-- 引入db.properties文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 创建druid 的数据源 -->
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password"  value="${jdbc.password}" />
    </bean>

    <!-- 配置Hibernate的SessionFactory对象 -->
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="sessionFactory">
        <!-- 关联数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置Hibernate的属性信息 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="MYSQL"/>
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
            </bean>
            <!--<props>
                <prop key="show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>-->
        </property>
        <!-- 扫描路径 -->
        <property name="packagesToScan">
            <list>
                <value>com.bobo.pojo</value>
            </list>
        </property>
    </bean>


    <!--  配置事务管理-->
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="sessionFactory" />
    </bean>

    <!-- 配置开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- 配置扫描路径 -->
    <context:component-scan base-package="com.bobo" />
</beans>
??
文章来源:https://blog.csdn.net/m0_52514893/article/details/135354074
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。