SpringData-JPA入门

本文详细介绍了使用Java Persistence API (JPA)与Hibernate框架进行数据库操作的全过程,包括配置环境、创建实体类、编写工具类及进行增删改查等核心操作。通过具体示例,展示了如何在实际项目中应用JPA和Hibernate。
摘要由CSDN通过智能技术生成

1.导入JAR包

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.hibernate.version>5.0.7.Final</project.hibernate.version>
    </properties>

    <dependencies>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- hibernate对jpa的支持包 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${project.hibernate.version}</version>
        </dependency>

        <!-- c3p0 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${project.hibernate.version}</version>
        </dependency>

        <!-- log日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- Mysql and MariaDB -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>

2.配置JPA核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <!--需要配置persistence-unit节点
        持久化单元:
            name:持久化单元名称
            transaction-type:事务管理的方式
                    JTA:分布式事务管理
                    RESOURCE_LOCAL:本地事务管理
    -->
    <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
        <!--jpa的实现方式 -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <!--可选配置:配置jpa实现方的配置信息-->
        <properties>
            <!-- 数据库信息
                用户名,javax.persistence.jdbc.user
                密码,  javax.persistence.jdbc.password
                驱动,  javax.persistence.jdbc.driver
                数据库地址   javax.persistence.jdbc.url
            -->
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="root"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>

            <!--配置jpa实现方(hibernate)的配置信息
                显示sql           :   false|true
                自动创建数据库表    :  hibernate.hbm2ddl.auto
                        create      : 程序运行时创建数据库表(如果有表,先删除表再创建)
                        update      :程序运行时创建表(如果有表,不会创建表)
                        none        :不会创建表

            -->
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>

3.创建实体类 并加注解

package com.itheima.domain;

import javax.persistence.*;

/**
 * 客户的实体类
 *      配置映射关系
 *
 *
 *   1.实体类和表的映射关系
 *      @Entity:声明实体类
 *      @Table : 配置实体类和表的映射关系
 *          name : 配置数据库表的名称
 *   2.实体类中属性和表中字段的映射关系
 *
 *
 */
@Entity
@Table(name = "cst_customer")
public class Customer {

    /**
     * @Id:声明主键的配置
     * @GeneratedValue:配置主键的生成策略
     *      strategy
     *          GenerationType.IDENTITY :自增,mysql
     *                 * 底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)
     *          GenerationType.SEQUENCE : 序列,oracle
     *                  * 底层数据库必须支持序列
     *          GenerationType.TABLE : jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
     *          GenerationType.AUTO : 由程序自动的帮助我们选择主键生成策略
     * @Column:配置属性和字段的映射关系
     *      name:数据库表中字段的名称
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId; //客户的主键

    @Column(name = "cust_name")
    private String custName;//客户名称

    @Column(name="cust_source")
    private String custSource;//客户来源

    @Column(name="cust_level")
    private String custLevel;//客户级别

    @Column(name="cust_industry")
    private String custIndustry;//客户所属行业

    @Column(name="cust_phone")
    private String custPhone;//客户的联系方式

    @Column(name="cust_address")
    private String custAddress;//客户地址

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custAddress='" + custAddress + '\'' +
                '}';
    }
}

4.编写工具类 ,方便后面测试

package com.itheima.utils;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * 工具类得到
 */
public class JpaUtil {

    private static  EntityManagerFactory factory;
    static {
        factory = Persistence.createEntityManagerFactory("myJpa");
    }

    /**
     * 获取实体管理器
     * @return
     */
    public static  EntityManager getEntityManager(){
       return  factory.createEntityManager();
    }
}

5.测试(增删改)

package com.itheima.test;

import com.itheima.domain.Customer;
import com.itheima.utils.JpaUtil;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


public class JpaTest {
    /**
     * 测试jpa的保存
     *      案例:保存一个客户到数据库中
     *  Jpa的操作步骤
     *     1.加载配置文件创建工厂(实体管理器工厂)对象
     *     2.通过实体管理器工厂获取实体管理器
     *     3.获取事务对象,开启事务
     *     4.完成增删改查操作
     *     5.提交事务(回滚事务)
     *     6.释放资源
     */

