Maven Project Build spring boot + spring mvc + JPA example, mavenmvc

Source: Internet
Author: User

Maven Project Build spring boot + spring mvc + JPA example, mavenmvc

This article describes how to build spring boot + spring mvc + JPA by using Maven:

Add Spring boot support and introduce related packages:

1. For maven projects, see the official website for introduction of pom. xml and spring boot:

<Parent> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-parent </artifactId> <version> 1.5.9.RELEASE </version> </parent> <dependencies> <dependency> <groupId> javax. servlet </groupId> <artifactId> javax. servlet-api </artifactId> <scope> provided </scope> <! -- Compile a jar package that is not required and release it --> </dependency> <groupId> org. springframework </groupId> <artifactId> spring-webmvc </artifactId> </dependency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-web </artifactId> </dependency> <! -- Jpa jar package, database operations --> <dependency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-data-jpa </artifactId> </dependency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-data-redis </artifactId> </dependency> <! -- Mysql driver --> <dependency> <groupId> mysql </groupId> <artifactId> mysql-connector-java </artifactId> </dependency> <groupId> org. apache. shiro </groupId> <artifactId> shiro-core </artifactId> <version> 1.2.2 </version> </dependency> <groupId> org. apache. shiro </groupId> <artifactId> shiro-spring </artifactId> <version> 1.2.2 </version> </dependency> <! -- Shiro ehcache --> <dependency> <groupId> org. apache. shiro </groupId> <artifactId> shiro-ehcache </artifactId> <version> 1.2.2 </version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-maven-plugin </artifactId> <executions> <execution> <goals> <goal> repackage </goal> </goals> </execution> </executions> </plugin> </plugins> <finalName> name </finalName> </build>

2. The above Code introduces spring boot. Spring mvc, jpa, and mysql database driver jar;

Compile the startup class and install the configuration file:

1. the startup class is as follows:

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.data.jpa.repository.config.EnableJpaAuditing;import java.io.IOException;import com.my.config.CommonProperties;@SpringBootApplication@EnableAutoConfiguration@EnableJpaAuditingpublic class Application { public static void main(String[] args) throws IOException{  String loc = CommonProperties.loadProperties2System(System.getProperty("spring.config.location")); System.getProperties().setProperty("application.version", CommonProperties.getVersion(Application.class)); System.getProperties().setProperty("app.home", loc + "/.."); SpringApplication.run(Application.class, args);  } }

