SPRING-DATA-JPA Project Building

Source: Internet
Author: User
Tags connection pooling

Portal : Spring Data Learning Spring Data development environment Building

Brief introduction

What is Spring data

Spring data is an open-source framework for simplifying database access and supporting cloud services. Its main goal is to make access to data easier and faster. What spring data JPA can do

Can greatly simplify the formulation of JPA, can be used in the case of almost no write implementation, the implementation of data access and operation. In addition to CRUD, it also includes some common functions such as paging, sorting, and so on.

what does Spring Data JPA haveThe main thing to look at is the interface provided by spring data JPA, which is also the core concept of spring data JPA: 1:repository: The topmost interface is an empty interface that is designed to unify all Repository types and to automatically recognize components when they are scanned. 2:crudrepository: is a repository sub-interface that provides CRUD functionality 3:pagingandsortingrepository: is a crudrepository sub-interface, adding pagination and sorting functions 4:jparepo    Sitory: Is the Pagingandsortingrepository sub-interface, added some useful functions, such as: batch operation. 5:jpaspecificationexecutor: The interface used to do the query 6:specification: A query specification provided by Spring Data JPA, to make complex queries, simply set the query criteria around this specification to feature
    • Powerful repositories and custom object mapping abstractions
    • Dynamic query export from the repository method name
    • Implementing a domain base class provides basic properties
    • Support Transparent auditing (create, last change)
    • Possibility to integrate custom repository code
    • Easy Spring integrates with Javaconfig and custom XML namespaces
    • Advanced integration with Spring MVC Controller
    • Experimental support for cross-store storage

Building process

1. Configure XML

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"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-4.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA http://www.springframework.org/schema/data/jpa/ Spring-jpa-1.3.xsd "Default-lazy-init= "true">    <Description>Spring Public configuration</Description>    <!--Database Connection -    <Context:property-placeholder Location= "Classpath:/config/jdbc.properties"/>    <!--Scan Service Packs -    <Context:component-scanBase-package= "Com.wang.service"/>    <!--Jpa Entity Manager configuration -    <BeanID= "Entitymanagerfactory"class= "Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        < Propertyname= "DataSource"ref= "DataSource"/>        < Propertyname= "Jpavendoradapter"ref= "Hibernatejpavendoradapter"/>        < Propertyname= "Packagestoscan"value= "Com.wang.entity"/>        < Propertyname= "Jpaproperties">            <Props>                <!--naming rules My_name->myname -                <propKey= "Hibernate.ejb.naming_strategy">Org.hibernate.cfg.ImprovedNamingStrategy</prop>                <propKey= "Hibernate.dialect">Org.hibernate.dialect.MySQL5InnoDBDialect</prop>                <propKey= "Hibernate.show_sql">True</prop>                <propKey= "Hibernate.format_sql">True</prop>                <propKey= "Hibernate.hbm2ddl.auto">Update</prop>            </Props>        </ Property>        < Propertyname= "Jpadialect">            <Beanclass= "Org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>        </ Property>    </Bean>    <BeanID= "Hibernatejpavendoradapter"class= "Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>    <!--Spring Data JPA configuration -    <jpa:repositoriesBase-package= "Com.wang.reposity"Transaction-manager-ref= "TransactionManager"Entity-manager-factory-ref= "Entitymanagerfactory"/>    <!--JPA Transaction Configuration -    <BeanID= "TransactionManager"class= "Org.springframework.orm.jpa.JpaTransactionManager">        < Propertyname= "Entitymanagerfactory"ref= "Entitymanagerfactory"/>    </Bean>    <!--defining transactions using annotation -    <Tx:annotation-drivenTransaction-manager= "TransactionManager"Proxy-target-class= "true"/>    <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate">        < Propertyname= "DataSource"ref= "DataSource"/>    </Bean>    <!--data source configuration, using the Tomcat JDBC Connection pool -    <BeanID= "DataSource"class= "Org.apache.tomcat.jdbc.pool.DataSource"Destroy-method= "Close">        <!--Connection Info -        < Propertyname= "Driverclassname"value= "${jdbc.driver}"/>        < Propertyname= "url"value= "${jdbc.url}"/>        < Propertyname= "username"value= "${jdbc.username}"/>        < Propertyname= "Password"value= "${jdbc.password}"/>        <!--Connection Pooling Info -        < Propertyname= "Maxactive"value= "${jdbc.pool.maxactive}"/>        < Propertyname= "Maxidle"value= "${jdbc.pool.maxidle}"/>        < Propertyname= "Minidle"value= "0"/>        < Propertyname= "Defaultautocommit"value= "true"/>    </Bean></Beans>

2. Create an entity class

Package Com.wang.entity;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import javax.persistence.table;import java.util.Date, @Entity @table (name= "Jpa_persons")    public class Person {private Integer ID;    Private String LastName;    Private String Email;    Private Date birth;    Public person () {} @GeneratedValue//is self-increasing by default in the database @Id public Integer getId () {return Id;    } public void SetId (Integer id) {this.id = ID;    } public String Getlastname () {return lastName;    } public void Setlastname (String lastName) {this.lastname = LastName;    } public String Getemail () {return email;    } public void Setemail (String email) {this.email = email;    Public Date Getbirth () {return birth;    } public void Setbirth (Date birth) {This.birth = birth; } @Override Public String toString () {return "person{" + "id=" + ID + ", lastname= '" + lastName + "\" + ", email=" + email + "\" + ", birth=    "+ Birth + '} '; }}

  

3. Writing the Reposity interface class

Package Com.wang.reposity;import Com.wang.entity.person;import org.springframework.data.repository.repository;/** * Operation of the interface of the person class * need to inherit from repository * Parameter 1: Entity class representing the current operation * Parameter 2: Represents the primary key type of the entity class * @author Dell * *repository is the core interface of Springdata, the implementation of this interface provides Specification of the Spring Data Operations database-the naming specification * query is */public interface Personrepository extends Repository<person with GET or find or read start integer> {person    getbylastname (String lastName);}

  

4. Testing

Package Com.wang.reposity;import Com.wang.entity.person;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Testspringdata {    private ApplicationContext context;    Private Personrepository personrepository;    @org. Junit.before  //The annotation means execute this code before executing the @test annotation public    Void before () {        context=new Classpathxmlapplicationcontext ("/spring/spring-context.xml");        Personrepository=context.getbean (personrepository.class);        System.out.println ("Pre-Test");    }    @Test public    void Testhellord () {person person        = personrepository.getbylastname ("Wang");        SYSTEM.OUT.PRINTLN (person);    }}

  

SPRING-DATA-JPA Project Building

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.