This article introduces an example of building spring boot+spring mvc+JPA for Maven project. It is shared with you. The details are as follows:
Add Spring boot support and introduce related packages:
1. The maven project is indispensable for pom.xml. For the introduction of 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><!-- Compile and publish unwanted jar packages--> </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 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 driver--> <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> <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 and jpa, as well as driver jar for mysql database;
Write a 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. Spring boot projects are generally made into jar packages:
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 jar package's directory at the same level, including log configuration, application.yml file, other configuration files, etc.;
Write automatic configuration classes
Used to scan company*, 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;/** * Preconfiguration* */@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, 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 pagination 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 adopts a layered model, 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;/** * Some common methods are put 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, you need to pay attention to the annotation in the parent class @MappedSuperclass
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 enum AccountStatus { /** * Normal*/ Enable, // /** * Disable */ Disable } private static final long serialVersionUID = -3101319619397064425L; private String password; private String salt; /** Account status*/ private AccountStatus status; /** Authentication email*/ @Email(message = "User.email attribute must comply with the email format") private String email; /** Mobile phone number*/ private String mobileNo; /** ID number*/ private String cardId; @ManyToMany(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 setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } 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.parentId attribute length cannot be greater than 32") public String parentId; /** Type of parent unit*/ public ParentType parentType; /** * Unit name*/ @NotNull(message = "BaseUnit.name attribute cannot be empty") public String name; @CreatedBy public String createBy; @CreatedDate public Date createDate; @LastModifiedBy public String lastModifiedBy; /** * Last updated date*/ @LastModifiedDate public Date lastModifiedDate; public String getId() { return id; } public void setId(String id) { this.id = id; } /** * Get the name of the unit* * @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 name of the unit* * @param name * Required */ public void setName(String name) { this.name = name; } /** * Set the 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: The specific behavior of the entity class maintaining the database table structure. Update means that when the properties of the entity class change, the table structure will be updated. Here we can also take the value create. This create means that the last generated table was deleted at startup and regenerate the table according to the entity class. At this time, the data in the previous table will be cleared; it can also take the value create-drop, which means that the table is generated based on the entity class at startup, but when the sessionFactory is closed, the table will be deleted; validate means that the entity class and the data table are consistent at startup; none means that nothing is done. #show-sql means hibernate prints real sql statement on the console when operating #jackson means formatted output json string
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.