2. Place the configuration file outside the classpath to facilitate modification without repackaging. The spring boot project is usually packaged into a jar package:

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;import org.springframework.util.StringUtils;public final class CommonProperties {  public static final String PPT_KEY_APP_HOME = "app.home"; public static final String DEFAULT_APP_HOME = "./"; public static final String getAppHome() { return System.getProperty("./", "./"); } public static String loadProperties2System(String location) throws IOException { String configLocation = location; File cnf; if (!StringUtils.hasLength(location)) { configLocation = "./config"; cnf = new File(configLocation); if (!cnf.exists() || !cnf.isDirectory()) { configLocation = "../config"; cnf = new File(configLocation); } } else { cnf = new File(location); } File[] arg2 = cnf.listFiles(); int arg3 = arg2.length; for (int arg4 = 0; arg4 < arg3; ++arg4) { File file = arg2[arg4]; if (file.isFile() && file.getName().endsWith(".properties")) { Properties ppt = new Properties(); FileInputStream fi = new FileInputStream(file); Throwable arg8 = null; try {  ppt.load(fi);  System.getProperties().putAll(ppt); } catch (Throwable arg17) {  arg8 = arg17;  throw arg17; } finally {  if (fi != null) {  if (arg8 != null) {  try {  fi.close();  } catch (Throwable arg16) {  arg8.addSuppressed(arg16);  }  } else {  fi.close();  }  } } } } return configLocation; } public static String getVersion(Class<?> clazz) { Package pkg = clazz.getPackage(); String ver = pkg != null ? pkg.getImplementationVersion() : "undefined"; return ver == null ? "undefined" : ver; }

Place the configuration file in the config folder of the same directory of the jar package, including the log configuration, application. yml file, and other configuration files;

Compile automatic configuration class

Used to scan compan * instead of spring mvc's spring. xml configuration file:

Import org. springframework. context. annotation. componentScan; import org. springframework. context. annotation. configuration; @ Configuration @ ComponentScan (basePackages = {"com. my. rs "," com. my. service "," com. my. repository "}) public class AppAutoConfiguration {} import org. springframework. boot. autoconfigure. web. httpMessageConverters; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. configuration; import org. springframework. web. servlet. config. annotation. resourceHandlerRegistry; import org. springframework. web. servlet. config. annotation. webMvcConfigurerAdapter;/***** pre-configuration **/@ Configurationpublic class MyConfiguration extends WebMvcConfigurerAdapter {@ Bean public HttpMessageConverters customConverters () {return new HttpMessageConverters ();} @ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {// registry. addResourceHandler ("/**")//. addResourceLocations ("classpath:/META-INF/resources /**");}

Write rs, service, and repository

Package com. my. rs; import java. util. list; import org. springframework. web. bind. annotation. requestBody; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestMethod; import org. springframework. web. bind. annotation. requestParam; import org. springframework. web. bind. annotation. responseBody; import com. my. entity. user; @ RequestMapping ({"/api/user"}) public interface UserRS {@ RequestMapping (value = "/add", method = {RequestMethod. POST}) @ ResponseBody public User saveUser (@ RequestBody User user); @ RequestMapping (value = "/update", method = {RequestMethod. POST}) @ ResponseBody public User updateUser (@ RequestBody User user); @ RequestMapping (value = "/delete", method = {RequestMethod. POST, RequestMethod. DELETE}) public void deleteUser (@ RequestParam String [] userIds); @ RequestMapping (value = "/get", method = {RequestMethod. GET}) @ ResponseBody public User getUser (@ RequestParam String userId); @ RequestMapping (value = "/query/all", method = {RequestMethod. GET}) public List <User> queryAll (); @ RequestMapping (value = "/query/byName", method = {RequestMethod. GET}) public List <User> queryByName (@ RequestParam String name); @ RequestMapping (value = "/query/byParentId", method = {RequestMethod. GET}) public List <User> queryChildren (@ RequestParam String parentId); // No parameter paging query @ RequestMapping (value = "/query/page", method = {RequestMethod. GET}) public List <User> queryByPage (@ RequestParam int pageNo, @ RequestParam int pageSize, @ RequestBody (required = false) User user );}
package com.my.rs.impl;import java.util.List;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import com.my.entity.User;import com.my.rs.UserRS;import com.my.service.UserService;@RestControllerpublic class UserRSImpl implements UserRS{ public static Logger logger = LoggerFactory.getLogger(UserRSImpl.class);  @Autowired UserService _userService;  @Override public User saveUser(@RequestBody User user){ try { return _userService.save(user); } catch (Throwable e) { logger.error(e.getMessage(),e); throw e; } } @Override public User updateUser(@RequestBody User user) { return _userService.update(user); } @Override public void deleteUser(String[] userIds) { for (String userId : userIds) { _userService.deleteById(userId); } } @Override public List<User> queryAll() { return _userService.queryAll(); } @Override public List<User> queryByName(String name) { return _userService.findByName(name); } @Override public List<User> queryChildren(String parentId) { return _userService.findByParentId(parentId); } @Override public User getUser(String userId) { return _userService.findById(userId); } @Override public List<User> queryByPage(int pageNo, int pageSize, User user) {  return null; } }
package com.my.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.my.entity.User;import com.my.repository.UserRepository;@Servicepublic class UserService extends BaseService<User>{ @Autowired UserRepository _userRepository; public List<User> findByName(String name){ return _userRepository.findByName(name); }  public List<User> findByParentId(String parentId){ return _userRepository.findByParentId(parentId); } }
package com.my.repository;import java.util.List;import com.my.entity.User;public interface UserRepository extends BaseRepository<User>{  List<User> findByName(String name); List<User> findByParentId(String parentId);}

The above uses the layered mode, which is a bit cumbersome, but it is more convenient to modify the business logic of each layer later.

JPA-related classes are as follows:

Package com. my. service; import java. io. serializable; import javax. persistence. entityManager; import javax. transaction. transactional; import org. springframework. beans. factory. annotation. autowired; import com. my. repository. baseRepository;/*** common methods are shown here **/@ Transactionalpublic class BaseService <E extends Serializable >{@ Autowired BaseRepository <E> _ baseRepository; @ Autowired EntityManager em; public E save (E baseUnit) {return _ baseRepository. saveAndFlush (baseUnit);} public E update (E baseUnit) {return _ baseRepository. saveAndFlush (baseUnit);} public void deleteById (String id) {_ baseRepository. delete (id);} public java. util. list <E> queryAll () {return _ baseRepository. findAll ();} public E findById (String id) {return _ baseRepository. getOne (id );}}
package com.my.repository;import java.io.Serializable;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.repository.NoRepositoryBean;@NoRepositoryBeanpublic interface BaseRepository<E> extends JpaRepository<E, Serializable>{}

Entity class: Related to database fields. Note the annotation @ MappedSuperclass in the parent class.

Package com. my. entity; import java. util. arrayList; import java. util. list; import javax. persistence. entity; import javax. persistence. manyToMany; import org. hibernate. annotations. dynamicInsert; import org. hibernate. annotations. dynamicUpdate; import org. hibernate. validator. constraints. email; @ Entity (name = "db_user") @ DynamicInsert @ DynamicUpdatepublic class User extends BaseUnit {/*** account status */public static e Num AccountStatus {/*** normal */Enable, // *** Disable */Disable} private static final long serialVersionUID =-31013196191_641_l; private String password; private String salt; /** account status */private AccountStatus status;/** authenticated Email address */@ Email (message = "User. the email attribute must comply with the email format ") private String email;/** mobile phone number */private String mobileNo;/** ID card number */private String cardId; @ manytoty (targetEntity = Role. Class) private List <String> roleIds;/** nickname. Optional. */Private String nickName; public String getCardId () {return cardId;} public String getEmail () {return email;} public String getMobileNo () {return mobileNo ;} public String getNickName () {return nickName;} public String getPassword () {return password;} public List <String> getRoleIds () {if (roleIds = null) {roleIds = new ArrayList <> () ;}return roleIds;} public String getSalt () {return salt;} public AccountStatus getStatus () {return status ;} public void setCardId (String cardId) {this. cardId = cardId;} public void setEmail (String email) {this. email = email;} public void setinclueno (String inclueno) {this. required Eno = required Eno;} public void setNickName (String nickName) {this. nickName = nickName;} public void setPassword (String password) {this. password = password;} public void setRoleIds (List <String> roleIds) {this. roleIds = roleIds;} public void setSalt (String salt) {this. salt = salt;} public void setStatus (AccountStatus status) {this. status = status ;}}
Package com. my. entity; import java. io. serializable; import java. util. date; import javax. persistence. id; import javax. persistence. mappedSuperclass; import javax. validation. constraints. notNull; import javax. validation. constraints. size; import org. springframework. data. annotation. createdBy; import org. springframework. data. annotation. createdDate; import org. springframework. data. annotation. lastModifiedBy; import org. springframework. data. annotation. lastModifiedDate; @ MappedSuperclasspublic class BaseUnit implements Serializable {@ Id @ NotNull public String id;/*** parent unit ID */@ Size (max = 32, message = "BaseUnit. the length of the parentId attribute cannot be greater than 32 ") public String parentId;/** parent unit type */public ParentType parentType; /*** unit name */@ NotNull (message = "BaseUnit. name attribute cannot be blank ") public String name; @ CreatedBy public String createBy; @ CreatedDate public Date createDate; @ LastModifiedBy public String lastModifiedBy; /*** last update Date */@ LastModifiedDate public Date lastModifiedDate; public String getId () {return id;} public void setId (String id) {this. id = id;}/*** obtain the unit name ** @ return required */public String getName () {return name ;} /***** @ return UUID, excluding {} and-*/public String getParentId () {return parentId;} public ParentType getParentType () {return parentType ;} public String getStationId () {return stationId;} public String getThumbnailId () {return thumbnailId;} public String getCreateBy () {return createBy;} public void setCreateBy (String createBy) {this. createBy = createBy;} public Date getCreateDate () {return createDate;} public void setCreateDate (Date createDate) {this. createDate = createDate;}/*** set the unit name ** @ param name * required */public void setName (String name) {this. name = name;}/*** set parent unit ID ** @ param parentId * UUID, excluding {} and-*/public void setParentId (String parentId) {this. parentId = parentId;} public String getLastModifiedBy () {return lastModifiedBy;} public void setLastModifiedBy (String lastModifiedBy) {this. lastModifiedBy = lastModifiedBy;} public Date getLastModifiedDate () {return lastModifiedDate;} public void setLastModifiedDate (Date lastModifiedDate) {this. lastModifiedDate = lastModifiedDate ;}}

Configuration file:

server: port: 16800 contextPath: / logging: config: ./config/logback.xml spring: http: multipart:  enabled: false datasource:  url : jdbc:mysql://127.0.0.1:3306/db?useUnicode=true&characterEncoding=utf-8  username : root  password : 123456  driverClassName : com.mysql.jdbc.Driver  jpa:  database : MYSQL  show-sql : true  hibernate:   ddl-auto : update jackson: serialization:  INDENT_OUTPUT : true
# Hibernate: configures the specific behavior of the object class to maintain the database table structure. update indicates that when the attributes of the object class change, the table structure is updated. Here we can also set the value to create, this create statement deletes the last generated table at startup and regenerates the table based on the object class. Data in the previous table will be cleared. You can also set this parameter to create-drop, this indicates that the table is generated based on the object class at startup, but the table will be deleted when sessionFactory is closed; validate indicates that the entity class and the data table are consistent at startup; none indicates that nothing is done. # Show-SQL indicates that hibernate prints real SQL statements on the console during operations # jackson indicates formatting the output json string

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.