欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JPA学习

程序员文章站 2022-03-02 15:23:25
...

JPA学习

什么是orm

object-relational-mapper:对象关系映射,就是建立对象与数据库之间的映射关系,就是orm

对象关系映射可以大大的减少重复性的代码,提高开发效率;

常见的orm框架:hibernate

目的:达到操作类一样操作数据库;

什么是JPA

是sum公司提供的一套持久层操作规范;

底层可以使用hibernate进行数据库操作;

JPA入门案例

在META-INF下编写配置文件persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <!-- 配置持久化单元
    name: 持久化单元名称
    transaction-type: 事务类型
            RESOURCE_LOCAL: 本地事务
            JTA: 跨数据库事务【分布式事务】
    -->
    <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
        <!-- 配置提供商 -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <!-- 其他属性 -->
        <properties>
            <!-- 链接数据库的四要素 -->
            <!-- mysql-->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"></property>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/springjpa?useUnicode=true&amp;characterEncoding=UTF-8"></property>
            <property name="javax.persistence.jdbc.user" value="root"></property>
            <property name="javax.persistence.jdbc.password" value="root"></property>

            <!--Oracle
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"></property>
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@dbnode01:1521:xe"></property>
            <property name="javax.persistence.jdbc.user" value="feifei"></property>
            <property name="javax.persistence.jdbc.password" value="passw0rd"></property>-->

            <!-- 其他属性 : 显示sql语句-->
            <property name="hibernate.show_sql" value="true"></property>
            <!-- 其他属性:让hibernate维护表结构
            create:  先删除表,再创建表
            update:  有表,就维护表;没有表就更新表
            none:    什么也不干
            -->
            <property name="hibernate.hbm2ddl.auto" value="none"></property>
        </properties>
    </persistence-unit>
</persistence>

编写与数据库对应的实体类

package com.itheima.domain;

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

/**
 * 客户实体类
 *
 *      导的所有类: javax.persistence
 */
//把一个类标记成实体类
@Entity
//映射表名称
@Table(name = "cst_customer")
public class Customer implements Serializable {

    //把一个属性标记成主键属性
    @Id
    //配置主键生成的策略
    @GeneratedValue(strategy = GenerationType.IDENTITY) //适用于: Mysql,主键自动增长
    //@GeneratedValue(strategy = GenerationType.SEQUENCE) //适用于: Oracle,使用序列机制
    //指定序列
    /*@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "customer_id")
    @SequenceGenerator(
            //名称,给别人引用
            name="customer_id",
            //数据库中序列的名称
            sequenceName = "SEQ_CUSTOMER_ID",
            //指定序列的初始值
            initialValue = 1,
            //增量:步长
            allocationSize = 1
    )*/
    //@GeneratedValue(strategy = GenerationType.TABLE) //使用表来维护id
    //@GeneratedValue(strategy = GenerationType.AUTO) //根据环境选择最优策略
    //映射字段
    @Column(name="cust_id")
    private Long custId;

    @Column(name="cust_name")
    private String custName;

    @Column(name="cust_level")
    private String custLevel;

    @Column(name="cust_source")
    private String custSource;

    @Column(name="cust_industry")
    private String custIndustry;

    @Column(name="cust_address")
    private String custAddress;

    @Column(name="cust_phone")
    private String custPhone;

    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 getCustLevel() {
        return custLevel;
    }

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

    public String getCustSource() {
        return custSource;
    }

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

    public String getCustIndustry() {
        return custIndustry;
    }

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

    public String getCustAddress() {
        return custAddress;
    }

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

    public String getCustPhone() {
        return custPhone;
    }

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

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

测试

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

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

public class DemoTest {
   @Test
   public void test01(){
       EntityManagerFactory myJpa = Persistence.createEntityManagerFactory("myJpa");
       EntityManager entityManager = myJpa.createEntityManager();
       EntityTransaction transaction = entityManager.getTransaction();
       transaction.begin();

       Customer customer = new Customer();
       customer.setCustName("nihap");

       entityManager.persist(customer);
       transaction.commit();

       entityManager.close();
       myJpa.close();
   }
}

主键生成策略有4种

@GenetaredValue(strategy=GenerationType.IDENTITY)这个比较常用
-------------------------------------------------------
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="payablemoney_seq")
@SequenceGenerator(name="payablemoney_seq", sequenceName="seq_payment")
-------------------------------------------------------
@GeneratedValue(strategy = GenerationType.AUTO)
-------------------------------------------------------
@GeneratedValue(strategy = GenerationType.TABLE, generator="payablemoney_gen")
@TableGenerator(name = "pk_gen",
table="tb_generator",
pkColumnName="gen_name",
valueColumnName="gen_value",
pkColumnValue="PAYABLEMOENY_PK",
allocationSize=1
)

Manager方法

这是简单查询:
    getTransaction : 获取事务对象
    persist : 保存操作
    merge : 更新操作
    remove : 删除操作
    find/getReference : 根据 id 查询
        其中就是find和getReference的区别
        find:不管要不要使用都会生成sql语句
        getReference:是预编译对象,意思就是要用的时候才会生成sql语句,不用的时候是不会生成的;
复杂查询:
	编写jpql语句:
        全部查询:
               String jpql = "from Customer";
               Query query = manager.createQuery(jpql);
               List resultList = query.getResultList();
		分页查询:
			   Query query = manager.createQuery(jpql);
               query.setFirstResult(0);
               query.setMaxResults(2);
               List resultList = query.getResultList();
		条件查询:
			   String jpql = "from Customer where custName like ?";
               Query query = manager.createQuery(jpql);
               query.setParameter(1,"n%");
               Object singleResult = query.getSingleResult();会根据你的得到的数据判断,如果				是一条就不会错,如果是多条就会报错;
               System.out.println(singleResult);
		排序查询:
				String jpql = "from Customer order by custId desc";
		统计查询:
			   String jpql = "select count(custId) from Customer"

上一篇: JPA(学习)

下一篇: 异常