Spring Data JPA是簡化基於JPA和Spring整合應用開發,從此之後,持久層無需實現類,只需接口即可!
1. 導入spring data jpa座標
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> </dependency> |
2. 配置applicationContext.xml
1)先加入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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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"> |
2)配置spring data jpa:
<!-- spring data jpa的Dao接口的包掃描 base-package: --> <jpa:repositories base-package="com.itheima.bos.dao"/> |
3. 改造Dao接口
package com.itheima.bos.dao.base;
import org.springframework.data.jpa.repository.JpaRepository;
import com.itheima.bos.domain.base.Standard; /** * * 參數一:需要操作的實體類型 * 參數二:實體裏面的主鍵屬性類型 */ public interface StandardDao extends JpaRepository<Standard, Long>{ }
|
4. 編寫測試類
package com.itheima.test;
import javax.annotation.Resource;
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional;
import com.itheima.bos.dao.base.StandardDao; import com.itheima.bos.domain.base.Standard;
@RunWith(SpringJUnit4ClassRunner.class) // 導入Spring環境 @ContextConfiguration("classpath:applicationContext.xml") // 加載applicationContext.xml配置文件 publicclass StandardDaoTest {
//注入dao @Resource private StandardDao standardDao;
@Test @Transactional// 在測試方式裏面使用事務管理,注意:@Transactional用在@Test方法裏面,事務會自動回滾的 @Rollback(false) // 取消自動回滾 publicvoid testSave(){ Standard standard = new Standard(); standard.setName("10-20斤"); standard.setMinWeight(10L); standard.setMaxWeight(20L); standard.setMinLength(1000L); standard.setMaxLength(2000L);
standardDao.save(standard); } }
|