Spring Data JPA Understanding (default query custom query paged query) and no session two methods of processing

Source: Internet
Author: User
Tags string format

Summary: Spring Data JPA is actually a dynamic proxy for JDK mode (requires an interface with a whole bunch of top-repository interfaces from Org.springframework.data.repository,
There are crudrepository interface and an implementation class Simplejparepository), as long as there is an interface can query the database, in fact, is the proxy method, the specific query method has two
One is simply the method named findby+ attribute name + (andorisequals, etc.)
The other is the custom method is that the property name is blind to ABC xyz what the fundamental cannot find this attribute, then can use SQL or JPQL two languages
@Query (Nativequery=false is the default without writing, can be used in jpql language, value= "from standard where name=?")
@Query (Nativequery=true must be written, represented in SQL language, value= "SELECT * from Standard where c_name=?")
Public list<standard> findbyabc (String name) parameter is?
If the addition and deletion of the operation to add @modifying

Paging: For paged query, it is more convenient
Public interface Standarddao extends Jparepository<standard, integer>{//inherited interfaces already contain methods in the paging query interface
So just in the service implementation class
@Service
@Transactional
public class Standardserviceimpl implements Standardservice {//Call FindAll (pageable pageable) method that is not visible in the DAO interface
Public page<standard> pagequery (pageable pageable) {//
Return Standarddao.findall (pageable);
}
The pageable is also an interface, and his implementation class encapsulates the parameters submitted by page and rows two browsers (URL requests from the Easyui DataGrid that require the DataGrid to have pagination properties)
pageable pageable = new Pagerequest (page-1, rows);
Note that the index of the page starts at 0 and 0 represents the first page, so subtract one
Page is the page number of a paged query rows is a few pages per page
Only the implementation class object that is automatically injected into the service interface through the spring framework in the action of the Web tier
@Autowired
Private Standardservice Standardservice;
Call one of the methods
page<standard> page = Standardservice.pagequery (pageable);
You can get the implementation class object of the page interface,
The content in the Page object is exactly what is required in the Easyui DataGrid component, but the name is different, not rows, but content
{
"Total": 86,
"Rows": [
{"id": 101, "name": "Jack", "Age": 20},
{"id": 102, "name": "Rose", "Age": 21},
{"id": 103, "name": "Lili", "Age": 22}
]
}
Total number of records obtained through Page.gettotalelements ()
Get content based on paged query via Page.getcontent ()
By outputting to the console
SYSTEM.OUT.PRINTLN ("Total number of records:" +page.gettotalelements ());
System.out.println ("Current page record:" +page.getcontent ());
The result is that the number type and the list collection are not the JSON format we need
Convert the Map collection to the top JSON format and set the key value to the "Rows" we need
map<string, object> map = new hashmap<> ();
Map.put ("Total", page.gettotalelements ());
Map.put ("Rows", page.getcontent ());
Convert to JSON string format using Jsonlib Jsonobject
String JSON = jsonobject.fromobject (map). ToString ();
Send back to Browser
Servletactioncontext.getresponse (). setContentType ("Text/json;charset=utf-8");
Servletactioncontext.getresponse (). Getwriter (). write (JSON);

Save: Page Submission Form <form id= "Standardform" action= "${pagecontext.request.contextpath}/standardaction_save.action" method = "POST" >
Find the Save method that standardaction_save.action points to
Call the Save method with an auto-injected service
Standardservice.save (model);
In the implementation class of the service
@Service
@Transactional
public class Standardserviceimpl implements Standardservice {
Invoke automatic injection of DAO
@Autowired
Private Standarddao Standarddao;
The method
public void Save (Standard Model) {
Standarddao.save (model);
}
This save (model) method is not visible in the DAO interface, it is defined in the DAO inherited interface Crudrepository, and the addition is save, with no Add and update
Model from implementing the Modeldriven interface
Implements Modeldriven<t>
Below is the Baseaction parent class that is extracted upward
public class Baseaction<t> extends Actionsupport implements modeldriven<t> {

Protected T model;//here requires the new object, which is generated in the constructor method.
Public T Getmodel () {
return model;
}

The subclass action is created, the parent class is executed without a parameter, and the subclass inherits the generic class from the baseaction.
/*
* Parameterized Type type:baseaction<standard>--cn.itcast.bos.web.action.common.baseaction< Cn.itcast.bos.base.standard>
* Actual type parameter: "In" class called actual type parameter
* */
Public Baseaction () {
try {
First step: Get the currently running class-subclass
Class clzz = This.getclass ();
System.err.println (CLZZ);
Step two: Get the class--parameterized type of the child class inheriting the parent class
/*type getgenericsuperclass () Type: interface class is the type implementation class
Returns the type of the direct superclass that represents the entity (class, interface, base type, or void) represented by this class. */
Type type = Clzz.getgenericsuperclass ();
System.err.println (type);
Converts the type interface to a sub-interface Parameterizedtype
Parameterizedtype Parameterizedtype = (parameterizedtype) type;
Step three: Get the actual type parameter-model object class
type[] types = parameterizedtype.getactualtypearguments (); [Cn.itcast.bos.base.Standard]
SYSTEM.ERR.PRINTLN (types);
Convert type interface to implementation class
Class clzzzzzzzzzzzz = (Class) types[0];
Fourth step: Instantiate the class
Model = (T) clzzzzzzzzzzzz.newinstance ();
} catch (Exception e) {
E.printstacktrace ();
}
}

Gets the current page by property drive, showing the number of records per page
Page-1
protected Integer page;
protected Integer rows;
public void Setpage (Integer page) {
This.page = page-1;
}


public void Setrows (Integer rows) {
This.rows = rows;
}

/**
* @Description: JSON data is required to turn service query to page object to paging
* @param page
* @param excluds
*
*/
public void Java2json (page<t> Page, string[] excluds) {
try {
map<string, object> map = new hashmap<> ();
Map.put ("Total", page.gettotalelements ());
Map.put ("Rows", page.getcontent ());

Jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.setexcludes (Excluds);

String JSON = jsonobject.fromobject (map, Jsonconfig). toString ();
SYSTEM.ERR.PRINTLN (JSON);
Servletactioncontext.getresponse (). setContentType ("Text/json;charset=utf-8");
Servletactioncontext.getresponse (). Getwriter (). write (JSON);
} catch (Exception e) {
E.printstacktrace ();
}
}

/**
* @Description: Convert list collection to JSON array
*/
public void Java2json (List list, string[] excluds) {
try {
Jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.setexcludes (Excluds);
String json = jsonarray.fromobject (list, jsonconfig). toString ();
SYSTEM.ERR.PRINTLN (JSON);
Servletactioncontext.getresponse (). setContentType ("Text/json;charset=utf-8");
Servletactioncontext.getresponse (). Getwriter (). write (JSON);
} catch (Exception e) {
E.printstacktrace ();
}
}
}
About the No session problem
The bottom of the page to query the courier, if you do not handle the Courier Entity Foreign Key Association of the collection using lazy loading method to cause no session exception, that is
page<courier> page = courierservice.pagequery (model, pageable); The courier was queried after execution, but when the JSON was transferred,
The session is closed, lazy load collection No session can not load
Workaround One,
Jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.setexcludes (New string[]{"Fixedareas", "Company"});
Ignoring the Fixedareas collection is all you need.
Deny method Two,
You can also extend the session (Entitymanager in Spring data JPA) to the Web tier
The relevant code is as follows:
@Action ("Courieraction_pagequery")
Public String Pagequery () throws Exception {
pageable pageable = new Pagerequest (page, rows);
page<courier> page = courierservice.pagequery (model, pageable);
This.java2json (page, new string[]{"Fixedareas"});
/*map<string, object> Map = new hashmap<> ();
Map.put ("Total", page.gettotalelements ());
Map.put ("Rows", page.getcontent ());

Excludes the collection attribute Fixedareas in the Courier object (ignores the attribute, and eventually the Courier object does not exist)
Jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.setexcludes (New string[]{"Fixedareas", "Company"});

String JSON = jsonobject.fromobject (map, Jsonconfig). toString ();
SYSTEM.ERR.PRINTLN (JSON);
Servletactioncontext.getresponse (). setContentType ("Text/json;charset=utf-8");
Servletactioncontext.getresponse (). Getwriter (). write (JSON); */
return NONE;
}

Spring Data JPA Understanding (default query custom query paged query) and no session two methods of processing

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.