JavaEE--SSH--hibernate-JPA的介绍和使用

JPA是SUN公司对ORM推出的一套规范. hibernate框架中提供了对JPA的实现.

JPA的优点:

1.简单方便.在JPA框架下创建实体没有任何约束.只需用JPA进行注释.

2.查询能力,JPA查询是面向对象的,类似hibernate的HQL,JPA的查询语言教JPQL,是针对实体的一种查询语言,而且支持批量更新和修改,JOIN,GROUP BY,HAVING,子查询等SQL才有的高级查询特性.

3.能够支持面向对象的高级特性,如类之间的继承,多态及类之间的复杂关系.

JPA的使用:

1.环境搭建:引入jar包.JavaEE--SSH--hibernate-JPA的介绍和使用

2.编写JPA的配置文件persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
          http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
<!-- 告诉JPA哪个框架实现了JPA规范 -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- 告诉JPA哪些包下的类上有配置信息 -->
<class>cn.asiainfo.hibernate.domain.Customer</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql:///day04_hibernate" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="123456" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<!-- c3p0配置-->
<property name="hibernate.connection.provider_class"
value="org.hibernate.connection.C3P0ConnectionProvider" />

<!-- 设置当前的数据库的隔离界别 -->
<property name="hibernate.connection.isolation" value="4" />
<!-- 把session绑定到当前线程上 
<property name="hibernate.current_session_context_class"
value="thread" />
-->
</properties>
</persistence-unit>

</persistence>

3.创建数据库表 tb_customer和

CREATE TABLE `tb_customer` (
  `custId` bigint(20) NOT NULL AUTO_INCREMENT,
  `custAddress` varchar(255) DEFAULT NULL,
  `custIndustry` varchar(255) DEFAULT NULL,
  `custLevel` varchar(255) DEFAULT NULL,
  `custName` varchar(255) DEFAULT NULL,
  `custPhone` varchar(255) DEFAULT NULL,
  `custSource` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`custId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8


CREATE TABLE `tb_user` (
  `uid` bigint(20) NOT NULL AUTO_INCREMENT,
  `password` varchar(255) DEFAULT NULL,
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

4.编写实体类Customer和User.

package cn.asiainfo.hibernate.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

//@Entity  //告诉hibernate当前类是一个持久化类
//@Table(name="tb_customer")  //告诉hibernate当前类创建的对象上的数据向表tb_customer中来进行插入
public class Customer {


@Id //告诉hibernate当前属性是oid属性
@GeneratedValue(strategy=GenerationType.IDENTITY) //告诉hibernate当前属性是oid属性,主键生成策略采用的是IDENTITY
@Column(name="cust_id") //告诉hibernate当前属性对应的仓库中列的名称 
private Long custId;  //客户ID
@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 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 + "]";
}

}

package cn.asiainfo.hibernate.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

@Entity
@Table(name="tb_user")
public class User {
@Id
@Column
@GeneratedValue(strategy=GenerationType.TABLE,generator="myGen")
@TableGenerator(
table="tb_myGen",
  name="myGen",
  pkColumnName="aa",
  valueColumnName="bb",
  pkColumnValue="zzzz",
  initialValue=1,
  allocationSize=1
    )
private Long uid;
@Column
private String username;
@Column
private String password;
public Long getUid() {
return uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

5.编写JPA工具类

package cn.asiainfo.hibernate.utils;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/*
 * jpa工具类
 * 目的:创建实体管理类对象
 */
public class JPAUtil {
private static EntityManagerFactory fac=null;
static{
fac=Persistence.createEntityManagerFactory("myUnit");
}

public static EntityManager getEntityManager(){
return  fac.createEntityManager();
}

}


6.编写测试类:

package cn.asiainfo.hibernate.test;
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.hibernate.Transaction;
import org.junit.Test;
import cn.asiainfo.hibernate.domain.Customer;
/*
 * jpa的入门案例
 * 1_读取配置文件Configuration
 * 2_获取SessionFactory
 * 3_获取Session
 * 4_开启事务
 * 5_执行操作
 * 6_提交事务
 * 7_释放资源
 *
 *   通过session管理各个对象,EntityManger 实体管理器相当于Session,管理各个实体
 *   EntityMangerFactory 相当于session的工厂 ,创建EntityManger
 *   
 *  1_ 获取EntityManagerFactory对象
 *  2_获取EntityManager
 *  3_获取事务对象
 *  4_ 开启事务
 * 5_实现各种操作
 *  6_提交/回滚事务
 *  7_释放资源
 */
public class Test01 {


@Test
public void test() throws Exception {
Customer c=new Customer();
c.setCustAddress("安河桥");
c.setCustIndustry("歌手");
c.setCustLevel("11");
c.setCustName("宋冬野");
c.setCustPhone("110");
c.setCustSource("歌手");

EntityManagerFactory fac = null;
EntityManager em = null;
EntityTransaction tx = null;

try {
fac = Persistence.createEntityManagerFactory("myUnit");
em = fac.createEntityManager();
tx = em.getTransaction();
//开启事务
tx.begin();
//执行添加操作
em.persist(c);

//提交事务
tx.commit();
} catch (Exception e) {
//报错则回滚事务
tx.rollback();
e.printStackTrace();
}finally {
//关闭资源
em.close();
}
}

}

7.测试结果:

JavaEE--SSH--hibernate-JPA的介绍和使用

JavaEE--SSH--hibernate-JPA的介绍和使用