本文介绍了Maven工程搭建spring boot+spring mvc+JPA的示例,分享给大家,具体如下:
添加Spring boot支持,引入相关包:
1、maven工程,少不了pom.xml,spring boot的引入可参考官网:
org.springframework.boot spring-boot-starter-parent1.5.9.RELEASE javax.servlet javax.servlet-apiprovided org.springframework spring-webmvcorg.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-data-jpaorg.springframework.boot spring-boot-starter-data-redismysql mysql-connector-javaorg.apache.shiro shiro-core1.2.2 org.apache.shiro shiro-spring1.2.2 org.apache.shiro shiro-ehcache1.2.2 org.springframework.boot spring-boot-maven-pluginrepackage name
2、以上代码引入了spring boot。spring mvc 和jpa,以及mysql数据库的驱动jar;
编写启动类,并加装配置文件:
1、启动类如下:
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、配置文件的位置放到classpath外边,方便在不重新打包的情况下修改,spring boot工程一般都打成jar包:
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;
}
将配置文件放到jar包同级目录的config文件夹下,包括日志配置,application.yml文件,其他配置文件等;
编写自动配置类
用于扫描compan* ,代替spring mvc的spring.xml配置文件:
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;
@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter{
@Bean
public HttpMessageConverters customConverters() {
return new HttpMessageConverters();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("
@Transactional
public class baseService {
@Autowired
baseRepository _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 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 baseRepositoryextends JpaRepository { }
实体类:与数据库字段相关,需要注意下父类中的注解@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
@DynamicUpdate
public class User extends baseUnit {
public static enum AccountStatus {
Enable, //
Disable
}
private static final long serialVersionUID = -3101319619397064425L;
private String password;
private String salt;
private AccountStatus status;
@Email(message = "User.email属性必须符合邮箱格式")
private String email;
private String mobileNo;
private String cardId;
@ManyToMany(targetEntity=Role.class)
private List roleIds;
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 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 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;
@MappedSuperclass
public class baseUnit implements Serializable {
@Id
@NotNull
public String id;
@Size(max = 32, message = "baseUnit.parentId属性长度不能大于32")
public String parentId;
public ParentType parentType;
@NotNull(message = "baseUnit.name属性不能为空")
public String name;
@CreatedBy
public String createBy;
@CreatedDate
public Date createDate;
@LastModifiedBy
public String lastModifiedBy;
@LastModifiedDate
public Date lastModifiedDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
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;
}
public void setName(String name) {
this.name = name;
}
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;
}
}
配置文件:
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:配置了实体类维护数据库表结构的具体行为,update表示当实体类的属性发生变化时,表结构跟着更新, 这里我们也可以取值create,这个create表示启动的时候删除上一次生成的表,并根据实体类重新生成表, 这个时候之前表中的数据就会被清空;还可以取值create-drop,这个表示启动时根据实体类生成表,但是当sessionFactory关闭的时候表会被删除; validate表示启动时验证实体类和数据表是否一致;none表示啥都不做。 #show-sql表示hibernate在操作的时候在控制台打印真实的sql语句 #jackson表示格式化输出的json字符串
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



