| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
11年前发布

spring-data-jpa 入门资料

使用spring-data-jpa,结合hibernate快速开发

spring-data-jpa 入门资料

  • maven环境安装 
<dependency>   <groupId>org.springframework.data</groupId>   <artifactId>spring-data-jpa</artifactId>   <version>1.4.3.RELEASE</version>   </dependency>       <dependency>   <groupId>org.hibernate.javax.persistence</groupId>   <artifactId>hibernate-jpa-2.1-api</artifactId>   <version>1.0.0.Draft-16</version>   </dependency>   <dependency>   <groupId>org.hibernate</groupId>   <artifactId>hibernate-entitymanager</artifactId>   <version>4.2.7.SP1</version>   </dependency> 
spring-data-jpa下载jar会自动依赖包,包括spring framework框架包。
1.4.3.RELEASE依赖包是spring framework的版本是3.14
具体如下:
 


除此之外,需要手动选择jpa支持的厂商,我这里选择是hibernate。hibernate-jpa-2.1-api是指的jpa的2.1规范,hibernate-entitymanager是jpa的具体实现。


加入数据库驱动包及spring test
<dependency>   <groupId>com.h2database</groupId>   <artifactId>h2</artifactId>   <version>1.3.174</version>   </dependency>   <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-test</artifactId>   <version>3.1.4.RELEASE</version>   <scope>test</scope>   </dependency>  


最终,pom文件如下:

<dependencies>   <dependency>   <groupId>org.springframework.data</groupId>   <artifactId>spring-data-jpa</artifactId>   <version>1.4.3.RELEASE</version>   </dependency>     <dependency>   <groupId>org.hibernate.javax.persistence</groupId>   <artifactId>hibernate-jpa-2.1-api</artifactId>   <version>1.0.0.Draft-16</version>   </dependency>   <dependency>   <groupId>org.hibernate</groupId>   <artifactId>hibernate-entitymanager</artifactId>   <version>4.2.7.SP1</version>   </dependency>     <dependency>   <groupId>com.h2database</groupId>   <artifactId>h2</artifactId>   <version>1.3.174</version>   </dependency>   <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-test</artifactId>   <version>3.1.4.RELEASE</version>   <scope>test</scope>   </dependency>    </dependencies> 


  • 配置 
   在src/main/resources/META-INF目录下,新建persistence.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>   <persistence version="2.0"   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_2_0.xsd">   <persistence-unit name="jpa.sample.plain">   <properties>   <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />   <property name="hibernate.connection.url" value="jdbc:h2:tcp://127.0.0.1:9043/~/test" />   <property name="hibernate.connection.driver_class" value="org.h2.Driver" />   <property name="hibernate.connection.username" value="sa" />   <property name="hibernate.connection.password" value="123" />   <property name="hibernate.hbm2ddl.auto" value="create-drop" />   <property name="hibernate.show_sql" value="true" />   <property name="hibernate.format_sql" value="true" />   </properties>   </persistence-unit>   </persistence> 


在src/main/resources,新建infrastructure.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:tx="http://www.springframework.org/schema/tx"   xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd       http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">     <bean id="org.h2.tools.Server" class="org.h2.tools.Server"   factory-method="createTcpServer" init-method="start" destroy-method="stop">   <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9043" />   </bean>     <bean id="entityManagerFactory"   class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"   depends-on="org.h2.tools.Server">   <property name="persistenceUnitName" value="jpa.sample.plain" />   </bean>     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">   <property name="entityManagerFactory" ref="entityManagerFactory" />   </bean>     </beans> 

在src/main/resources,新建log4j.xml,内容如下:
<?xml version="1.0"?>   <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">     <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">   <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">   <layout class="org.apache.log4j.PatternLayout">   <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c] %m%n" />   </layout>   </appender>     <root>   <priority value="ERROR" />   <appender-ref ref="CONSOLE" />   </root>   </log4j:configuration> 

  • 开发 

    User类:

package org.springframework.data.jpa.example.domain;       import javax.persistence.Column;   import javax.persistence.Entity;   import javax.persistence.NamedQuery;       import org.springframework.data.jpa.domain.AbstractPersistable;       /**    * Sample user class.    *     * @author Oliver Gierke    * @author Thomas Darimont    */   @Entity   @NamedQuery(name = "User.findByTheUsersName", query = "from User u where u.username = ?1")   public class User extends AbstractPersistable<Long> {       private static final long serialVersionUID = -2952735933715107252L;       @Column(unique = true) private String username;       private String firstname;   private String lastname;       public User() {   this(null);   }       /**   * Creates a new user instance.   */   public User(Long id) {   this.setId(id);   }       /**   * Returns the username.   *    * @return   */   public String getUsername() {       return username;   }       /**   * @param username the username to set   */   public void setUsername(String username) {   this.username = username;   }       /**   * @return the firstname   */   public String getFirstname() {   return firstname;   }       /**   * @param firstname the firstname to set   */   public void setFirstname(String firstname) {   this.firstname = firstname;   }       /**   * @return the lastname   */   public String getLastname() {   return lastname;   }       /**   * @param lastname the lastname to set   */   public void setLastname(String lastname) {   this.lastname = lastname;   }   } 




SimpleUserRepository类:


package org.springframework.data.jpa.example.repository.simple;       import java.util.List;       import org.springframework.data.jpa.example.domain.User;   import org.springframework.data.jpa.repository.Query;   import org.springframework.data.repository.CrudRepository;   import org.springframework.data.repository.query.Param;       /**    * Simple repository interface for {@link User} instances. The interface is used to declare so called query methods,    * methods to retrieve single entities or collections of them.    *     * @author Oliver Gierke    * @author Thomas Darimont    */   public interface SimpleUserRepository extends CrudRepository<User, Long> {       /**   * Find the user with the given username. This method will be translated into a query using the   * {@link javax.persistence.NamedQuery} annotation at the {@link User} class.   *    * @param lastname   * @return   */   User findByTheUsersName(String username);       /**   * Find all users with the given lastname. This method will be translated into a query by constructing it directly   * from the method name as there is no other query declared.   *    * @param lastname   * @return   */   List<User> findByLastname(String lastname);       /**   * Returns all users with the given firstname. This method will be translated into a query using the one declared in   * the {@link Query} annotation declared one.   *    * @param firstname   * @return   */   @Query("select u from User u where u.firstname = ?")   List<User> findByFirstname(String firstname);       /**   * Returns all users with the given name as first- or lastname. Makes use of the {@link Param} annotation to use named   * parameters in queries. This makes the query to method relation much more refactoring safe as the order of the   * method parameters is completely irrelevant.   *    * @param name   * @return   */   @Query("select u from User u where u.firstname = :name or u.lastname = :name")   List<User> findByFirstnameOrLastname(@Param("name") String name);   } 



加入spring配置:

<?xml version="1.0" encoding="UTF-8"?>   <beans xmlns="http://www.springframework.org/schema/beans"   xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">       <import resource="infrastructure.xml" />       <jpa:repositories   base-package="org.springframework.data.jpa.example.repository.simple" />     </beans> 





  • 测试 
AbstractSimpleUserRepositoryTests类:

package org.springframework.data.jpa.example.repository.simple;       import static org.junit.Assert.*;       import java.util.List;       import org.junit.Before;   import org.junit.Test;   import org.junit.runner.RunWith;   import org.springframework.beans.factory.annotation.Autowired;   import org.springframework.data.jpa.example.domain.User;   import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;   import org.springframework.transaction.annotation.Transactional;       /**    * Intergration test showing the basic usage of {@link SimpleUserRepository}.    *     * @author Oliver Gierke    * @author Thomas Darimont    */   @RunWith(SpringJUnit4ClassRunner.class)   //@Transactional   public abstract class AbstractSimpleUserRepositoryTests {       @Autowired SimpleUserRepository repository;   User user;       @Before   public void setUp() {   user = new User();   user.setUsername("foobar");   user.setFirstname("firstname");   user.setLastname("lastname");   }       @Test   public void findSavedUserById() {       user = repository.save(user);   user = repository.findByTheUsersName("foobar");       // assertEquals(user, repository.findOne(user.getId()));   }       @Test   public void findSavedUserByLastname() throws Exception {       // user = repository.save(user);       List<User> users = repository.findByLastname("lastname");       // assertNotNull(users);   // assertTrue(users.contains(user));   }       @Test   public void findByFirstnameOrLastname() throws Exception {       // user = repository.save(user);       List<User> users = repository.findByFirstnameOrLastname("lastname");       // assertTrue(users.contains(user));   }   } 




XmlConfigSimpleUserRepositoryTests类:

package org.springframework.data.jpa.example.repository.simple;       import org.springframework.test.context.ContextConfiguration;       /**    * @author Thomas Darimont    */   @ContextConfiguration(locations = "/simple-repository-context.xml")   public class XmlConfigSimpleUserRepositoryTests extends AbstractSimpleUserRepositoryTests {} 

  • 结果 
 
160400_bb0i_1177247.jpg

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1387370269140.html
Spring 持久层框架