一、JPA相关概念
1、JPA概述
全称是:Java Persistence API。是SUN公司推出的一套基于ORM的规范。hibernate框架中提供了JPA的实现。
JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
2、学习JPA要明白
JPA是一套ORM规范,hibernate实现了JPA规范
hibernate中有自己的独立ORM操作数据库方式,也有JPA规范实现的操作数据库方式。
我们在hibernate的学习中,主要以JPA配置为主,而hibernate的配置不再是重点。
在数据库增删改查操作中,我们hibernate和JPA的操作都要会。
二、使用JPA进行hibernate的CRUD
1、改造hibernate的映射文件
package cn.itcast.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 客户的实体类(数据模型)
* @author zhy
* 基于注解映射配置:都是JPA规范的。
* 所以我们导包需要导入的是javax.persistence包下的
*/
@Entity
@Table(name="cst_customer") //映射数据库表
public class Customer implements Serializable {
@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_industry")
private String custIndustry;
@Column(name="cust_level")
private String custLevel;
@Column(name="cust_address")
private String custAddress;
@Column(name="cust_phone")
private String custPhone;
public Customer(){
}
public Customer(Long custId, String custName) {
this.custId = custId;
this.custName = custName;
}
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 getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
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 + ", custSource=" + custSource
+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
+ ", custPhone=" + custPhone + "]";
}
}
2、指定主配置文件中的映射文件位置
<!-- 3、指定映射文件的位置 -->
<mapping class="cn.itcast.domain.Customer"/>