1.orm思想和以及jpa的概述和jpa的基本操作
简单的说:ORM就是建立实体类和数据库表之间的关系,从而达到操作实体类就相当于操作数据库表的目的。
orm思想
主要目的:操作实体类就相当于操作数据库表
建立两个映射关系:
实体类和表的映射关系
实体类中属性和表中字段的映射关系
不再重点关注:sql语句
实现了ORM思想的框架:mybatis,hibernate
2.hibernate框架介绍
Hibernate是一个开放源代码的对象关系映射框架,
它对JDBC进行了非常轻量级的对象封装,
它将POJO与数据库表建立映射关系,是一个全自动的orm框架
3. JPA
jpa规范,实现jpa规范,内部是由接口和抽象类组成
JPA规范本质上就是一种ORM规范,注意不是ORM框架——因为JPA并未提供ORM实现,它只是制订了一些规范,提供了一些编程的API接口,但具体实现则由服务厂商来提供实现。
3.1JPA与hibernate的关系
JPA和Hibernate的关系就像JDBC和JDBC驱动的关系,JPA是规范,Hibernate除了作为ORM框架之外,它也是一种JPA实现。JPA怎么取代Hibernate呢?JDBC规范可以驱动底层数据库吗?答案是否定的,也就是说,如果使用JPA规范进行数据库操作,底层需要hibernate作为其实现类完成数据持久化工作。
4.Spring Data JPA的快速入门
1>创建maven工程导入依赖的jar坐标
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<hibernate.version>5.0.7.Final</hibernate.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysql.version>5.1.6</mysql.version>
</properties>
<dependencies>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<!-- spring beg -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring对orm支持的包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring end -->
<!-- hibernate beg -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- hibernate end -->
<!-- c3p0 beg -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- c3p0 end -->
<!-- log end -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- el beg 使用spring data jpa 必须引入 -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- el end -->
</dependencies>
2>配置JPA的核心配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!--spring和spring datajpa的配置-->
<!--1. 创建entityManagerFactory对象交给spring容器管理-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="packagesToScan" value="com.hdh.domain"></property>
<!--jpa的实现厂家-->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
</property>
<!--jpa的供应商适配器-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--generateDdl 配置是否自动创建数据库表-->
<property name="generateDdl" value="false"/>
<!--database 指定数据库类型-->
<property name="database" value="MYSQL"/>
<!--数据库方言:支持特有的语法-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<!--是否显示sql语句-->
<property name="showSql" value="true"/>
</bean>
</property>
<!--jpa的方言:高级的特性-->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
</property>
</bean>
<!--2.创建数据库连接池-->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="12345"></property>
<property name="jdbcUrl" value="jdbc:mysql:///jpa"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
</bean>
<!-- 3.整合spring data jpa-->
<jpa:repositories base-package="com.hdh.dao" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory">
</jpa:repositories>
<!--4.配置事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 5.txAdvice声明式事务-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 5.aop-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.hdh.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
</aop:config>
<context:component-scan base-package="com.hdh"></context:component-scan>
<!--组装其它 配置文件-->
</beans>
3> 使用JPA注解配置映射关系(get,set,tostring省略)
/**
* 客户的实体类
* 配置映射关系:
* 1.实体类和表的映射关系
* @Entity 声明是实体类
* @Table(name = "cst_customer") 表示对应数据库中的表
*
* 2.实体类中属性和表中字段的映射
*/
@Entity
@Table(name = "cst_customer")
public class Customer implements Serializable {
/**@Id 主键
* @GeneratedValue 配置主键的生成策略
* GenerationType.IDENTITY 自增 条件:数据库必须支持自动增长
* GenerationType.SEQUENCE 序列 条件:数据库必须支持序列,Oracle支持
* GenerationType.TABLE jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
* GenerationType.AUTO 由程序自动帮我们选择
* @Column 实体类中属性和表中字段的映射
*/
@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;//客户电话
4> 编写符合Spring Data JPA规范的Dao层接口
/**
* 符合SpringDataJpa的dao层接口规范
* 1.JpaRepository<操作的实体类类型,主键的类型> 封装了CRUD
* <p>
* 2.paSpecificationExecutor<操作的实体类类型> 封装了复杂查询
*/
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
5>测试 完成基本CRUD操作
@RunWith(SpringJUnit4ClassRunner.class)//声明spring提供的单元测试
@ContextConfiguration(locations = "classpath:application.xml") //指定spring的配置文件
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao;
/**
* 更具id查询
*/
@Test
public void findOne() {
Customer customer = customerDao.findOne(2l);
System.out.println(customer);
}
/**
* save:保存或者更新
* 根据传递的对象是否存在直接id,如果没有主键则为保存
* 如果有主键则为更新
*/
@Test
public void save() {
Customer customer = new Customer();
customer.setCustId(8l);
customer.setCustName("hdh");
customer.setCustLevel("vip");
customer.setCustSource("学生");
customerDao.save(customer);
}
@Test
public void update() {
Customer customer = new Customer();
customer.setCustId(8l);
customer.setCustName("哈哈哈");
customerDao.save(customer);
}
@Test
public void delete() {
customerDao.delete(8l);
}
/**
* 查询所有
*/
@Test
public void findAll() {
List<Customer> list = customerDao.findAll();
for (Customer customer : list) {
System.out.println(customer);
}
}
/**
* 统计查询所有 count
*/
@Test
public void count() {
long count = customerDao.count();
System.out.println(count);
}
/**
* 判断id=4l的客户是否存在
*/
@Test
public void exists() {
boolean exists = customerDao.exists(4l);
System.out.println(exists);
}
/**
* 根据id从数据库查询
* 需要加Transactional
* findOne:立即加载
* getOne:延迟加载
*/
@Test
@Transactional
public void getOne() {
Customer customer = customerDao.getOne(4l);
// System.out.println(customer);
}
}