Build Springmvc+springdatajpa+hibernate_java from the most basic Java engineering

Source: Internet
Author: User
Tags aop

This article will introduce you from one of the most basic Java projects, to Web engineering, to integrated spring, SPRINGMVC, and Springdatajpa+hibernate.

Usually we can build a project from a template, or directly import a project, and this article chose to start with the most basic Java project, to show more principles.

Of course, we started with one of the most basic MAVEN projects, in fact, the common non-MAVEN project, the construction process is almost the same, but the jar package requires us to manually add to the project, and the MAVEN project is only to modify the configuration file.

The following is officially started.

1, based on MAVEN (if not using Maven can also use traditional engineering) to create the most basic Java engineering

New project, select Maven Project,next:

Check it out as a simple project (Create a Simplicity project), Next:

Group ID for your domain name reverse order, usually with the project source of the package name, artifact ID for this group ID in the project's unique name, according to your hobby, how to fill all the lines, and then finish:

This is the resulting engineering directory structure that is like this:

Pom.xml is the core document of Maven.

2, the project is set as a Dynamic Web page mode

Next, convert the project to Web engineering, right-click on the project properties, click Project Facets in the left menu, and click Convert to faceted from ... :

On the right, we tick Dynamic Web Module (animated web), and then click OK:

There will be an extra webcontent directory:

In the Web-inf directory, add the Web.xml file as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi=
"Http://www.w3.org/2001/XMLSchema-instance" "
 xmlns=" Http://java.sun.com/xml/ns/javaee "
xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "
 version=" 3.0 ">
 <display-name>SpringDataJPA< /display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>

Then add a welcome page index.html:

 
 

At this point the directory structure is as follows:

At this point, you can right-click the project, Run on server, you can see the effect:

3. Integrated SPRING+SPRINGMVC

Create a new package and add some interfaces and classes (which are listed later in the code), as shown in the package structure:

Need to add jar package, directly modify the Pom file, if for ordinary works, press Pom.xml jar package, add to the project can be.

First add the use of the spring version, facilitate unified management, and then add all the required jar packs, the following add all the jar packages needed here, after the completion of the Pom.xml is as follows:

