SpringDataJPA
一.SpringDataJpa入门案列
1.搭建环境
1.1 创建工程导入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>
<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>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
1.2 配置配置文件
<?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">
<bean id="dataSources" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
<!--1.创建entityManagerfactory对象交给spring容器管理-->
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSources"></property>
<!-- 2.配置的是扫描的包,实体类所在包-->
<property name="packagesToScan" value="cn.xkm.domain"></property>
<!-- 3.jpa实现厂家-->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"
</property>
<!--JPA的供应商适配器-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 配置是否自动创建数据库表-->
<property name="generateDdl" value="false" />
<!-- 指定数据库类型-->
<property name="database" value="MYSQL" />
<!-- 数据库方言,支持的特有语法-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<property name="showSql" value="true" />
</bean>
</property>
<!-- jpa的方言:高级的特性-->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
</property>
</bean>
<!-- 整合springdatajpa-->
<jpa:repositories base-package="cn.xkm.dao" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManager"></jpa:repositories>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager"></property>
</bean>
<!-- spring声明式事务,此处省略-->
<!-- 注解包扫描-->
<context:component-scan base-package="cn.xkm"></context:component-scan>
</beans>
1.3 创建客户实体类并配置映射关系
package cn.xkm.domain;
import javax.persistence.*;
@Entity
@Table(name="cst_customer")
public class Customer {
@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; //客户联系方式
1.4 编写SpringDataJpa规范的Dao接口
不需要写额外代码,只要继承两个接口就行
//符合SpringDataJpa的Dao曾接口规范
//JpaRepository<操作的实体类类型,实体类中主键属性的类型>
// *封装了基本的CRUD操作
//JpaSpecificationExecutor<操作的实体类类型>
// *封装了复杂查询(分页)
public interface JpaDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
}
1.5 测试代码
1.5.1 findall查询所有
//声明Spring提供的单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定spring容器的配置信息
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JpaTest {
@Autowired
private JpaDao jpaDao;
@Test
public void findall(){
List<Customer> all = jpaDao.findAll();
all.forEach(a-> System.out.println(a));
}
}
1.5.2 save保存和更新
如果主键存在,则更新,如果主键不存在则保存,都是save
jpaDao.save(customer);
1.5.3 delete删除记录
jpaDao.delete(4l);
2.复杂查询
2.1 findone (立即加载)
Customer one = jpaDao.findOne(5l);
System.out.println(one);
2.2 getone (延迟加载)
需要加上 @Transactional注解防止报错
@Test
@Transactional
public void getOne(){
Customer one = jpaDao.getOne(5l);
System.out.println(one);
}
2.3 自定义方法查询
在Dao接口上添加@Query注解,并设定查询语句
public interface JpaDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
@Query(value = "from Customer where custName = ? and custId = ?")
public List<Customer> findJpql(String custName,long id);
}
2.4自定义方法更新
注:
1.dao接口中方法要加上 @Modifying,代表此操作是更新
2.更新操作要添加事务管理的注解 @Transactional
3.更新会默认回滚,要将默认回滚设为False,否则不成功 @Rollback(false)
@Query(value = "update Customer set custName = ? where custId = ?")
@Modifying//代表此操作是更新
public void updateJpql(String custName,long id);
@Test
@Transactional
@Rollback(false)
public void update(){
jpaDao.updateJpql("xkm",3l);
}
}
2.5 在JPA中用SQL查询
2.5.1 查询全部
1.在dao中的 @Query注解中输入查询语句,并开启sql查询nativeQuery = true,默认为false
2.返回值设为List<Object[]>
@Query(value = "select * from cst_customer",nativeQuery = true)
public List<Object[]> findAllSql();
List<Object[]> objects = jpaDao.findAllSql();
for (Object[] object : objects) {
String s = Arrays.toString(object);
System.out.println(s);
2.5.2 条件查询
添加参数即可
@Query(value = "select * from cst_customer where cust_name = ?",nativeQuery = true)
public List<Object[]> findoneSql(String name);
2.6 方法命名规则查询
注:用提供好的命名规则,可以不用自己定义查询语句,例如:findBy开头
public Customer findByCustId(Long id);
Customer byCustId = jpaDao.findByCustId(4l);
System.out.println(byCustId);