Example of Maven boot+spring mvc+JPA project construction

  • 2021-01-02 21:52:54
  • OfStack

This paper introduces an example of Maven boot+spring mvc+JPA for Maven project construction, which is shared as follows:

Add Spring boot support and introduce related packages:

1. maven project is indispensable for the introduction of pom.xml and spring boot, please refer to the official website:


 <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><!--  What is required for compilation and not required for publication jar package  --> 
 </dependency> 
 
 <dependency> 
 <groupId>org.springframework</groupId> 
 <artifactId>spring-webmvc</artifactId> 
 </dependency> 
 
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <!--jpa the jar package   , operating the database -->
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>
 
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
 
 <!--mysql drive -->
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 </dependency>
 <dependency> 
 <groupId>org.apache.shiro</groupId> 
 <artifactId>shiro-core</artifactId> 
 <version>1.2.2</version> 
 </dependency> 
 <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. spring boot was introduced into the above code. spring mvc and jpa, and mysql database driver jar;

Write the startup class and add the configuration file:

1. Startup classes are 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
@EnableJpaAuditing
public 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 OF classpath for modification without repackaging. spring boot project 1 is generally packaged as 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 configuration files into the config folder in the same directory as the jar package, including log configuration, ES44en.yml files, other configuration files, etc.

Write the automatic configuration class

spring. xml configuration file for scanning compan* instead of spring mvc:


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-configured 
 * */
@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter{

 @Bean
 public HttpMessageConverters customConverters() {
 return new HttpMessageConverters();
 }

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
 //registry.addResourceHandler("/**")
 // .addResourceLocations("classpath:/META-INF/resources/**");
 }

The writing rs service 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);
 // Paging queries without parameters 
 @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;

@RestController
public 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;

@Service
public 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 layer mode is adopted, which is a little tedious, but it is more convenient to modify the business logic of each layer later

The 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;


/**
 * 1 So let's put some common methods here 
 * */
@Transactional
public 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;
@NoRepositoryBean
public interface BaseRepository<E> extends JpaRepository<E, Serializable>{
}

Entity class: Related to database fields, note the @MappedSuperclass annotation in the parent class


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
@EnableJpaAuditing
public 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); 
 } 
}
0

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
@EnableJpaAuditing
public 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); 
 } 
}
1

Configuration file:


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
@EnableJpaAuditing
public 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

 #hibernate: Configure the specific behavior of entity classes to maintain the database table structure, update Indicates that the table structure is updated when the attributes of the entity class change, 
 We could also evaluate it here create the create Delete on startup 1 The table is subgenerated, and the table is rebuilt according to the entity class, 
 At this point the data in the table will be cleared; You can also take the value create-drop , this means the table is generated based on the entity class at startup, but when sessionFactory Tables are deleted when closed; 
validate Indicates whether the entity class and data table are validated at startup 1 Cause; none It means to do nothing.  
#show-sql said hibernate Print the real one in the console at the time of operation sql statements  
#jackson Represents formatted output json string 

Related articles: