Java Learning Spring Data JPA

Source: Internet
Author: User

The purpose of the framework is to simplify operations, improve code utilization, the JDBC way there are many deficiencies, so not the framework required, so SPRINGJPA come forward, it not only has SPRINGJDBC integration, but also has simplified SQL, to achieve paging and other more powerful features.

Its implementation is similar to spring JDBC, where its configuration file is glued

<?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: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.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA http://www.springframework.org/schema/data/jpa/ Spring-jpa-1.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.0.xsd "> <!--1 configuration data Source-<bean id=" DataSource "class=" Org.springframework.jdbc.datasourc E.drivermanagerdatasource "> <property name=" driverclassname "value=" com.mysqL.jdbc.driver "/> <property name=" username "value=" root "/> <property name=" password "value=" "/&gt        ; <property name= "url" value= "Jdbc:mysql:///db_name"/> </bean> <!--2 configuration entitymanagerfactory--> &L T;bean id= "Entitymanagerfactory" class= "Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > & Lt;property name= "DataSource" ref= "DataSource"/> <property name= "Jpavendoradapter" > <bean cl ass= "Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> </property> <property name=                "Packagestoscan" value= "Com.imooc"/> <property name= "jpaproperties" > <props> <prop key= "Hibernate.ejb.naming_strategy" >org.hibernate.cfg.ImprovedNamingStrategy</prop> &L T;prop key= "Hibernate.dialect" >org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key= "Hibe Rnate.show_sql "&Gt;true</prop> <prop key= "Hibernate.format_sql" >true</prop> <prop key= "h Ibernate.hbm2ddl.auto ">update</prop> </props> </property> </bean> <!        --3 Configuration Transaction Manager--<bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionManager" >    <property name= "Entitymanagerfactory" ref= "Entitymanagerfactory"/> </bean> <!--4 Configure annotations-enabled transactions-- <tx:annotation-driven transaction-manager= "TransactionManager"/> <!--5 configuration spring data--> <jpa:reposit Ories base-package= "Com.repository" entity-manager-factory-ref= "Entitymanagerfactory"/> <context: Component-scan base-package= "Com.beans"/></beans>

In this case, note 1 and note 5: Automatic scan to find repositories; scan Bean class

Automatically scans to @Entity (doamin) and @repositorydefinition () annotations

To @Entity: This entity class will correspond to a database table (this table is not automatically created, the unique features of spring JPA), and is used as a bean

@Entitypublic class student{    private Integer ID;    private String name;    Private Integer age;    @GeneratedValue    @Id public    Integer getId () {        return Id;    }    public void SetId (Integer id) {        this.id = ID;    }    @Column (length =) public    String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public Integer Getage () {        return age;    }    public void Setage (Integer age) {        this.age = age;    }}

To @repositorydefinition (if not repositorydefinition directly inherit the repository class can also be implemented), using this annotation can be implemented Studentrepositor interface (interface name of its own definition, Generally take the name of the Bean), when used only to inherit this interface can. And this class can also be implemented in SQL encapsulation below is a list of several implementations I wrote

@RepositoryDefinition (DomainClass = student.class, Idclass = integer.class) public interface Studentrepository {public    Student findbyname (String name);    Where name like?% and age <?    Public list<student> Findbynamestartingwithandagelessthan (String name, Integer age); Where name like%?    and age <?    Public list<student> Findbynameendingwithandagelessthan (String name, Integer age);    where name in (?,?....) or age <?    Public list<student> Findbynameinoragelessthan (list<string> names, Integer age);    where name in (?,?....) and age <?    Public list<student> Findbynameinandagelessthan (list<string> names, Integer age);    @Query ("Select O from Student o where id= (select Max (ID) from Student T1)") Public Student Getemployeebymaxid (); @Query ("Select O from Student o where o.name=?1 and o.age=?2") public list<student> queryParams1 (String name, Int    Eger age); @Query ("Select O from Student o where O.namE=:name and O.age=:age ") public list<student> QueryParams2 (@Param (" name ") String name, @Param (' age ') Integer age);    @Query ("Select O from Student o where o.name like%?1%") public list<student> queryLike1 (String name); @Query ("Select O from Student o where o.name like%:name%") public list<student> QueryLike2 (@Param ("name") String    name);  @Query (Nativequery = true, value = "SELECT COUNT (1) from Student") public long GetCount (); modifying implements @Modifying @Query of Things ("Update Student o set o.age =: Age where o.id =: id"), public void update (@Para m ("id") Integer ID, @Param ("Age") of integer Age);

Repository query methods define rules and use

Next, as long as the implementation of Employeerepository interface can happily curd.

Gets by context
CTX = new Classpathxmlapplicationcontext ("Beans-new.xml"); studentrepository = Ctx.getbean (Studentrepository.class);
Student Student = Studentrepository.findbyname ("Zhangsan"); SYSTEM.OUT.PRINTLN ("ID:" + student.getid () + ", Name:" + student.getname () + ", Age:" + student.getage ());}

So how to achieve paging? It's simple, as long as the Studentrepository class inherits the PagingAndSorting interface.

Public interface Studentrepository extends pagingandsortingrepository{}

Operation note the Pageable class needs to introduce the Pageable class in the JPA package

Get CTX = new Classpathxmlapplicationcontext ("Beans-new.xml") according to the context; studentrepository = Ctx.getbean ( Studentrepository.class); pageable pageable = new Pagerequest (0,5); Student Student = Studentrepository.findall (pageable);

Java Learning Spring Data JPA

Related Article

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.