SpringDataJPA_day02

SpringDataJpa的由来:
	Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架
	jdbc-->hibernate-->jpa-->SpringDataJpa
主要的4种查询思想:
1.使用Spring Data JPA中接口定义的方法进行查询
	直接使用,不需要任何操作
2.使用JPQL的方式查询
	dao接口上加@Query注解,只能使用jpql语句查询;修改和删除需要在dao接口上加@Query和@Modifying注解,
在测试方法上加@Transactional和@Rollback(false)注解
3.使用SQL语句查询
	dao接口上加@Query注解,并指定属性值@Query(value="原生sql",nativeValue=true)
4.方法命名规则查询
	方法命名为findBy....,jpq框架会自动完成方法的实现
SpringDataJpa API
JpaRepository<T,ID>接口下:	
//不需要dao中写任何方法,直接就可以通过继承关系调用,方法名固定(内置jpql)
	save(Object obj);	//增,改
	delete(Long id);	//删
	findOne(Long id);	//查,立即加载
	getOne(Long id);	//查,延迟加载
	findAll();
JpaSpecificationExecutor<T>接口下:
//需要在dao中声明方法,并在@Query注解中指定jpql语句,方法名自定义
	@Query("from Customer")
	
Dao层接口
	Dao层接口实现JpaRepository<T,ID>和JpaSpecificationExecutor<T>接口,即可由hibernate自动方法封装;
JpaRepository<实体类,主键> 完成基本的CRUD操作;JpaSpecificationExecutor<实体类>完成复杂条件查询
	Dao层接口本质上通过JdkDynamicAopProxy生成一个动态代理对象,这个动态代理对象就是SimpleJpaRepository,而SimpleJpaRepository对象又会继续在底层找EntityManager对象来完成真正的CRUD操作
	DAO接口-->JDKDynamicAopProxy-->SimpleJpaRepository-->EntityManager
//注意:不需要@Repository注解
public interface ICustomerDao extends 		//类只能单一继承,接口可以多继承JpaRepository<Customer,Long>,JpaSpecificationExecutor<Customer>{

	@Query("from Customer")
	List<Customer> findAllCustomer();

	@Query("from Customer where custName = ? and custAddress = ?")	
	//默认会自动按照参数的顺序进行对"?"的赋值
	Customer findCustomerByNameAndAddress(String name,String address);

	@Query("from Customer where custName = ?2 and custAddress = ?1")	
	//也可以在?后面跟上参数的排序,从1开始
	Customer findCustomerByNameAndAddress(String address,String name);

	@Query("from Customer where custName = :name and custAddress = :address ")	
	//还可以用":变量"来代替占位符,然后用@Param注解来指定参数的对应的值
	Customer findCustomerByNameAndAddress(
        @Param("address")String address,@Param("name")String name);

	@Query("update Customer set custName = :name where custId : id")
	@Modifying
	void updateCustomer(@Param("name")String,@Param("id") id);

	@Query(value="select * from cst_customer",nativeValue=false)
	//nativeValue默认是false,表示使用jpql;指定为true表示使用sql查询
	List<Customer> findAllCustomer2();
}
测试类:
@Runwith(SpringJunit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class JpaTest{
    @Autowired 		//由于在jpa:repositories中配置了扫描dao接口,并自动生成代理类,所以可以完成注入
    private ICustomerDao customerDao;
    <!-------------------使用Spring Data JPA中接口定义的方法进行查询------------------->
	@Test	//增,改;没有主键就是增,有主键就是改(改会清空之前的数据,再重新设置新的实体数据)
    public void testSave(){
        Customer customer = new Customer();
        customer.set...
        customerDao.save(customer);   
    }
    @Test	//删
    public void testDelete(){
        customerDao.delete(2);
    }
    @Test  //查
     public void testFind(){
        customerDao.findOne(2);	//查询一个,立即加载,底层调用entityManager.find(2);
        customerDao.findAll();	//查询所有,立即加载,底层调用entityManager.findAll();
        customerDao.getOne(2);	//查询一个,延迟加载,底层调用entityManager.getReference();
    }
    <!-------------------------使用JPQL的方式查询--------------------------------> 
	@Test	//查询所有
    public void testFindAllCustomer(){
        List<Customer> customerDao.findAllCustomer();
    }
    
    @Test	//改和删
    @Transactional		//执行删/改需要在方法上加@Transactional注解,表示开启事务
    @Rollback(false)	//默认事务会自动回滚,所以需要设置为false
    public void updateCustomer(){	//接口方法上需要@Query注解+@Modifying注解
        customerDao.updateCustomer("张三",2l);
    }
     <!-------------------------使用SQL语句查询--------------------------------> 
	@Test	//查询所有
    public void testFindAllCustomer(){
        List<Customer> customerDao.findAllCustomer2();	
    }
	 <!-------------------------方法命名规则查询-------------------------------> 
     按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。
}
实体类Entity
@Entity
@Table(name="cst_customer")
public class Customer{
    .....
}
applicationContext.xml的配置
<?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">
	
	<!-- 1.dataSource 配置数据库连接池-->
	<bean id="dataSource" 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>
	
	<!-- 2.配置entityManagerFactory -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
        <!--配置包扫描,扫描@Entity和@Table注解-->
		<property name="packagesToScan" value="com.baidu.entity" />
		<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>
		<property name="jpaDialect">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
		</property>
	</bean>
    
	<!-- 3.事务管理器-->
	<!-- JPA事务管理器  -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	
	<!-- 整合spring data jpa-->
    	<!--配置包扫描,扫描dao层接口,自动生成SimpleJpaRepository的代理类,接口上不需要任何注解-->
	<jpa:repositories base-package="com.baidu.dao"
		transaction-manager-ref="transactionManager"
		entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
		
	<!-- 4.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.baidu.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
	</aop:config>
	
    <!--配置包扫描,扫描类上的@Component/@Controller/@Service/@Repository注解-->
	<context:component-scan base-package="com.baidu"></context:component-scan>
		
	<!--组装其它 配置文件-->
    
</beans>
SpringDateJPA的坐标
	<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 begin -->
        <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 begin -->
        <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 begin -->
        <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 begin 使用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值