     //增加
    @Test
    public void JpaSava(){
        //1.加载配置文件创建工厂(实体管理器工厂)对象
       // EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa");
        //2.通过实体管理器工厂获取实体管理器
        //EntityManager em = factory.createEntityManager();
        EntityManager em = JpaUtil.getEntityManager();
        //3.获取事务对象,开启事务
        EntityTransaction transaction = em.getTransaction();
        transaction.begin();
        // 4.完成增删改查操作
        Customer ct=new Customer();

        ct.setCustName("哈登");
        ct.setCustAddress("美国休斯敦-火箭队");
        //保存操作
        em.persist(ct);
        //5.提交事务(回滚事务)
        transaction.commit();
        // 6.释放资源  从后到前
        em.close();

    }

    /**
     * 根据id查找
     */
    @Test
   public  void Jpafind(){
       //得到实体管理器
       EntityManager entityManager = JpaUtil.getEntityManager();
       //获取事务对象  开启事务
       EntityTransaction transaction = entityManager.getTransaction();
       transaction.begin();
       //查找
       Customer customer = entityManager.find(Customer.class, 2L);
       System.out.println(customer);
       entityManager.close();
   }

    /**
     * 修改 先查再修改
     */
    @Test
    public  void JpaUpdate(){
        //得到实体管理器
        EntityManager entityManager = JpaUtil.getEntityManager();
        //获取事务对象  开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //查找
        Customer customer = entityManager.find(Customer.class, 2L);
        customer.setCustName("保罗");
        entityManager.merge(customer);
        System.out.println(customer);
        entityManager.close();
    }

    /**
     * 删除
     */
    @Test
    public void JpaDel(){
        //得到实体管理器
        EntityManager entityManager = JpaUtil.getEntityManager();
        //获取事务对象  开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //查找
        Customer customer = entityManager.find(Customer.class, 2L);

        entityManager.remove(customer);
        transaction.commit();
        entityManager.close();

    }
}

5.2  查询

package com.itheima.test;

import com.itheima.utils.JpaUtil;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;

public class JPQLTest {
    /**
     * 查询全部
     */
    @Test
     public void findAllTest(){
         EntityManager entityManager = JpaUtil.getEntityManager();
      //获取事务对象 ,开启事务
         EntityTransaction transaction = entityManager.getTransaction();
         transaction.begin();
         String pql="from Customer";
         Query query = entityManager.createQuery(pql);
         List resultList = query.getResultList();
         for (Object o : resultList) {
             System.out.println(o);
         }
          transaction.commit();

          entityManager.close();
     }

     //分页查询
    @Test
    public void findPage(){
        EntityManager entityManager = JpaUtil.getEntityManager();
        //获取事务对象 ,开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        String pql="from Customer ";
        Query query = entityManager.createQuery(pql);
        query.setFirstResult(1);
        query.setMaxResults(2);
        List resultList = query.getResultList();
        for (Object o : resultList) {
            System.out.println(o);
        }
        transaction.commit();

        entityManager.close();
    }

    //条件查询
    @Test
    public void  findByTj(){
        EntityManager entityManager = JpaUtil.getEntityManager();
        //获取事务对象 ,开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        String pql="from Customer where custName like  ? ";
        Query query = entityManager.createQuery(pql);
        query.setParameter(1,"%哈登%");
        List resultList = query.getResultList();
        for (Object o : resultList) {
            System.out.println(o);

        }
     transaction.commit();
        entityManager.close();
    }

    //统计查询
    @Test
    public void CountTest(){
        EntityManager entityManager = JpaUtil.getEntityManager();
        //获取事务对象 ,开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        String pql="select count (custName) from Customer where custName like ? ";
        Query query = entityManager.createQuery(pql);
        query.setParameter(1,"%哈登%");
        List resultList = query.getResultList();
        for (Object o : resultList) {
            System.out.println(o);

        }
        transaction.commit();
        entityManager.close();

    }

    //排序查询
   // SELECT * FROM cst_customer WHERE cust_name LIKE "%哈登%" ORDER BY cust_id DESC;
    @Test
    public void ordesTest(){
        EntityManager entityManager = JpaUtil.getEntityManager();
        //获取事务对象 ,开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        String pql=" from Customer where custName like ? order by custId DESC";
        Query query = entityManager.createQuery(pql);
        query.setParameter(1,"%哈登%");
        List resultList = query.getResultList();
        for (Object o : resultList) {
            System.out.println(o);
        }
         transaction.commit();
        entityManager.close();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值