JAVA entry [21]-simple Spring Data JPA example,-springjpa

Source: Internet
Author: User
Tags findone

JAVA entry [21]-simple Spring Data JPA example,-springjpa

Spring has powerful support for JPA. Developers only need to focus on the implementation code of core business logic, and do not need to focus too much on the creation of EntityManager, transaction processing, and other JPA-related processing. Spring Data JPA can automatically implement the persistence layer based on the method name.

Target

This time, our goal is to implement the functions in the previous sections, that is, to operate the data layer of Category. Complete and complete code structure:

Entity @ Table (name = "Category") public class Category implements Serializable {@ Override public String toString () {return "id =" + id + "name =" + name ;} private Integer id; @ Id public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} private String name; public String getName () {return name;} public void setName (String name) {this. name = name ;}}

  

Introduce JPA

The JPA specification requires that the configuration file must be named persistence. xml and coexist in the META-INF directory under the class path. This file usually contains all the information required to initialize the JPA engine. The LocalContainerEntityManagerFactoryBean provided by Spring provides flexible configuration, and information in persistence. xml can be provided in the form of property injection.

<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">    <persistence-unit name="category" transaction-type="RESOURCE_LOCAL">        <provider>org.hibernate.ejb.HibernatePersistence</provider>        <class>demoJPA.entity.Category</class>        <properties>            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/store"/>            <property name="hibernate.connection.username" value="root"/>            <property name="hibernate.connection.password" value="root"/>            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>            <property name="hibernate.show_sql" value="true"/>            <property name="hibernate.format_sql" value="true"/>            <property name="hibernate.use_sql_comments" value="false"/>            <property name="hibernate.hbm2ddl.auto" value="update"/>        </properties>    </persistence-unit></persistence>

  

Implement Data Persistence Layer

The core part is the support for the data persistence layer. The following three steps are required to use Spring Data JPA for persistent layer development:

1. Introduce dependencies first. Here we mainly use spring data commons and spring data jpa packages.

        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-commons</artifactId>            <version>1.13.3.RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-jpa</artifactId>            <version>1.11.3.RELEASE</version>        </dependency>

Complete pom:

<? Xml version = "1.0" encoding = "UTF-8"?> <Project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> DemoStore </groupId> <artifactId> DemoJPA </artifactId> <version> 1.0-SNAPSHOT </version> <properties> 

  

2. Declare the persistent layer interface CategoryDao to inherit the Repository interface. When Spring Data JPA creates a proxy object for the persistent layer interface in the background, it will parse the method name and automatically implement the corresponding functions.

public interface CategoryDao extends Repository<Category, Integer> {    void save(Category category);    Iterable<Category> findAll();    long count();    void delete(int id);}

  

3. Add a line of declaration to the Spring configuration file to allow Spring to create a proxy object for the declared interface. After <jpa: repositories> is configured, Spring will scan the package directory specified by base-package and its subdirectories during container initialization to create a proxy object for interfaces that inherit the Repository or its subinterfaces, and register the proxy object as Spring Bean, so that the business layer can directly use this object through the features automatically encapsulated by Spring.

<context:component-scan base-package="demoJPA"/>    <tx:annotation-driven transaction-manager="transactionManager"/>    <jpa:repositories base-package="demoJPA.dao"  repository-impl-postfix="Impl" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">        <property name="entityManagerFactory" ref="entityManagerFactory"/>    </bean>    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        <property name="jpaVendorAdapter">            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">                <property name="generateDdl" value="false"/>                <property name="showSql" value="true"/>            </bean>        </property>    </bean>

  

Use @ Query to create a Query

In addition to the method name resolution function, developers can directly use the @ Query Annotation on the declared method and provide a Query statement as a parameter. When Spring Data JPA creates a proxy object, it uses the provided query statement to implement its function.

@ Query annotation is very simple to use. You only need to mark the Annotation on the declared method and provide a JPQL Query statement. In the JPQL statement, parameters are specified in the format of ": variable". At the same time, @ Param is used before the method parameters to correspond the method parameters to the named parameters in jp ql.

    @Query("from Category where id=:id")    Category findOne(@Param("id") int id);

You can also use @ Query to perform an update operation. Therefore, you need to use @ Query and @ Modifying to mark the operation as Modifying the Query, in this way, the framework generates an update operation instead of a query.

    @Transactional    @Modifying    @Query("update Category  set name=:name where id=:id")    void updateName(@Param("id")int id,@Param("name")String name);

  

Unit Test
@ContextConfiguration(locations = "classpath:applicationContext.xml")@RunWith(SpringJUnit4ClassRunner.class)public class testJpa {    int id=5;    @Autowired    private CategoryDao categoryDao;    @Test    public void testSave(){        Category category=new Category();        category.setId(id);        category.setName("test");        categoryDao.save(category);    }    @Test    public void testUpdateName(){        String name="test111";        categoryDao.updateName(id,name);    }    @Test    public void testFindById(){        Category category=categoryDao.findOne(id);        System.out.println(category);    }    @Test    public void count(){        long count=categoryDao.count();        System.out.println(count);    }    @Test    public void testFindAll(){        Iterable<Category> categories=categoryDao.findAll();        for(Category category:categories){            System.out.println(category);        }    }    @Test    public void delete(){        categoryDao.delete(id);    }}

 

Source Code address: Https://github.com/cathychen00/learnjava/tree/master/DemoJPA

References:
  • Https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-jpa/index.html
  • Spring practice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.