&lt;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" &gt; &lt; Modelversion&gt;4.0.0&lt;/modelversion&gt; &lt;groupId&gt;com.anxpp&lt;/groupId&gt; &lt;artifactId&gt; Springdatajpa&lt;/artifactid&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;properties&gt; &lt;!-- Spring version number--&gt; &lt;spring.version&gt;4.2.5.RELEASE&lt;/spring.version&gt; &lt;/properties&gt; &lt;dependencies &gt; &lt;!--Spring Core package--&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifact Id&gt;spring-core&lt;/artifactid&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt; Dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactid&gt;spring-web&lt;/artifactid &gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version &gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupid&gt;org.springframework& Lt;/groupid&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; & lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactid&gt;spring
   -jdbc&lt;/artifactid&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt; version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt; Org.springframework&lt;/groupid&gt; &lt;artifactId&gt;spring-aop&lt;/artifactId&gt; &lt;version&gt;${ Spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactid&gt;spring-context-support&lt;/artifactid &gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupid&gt;org. Springframework&lt;/groupid&gt; &lt;artifactId&gt;spring-test&lt;/artifactId&gt; &lt;version&gt;${spring.version }&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;
  Artifactid&gt;spring-orm&lt;/artifactid&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt; /artifactid&gt; &lt;version&gt;1.10.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/ Project&gt;

    Add the Spring configuration file Applicationcontext.xml under the Web-inf directory and add the following:

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;beans "xmlns=" xmlns:
 Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:p= "http://www.springframework.org/schema/p" Xmlns:tx = "Http://www.springframework.org/schema/tx" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-4.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spRing-mvc-4.2.xsd "&gt; &lt;!--open IOC annotation scan--&gt; &lt;context:component-scan base-package=" Com.anxpp.demo "/&gt; &lt;!-- Open MVC annotation Scan--&gt; &lt;mvc:annotation-driven/&gt; &lt;/beans&gt;

  Modify Web.xml to add Spring in:

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 "&gt; &lt;display-name&gt;springdatajpa&lt;/display-name &gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.contextloaderlistener&lt;/ listener-class&gt; &lt;/listener&gt; &lt;context-param&gt; &lt;param-name&gt;contextconfiglocation&lt;/param-name
  &gt; &lt;param-value&gt;WEB-INF/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;springmvc&lt;/servlet-name&gt; &lt;servlet-class&gt; Org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt; Contextconfiglocation&lt;/param-name&gt; &lt;param-value&gt;classpath*:springmvc-servlet.xml&lt;/param-value &gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt; Springmvc&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt; welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app &gt;

Here's how to write the code, note don't forget to write, in the beginning of this section has given the package hierarchy.

Entity User:

Package com.anxpp.demo.core.entity;
public class User {
 private Integer ID;
 private String name;
 Public User (Integer ID, String name) {
  this.id = ID;
  this.name = name;
 Public Integer GetId () {return
  ID;
 }
 public void SetId (Integer id) {
  this.id = ID;
 }
 Public String GetName () {return
  name;
 }
 public void SetName (String name) {
  this.name = name;
 }
 @Override public
 String toString () {return
  "ID:" +id+ ", Name:" +name;
 }
}

DAO Layer Interface Userdao:

Package Com.anxpp.demo.core.dao;
Import Com.anxpp.demo.core.entity.User;
Public interface Userdao {
 User getuser (Integer id,string name);
}

DAO Layer Implementation Userdaoimpl:

Package Com.anxpp.demo.core.dao.impl;
Import org.springframework.stereotype.Repository;
Import Com.anxpp.demo.core.dao.UserDao;
Import Com.anxpp.demo.core.entity.User;
@Repository public
class Userdaoimpl implements userdao{
 @Override public
 User GetUser (Integer ID, String Name) {return
  new User (ID, name);
 }
}

Service Layer Interface UserService:

Package com.anxpp.demo.core.service;
Import Com.anxpp.demo.core.entity.User;
Public interface UserService {
 User getuser (Integer ID, String name);

Service Layer Implementation:

Package Com.anxpp.demo.core.service.impl;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import Com.anxpp.demo.core.dao.UserDao;
Import Com.anxpp.demo.core.entity.User;
Import Com.anxpp.demo.core.service.UserService;
@Service public
class Userserviceimpl implements userservice{
 @Autowired
 Userdao Userdao;
 @Override public
 User GetUser (Integer ID, String name) {return
  userdao.getuser (ID, name);
 }
}

Controller Layer Democontroller:

Package Com.anxpp.demo.controller;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.ResponseBody;
Import Com.anxpp.demo.core.service.UserService;
@Controller
@RequestMapping ("/") public
class Democontroller {
 @Autowired
 userservice userservice ;
 @RequestMapping ("/")
 @ResponseBody public
 String Index () {return
  ' index ';
 }
 @RequestMapping ("/getuser")
 @ResponseBody public
 String GetUser (Integer ID, String name) {
  return Userservice.getuser (ID, name). toString ();
 }

This is not going to run on Server directly, because the jar package will not be released together, we need to configure the following:

Right-click the project selection properties, according to the following figure configuration:

This is the time to run the test, the effect is as follows:

Here, we haven't manipulated the database yet.

4, add back JSON format data support

Now, we often use JSON as a format for data transfer, and the following is the support for SPRINGMVC to return JSON

First add the jar package:

 <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId> jackson-databind</artifactid>
   <version>2.5.0</version>
  </dependency>
  < dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId> jackson-core</artifactid>
   <version>2.5.0</version>
  </dependency>
  < dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId> jackson-annotations</artifactid>
   <version>2.5.0</version>
  </dependency>

Then rewrite the GetUser () method as follows:

@RequestMapping ("/getuser")
 @ResponseBody public
 map<string, object> getuser (Integer ID, String name) {
  map<string, object> Map = new hashmap<string, object> ();
  Map.put ("state", "success");
  Map.put ("Data", Userservice.getuser (ID, name));
  return map;
 }

After the rerun, the access effect is as follows:

At this point, you can return the JSON data.

5. Configure static resource access

Under normal circumstances, Web-inf directory resources, we are not directly accessible, if our site is composed of Html+ajax, then you can create a new HTML directory outside the Web-inf, and configure the default filter for Web.xml, but note that you want to put it before the SPINGMVC filter:

 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.html </url-pattern>
 </servlet-mapping>

If you are sure to access resources in the Web-inf directory, by looking through the spring official documentation, you find two ways

1, handwriting a resource mapper:

@Configuration
@EnableWebMvc Public
class Webconfig extends Webmvcconfigureradapter {
 @Override
 public void Addresourcehandlers (Resourcehandlerregistry registry) {
  Registry.addresourcehandler ("/resources/** ")
    . Addresourcelocations ("/public-resources/").
    Setcachecontrol (cachecontrol.maxage (1, timeunit.hours). Cachepublic ());
 }

As you can see, you can also set the caching time, and in a simpler way, the XML configuration:

<mvc:resources mapping= "/resources/**" location= "/public-resources/" >
 <mvc:cache-control max-age= " 3600 "cache-public=" true "/>
</mvc:resources>

You can also add the following:

<!--access to static resource files, leave the path that cannot be mapping to controller to the default servlet handler processing-->

6, garbled solution

We usually submit requests using AJAX, but we also use the address bar for direct testing. Request to submit the split get and post.

The use of Post submission request is, generally will not appear in Chinese garbled, but if it does appear garbled, you can add a code filter in Web.xml to solve:

<filter>
  <filter-name>CharacterEncoding</filter-name>
  <filter-class> org.springframework.web.filter.characterencodingfilter</filter-class>
  <init-param>
   < param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param >
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value> true</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  < filter-name>characterencoding</filter-name>
  <url-pattern>/*</url-pattern>
 </ Filter-mapping>

The above can only solve the post of Chinese garbled, for get (including the browser address bar direct submission method), we need to modify the Tomcat configuration, in the Conf directory in the Server.xml found and the following modifications:

 <connector connectiontimeout= "20000" port= "8080" protocol= "http/1.1" redirectport= "8443" URIEncoding= "UTF-8"/ >

If we are just testing, the project is not deployed, you can find server.xml directly under the server in Eclipse and make the same changes as above:

7. Integrate Springdatajpa+hibernate

You can use this text to understand JPA:JPA specification Introduction and example (Java Data Persistence solution)

SPRINGDATAJPA is also a lightweight solution, and the preferred hibernate implements JPA.

First, the jar package, the SPRINGDATAJPA jar package, was added to the previous integration of spring, and the following is the hibernate (and MySQL-driven) jar package.

 &lt;!--hibernate--&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactid&gt;hiber Nate-core&lt;/artifactid&gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt; Dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactid&gt;hibernate-ehcache&lt;/artifactid &gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupid&gt;o Rg.hibernate&lt;/groupid&gt; &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;${ hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupid&gt;org.hibernate&lt;/ Groupid&gt; &lt;artifactId&gt;hibernate-c3p0&lt;/artifactId&gt; &lt;version&gt;${hibernate.version}&lt;/version &gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactid&gt;mysql-connect Or-java&lt;/artifactid&gt; &lt;version&gt;5.1.9&lt;/version&gt; &lt;/dependency&gt; 

The unified management version is:

 <!--hibernate version number-->
  
 

Add JPA configuration file Persistence.xml to Meta-inf directory, this article describes the database using MySQL. and add the following:

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;persistence version= "1.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_1_0.xsd "&gt; &lt;persistence-unit name=" Demo " Transaction-type= "Resource_local" &gt; &lt;!--provider&gt;org.eclipse.persistence.jpa.persistenceprovider&lt;/ Provider--&gt; &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt; &lt;class&gt; com.ninelephas.meerkat.pojo.user&lt;/class&gt; &lt;!--MYSql connection--&gt; &lt;properties&gt; &lt;property name= "Hiber Nate.connection.driver_class "value=" Com.mysql.jdbc.Driver "/&gt; &lt;property name=" Hibernate.connection.url " Value= "Jdbc:mysql://127.0.0.1:3306/demo?createdatabaseifnotexist=true"/&gt; &lt;property name= " Hibernate.connection.username "value=" root "/&gt; &lt;property name=" Hibernate.connection.password "value="Root "/&gt; &lt;property name=" Hibernate.dialect "value=" Org.hibernate.dialect.MySQLDialect "/&gt; &LT;/PROPERTIES&G
 T &lt;/persistence-unit&gt; &lt;/persistence&gt;

  Spring Profile Applicationcontext.xml Add the full content of JPA support:

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;beans "xmlns=" xmlns:
 Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:p= "http://www.springframework.org/schema/p" Xmlns:tx = "Http://www.springframework.org/schema/tx" xmlns:mvc= "Http://www.springframework.org/schema/mvc" 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.2.xsd Http://www.springframework.org/schema/context
   Http://www.springframework.org/schema/context/spring-context-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX Http://www.springframework.org/schema/tx/spring-tx-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http:// Www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/ DATA/JPA http://www.springframework.org/schema/data/jpa/spring-jpa.xsd "&gt; &lt;!--open IOC annotation scan--&gt; &lt;context:co Mponent-scan base-package= "Com.anxpp.demo"/&gt; &lt;bean id= "Entitymanagerfactory"
   Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean "&gt; &lt;property name=" Jpavendoradapter "&gt; &lt;bean class= "Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" &gt; &lt;property name= "Generateddl" Value= "true"/&gt; &lt;property name= "database" value= "MYSQL"/&gt; &lt;/bean&gt; &lt;/property&gt; &lt;propert
 Y name= "Persistenceunitname" value= "demo"/&gt; &lt;/bean&gt; &lt;!--open MVC annotation scan--&gt; &lt;mvc:annotation-driven/&gt; &lt;bean class= "Org.springframework.web.servlet.view.ContentNegotiatingViewResolver" &gt; &lt;property name= " Viewresolvers "&gt; &lt;list&gt; &lt;bean class=" Org.springframEwork.web.servlet.view.InternalResourceViewResolver "&gt; &lt;property name=" prefix "value="/web-inf/view/"/&gt;" &lt;property name= "suffix" value= ". html"/&gt; &lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;!--used to convert objects to JSON--&gt; &lt;property name= "Defaultviews" &gt; &lt;list&gt; &lt;bean class= "Org.springframework.web.servle T.view.json.mappingjackson2jsonview "/&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!--access to static resource files will not be Mapp ing to Controller's path to the default servlet handler processing--&gt; &lt;mvc:default-servlet-handler/&gt; &lt;!--configuration transaction manager--&gt; &lt; Bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionManager" &gt; &lt;property name= " Entitymanagerfactory "ref=" entitymanagerfactory/&gt; &lt;/bean&gt; &lt;!--enable annotation transactions--&gt; Driven transaction-manager= "TransactionManager"/&gt; &lt;!--Configure the spring Data JPA Scan directory--&gt; &lt;jpa:repositories Ckage= "Com.anxpp.demo"/&gt; &lt;/beAns&gt; 

To modify an entity:

Package com.anxpp.demo.core.entity;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.GenerationType;
Import Javax.persistence.Id;
Import javax.persistence.Table;
@Entity
@Table Public
class User {
 @Id
 @GeneratedValue (strategy = Generationtype.auto)
 Private Integer ID;
 private String name;
 Public user () {
 } public
 User (String name) {
  this.name = name;
 }
 Public Integer GetId () {return
  ID;
 }
 public void SetId (Integer id) {
  this.id = ID;
 }
 Public String GetName () {return
  name;
 }
 public void SetName (String name) {
  this.name = name;
 }
 @Override public
 String toString () {return
  "ID:" +id+ ", Name:" +name;
 }
}

You can erase the DAO layer implementation, and we remember to inherit the DAO layer interface from the powerful jparepository:

Public interface Userdao extends Jparepository<user, serializable>{
 User FindByID (Integer ID);

Does it look particularly concise, and does not need to write implementation, SPRINGDATAJPA will automatically help us complete.

To modify the service layer interface:

Package com.anxpp.demo.core.service;
Import java.util.List;
Import Com.anxpp.demo.core.entity.User;
Public interface UserService {
 User FindByID (Integer ID);
 User Save (String name);
 List<user> findall ();
}

To modify the service layer implementation:

Package Com.anxpp.demo.core.service.impl;
Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import Com.anxpp.demo.core.dao.UserDao;
Import Com.anxpp.demo.core.entity.User;
Import Com.anxpp.demo.core.service.UserService;
@Service public
class Userserviceimpl implements userservice{
 @Autowired
 Userdao Userdao;
 @Override public
 User FindByID (Integer ID) {return
  Userdao.findbyid (ID);
 }
 @Override public
 User Save (String name) {return
  userdao.save (new User (name));
 @Override public
 list<user> FindAll () {return
  userdao.findall ();
 }
}

Modify controller to provide multiple test interfaces:

Package Com.anxpp.demo.controller;
Import Java.util.HashMap;
Import Java.util.Map;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.ResponseBody;
Import Com.anxpp.demo.core.service.UserService;
 @Controller @RequestMapping ("/") public class Democontroller {@Autowired userservice userservice;
 @RequestMapping ("/") @ResponseBody Public String Index () {return ' index ';
 @RequestMapping ("/info") public String info () {return "info";  @RequestMapping ("/findall") @ResponseBody public map&lt;string, object&gt; GetUser () {map&lt;string, object&gt; Map
  = new hashmap&lt;string, object&gt; ();
  Map.put ("state", "success");
  Map.put ("Data", Userservice.findall ());
 return map; @RequestMapping ("/findbyid") @ResponseBody public map&lt;string, object&gt; FindByID (Integer id) {map&lt;string, Ob Ject&gt;Map = new hashmap&lt;string, object&gt; ();
  Map.put ("state", "success");
  Map.put ("Data", Userservice.findbyid (ID));
 return map;  @RequestMapping ("/add") @ResponseBody public map&lt;string, object&gt; Save (String name) {map&lt;string, object&gt;
  Map = new hashmap&lt;string, object&gt; ();
  Map.put ("state", "success");
  Map.put ("Data", Userservice.save (name));
 return map; }
}

Operation Effect:

So, what if you need to add a lookup with a specified last name that is greater than the specified value?

If it's SQL, we'll write it like this (?) Represents a parameter):

SELECT * from user WHERE id>? and name like '?% ';

But here, we don't have to write SQL (or HQL), just add a method directly to the DAO layer interface:

 List<user> findbyidgreaterthanandnamelike (Integer id,string name);

You do not need to doubt that the above method of execution is to be successful (note: The use of service implementation, call the method remember name+ "%")!

The above is a small set to introduce the most basic Java project to build springmvc+springdatajpa+hibernate related knowledge, hope to help everyone, if you want to learn more information please pay attention to cloud Habitat community website!

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.