Maven工程搭建spring boot+spring mvc+JPA的示例
本文介绍了Maven工程搭建springboot+springmvc+JPA的示例,分享给大家,具体如下:
添加Springboot支持,引入相关包:
1、maven工程,少不了pom.xml,springboot的引入可参考官网:
org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE javax.servlet javax.servlet-api provided org.springframework spring-webmvc org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-data-redis mysql mysql-connector-java org.apache.shiro shiro-core 1.2.2 org.apache.shiro shiro-spring 1.2.2 org.apache.shiro shiro-ehcache 1.2.2 org.springframework.boot spring-boot-maven-plugin repackage name
2、以上代码引入了springboot。springmvc和jpa,以及mysql数据库的驱动jar;
编写启动类,并加装配置文件:
1、启动类如下:
importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.EnableAutoConfiguration; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.data.jpa.repository.config.EnableJpaAuditing; importjava.io.IOException; importcom.my.config.CommonProperties; @SpringBootApplication @EnableAutoConfiguration @EnableJpaAuditing publicclassApplication{ publicstaticvoidmain(String[]args)throwsIOException{ Stringloc=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外边,方便在不重新打包的情况下修改,springboot工程一般都打成jar包:
importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.util.Properties; importorg.springframework.util.StringUtils; publicfinalclassCommonProperties{ publicstaticfinalStringPPT_KEY_APP_HOME="app.home"; publicstaticfinalStringDEFAULT_APP_HOME="./"; publicstaticfinalStringgetAppHome(){ returnSystem.getProperty("./","./"); } publicstaticStringloadProperties2System(Stringlocation)throwsIOException{ StringconfigLocation=location; Filecnf; if(!StringUtils.hasLength(location)){ configLocation="./config"; cnf=newFile(configLocation); if(!cnf.exists()||!cnf.isDirectory()){ configLocation="../config"; cnf=newFile(configLocation); } }else{ cnf=newFile(location); } File[]arg2=cnf.listFiles(); intarg3=arg2.length; for(intarg4=0;arg4clazz){ Packagepkg=clazz.getPackage(); Stringver=pkg!=null?pkg.getImplementationVersion():"undefined"; returnver==null?"undefined":ver; }
将配置文件放到jar包同级目录的config文件夹下,包括日志配置,application.yml文件,其他配置文件等;
编写自动配置类
用于扫描compan*,代替springmvc的spring.xml配置文件:
importorg.springframework.context.annotation.ComponentScan; importorg.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages={ "com.my.rs", "com.my.service", "com.my.repository"}) publicclassAppAutoConfiguration{ } importorg.springframework.boot.autoconfigure.web.HttpMessageConverters; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** *预配置 **/ @Configuration publicclassMyConfigurationextendsWebMvcConfigurerAdapter{ @Bean publicHttpMessageConverterscustomConverters(){ returnnewHttpMessageConverters(); } @Override publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){ //registry.addResourceHandler("/**") //.addResourceLocations("classpath:/META-INF/resources/**"); }
编写rs,service,repository
packagecom.my.rs; importjava.util.List; importorg.springframework.web.bind.annotation.RequestBody; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.ResponseBody; importcom.my.entity.User; @RequestMapping({"/api/user"}) publicinterfaceUserRS{ @RequestMapping(value="/add",method={RequestMethod.POST}) @ResponseBody publicUsersaveUser(@RequestBodyUseruser); @RequestMapping(value="/update",method={RequestMethod.POST}) @ResponseBody publicUserupdateUser(@RequestBodyUseruser); @RequestMapping(value="/delete",method={RequestMethod.POST,RequestMethod.DELETE}) publicvoiddeleteUser(@RequestParamString[]userIds); @RequestMapping(value="/get",method={RequestMethod.GET}) @ResponseBody publicUsergetUser(@RequestParamStringuserId); @RequestMapping(value="/query/all",method={RequestMethod.GET}) publicListqueryAll(); @RequestMapping(value="/query/byName",method={RequestMethod.GET}) publicList queryByName(@RequestParamStringname); @RequestMapping(value="/query/byParentId",method={RequestMethod.GET}) publicList queryChildren(@RequestParamStringparentId); //无参数分页查询 @RequestMapping(value="/query/page",method={RequestMethod.GET}) publicList queryByPage(@RequestParamintpageNo, @RequestParamintpageSize, @RequestBody(required=false)Useruser); }
packagecom.my.rs.impl; importjava.util.List; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.RequestBody; importorg.springframework.web.bind.annotation.RestController; importcom.my.entity.User; importcom.my.rs.UserRS; importcom.my.service.UserService; @RestController publicclassUserRSImplimplementsUserRS{ publicstaticLoggerlogger=LoggerFactory.getLogger(UserRSImpl.class); @Autowired UserService_userService; @Override publicUsersaveUser(@RequestBodyUseruser){ try{ return_userService.save(user); }catch(Throwablee){ logger.error(e.getMessage(),e); throwe; } } @Override publicUserupdateUser(@RequestBodyUseruser){ return_userService.update(user); } @Override publicvoiddeleteUser(String[]userIds){ for(StringuserId:userIds){ _userService.deleteById(userId); } } @Override publicListqueryAll(){ return_userService.queryAll(); } @Override publicList queryByName(Stringname){ return_userService.findByName(name); } @Override publicList queryChildren(StringparentId){ return_userService.findByParentId(parentId); } @Override publicUsergetUser(StringuserId){ return_userService.findById(userId); } @Override publicList queryByPage(intpageNo,intpageSize,Useruser){ returnnull; } }
packagecom.my.service; importjava.util.List; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Service; importcom.my.entity.User; importcom.my.repository.UserRepository; @Service publicclassUserServiceextendsBaseService{ @Autowired UserRepository_userRepository; publicList findByName(Stringname){ return_userRepository.findByName(name); } publicList findByParentId(StringparentId){ return_userRepository.findByParentId(parentId); } }
packagecom.my.repository; importjava.util.List; importcom.my.entity.User; publicinterfaceUserRepositoryextendsBaseRepository{ List findByName(Stringname); List findByParentId(StringparentId); }
以上采用了分层模式,有点繁琐,但是对之后修改每层的业务逻辑比较方便
JPA相关的类如下:
packagecom.my.service; importjava.io.Serializable; importjavax.persistence.EntityManager; importjavax.transaction.Transactional; importorg.springframework.beans.factory.annotation.Autowired; importcom.my.repository.BaseRepository; /** *一些共有的方法放这里 **/ @Transactional publicclassBaseService{ @Autowired BaseRepository _baseRepository; @Autowired EntityManagerem; publicEsave(EbaseUnit){ return_baseRepository.saveAndFlush(baseUnit); } publicEupdate(EbaseUnit){ return_baseRepository.saveAndFlush(baseUnit); } publicvoiddeleteById(Stringid){ _baseRepository.delete(id); } publicjava.util.List queryAll(){ return_baseRepository.findAll(); } publicEfindById(Stringid){ return_baseRepository.getOne(id); } }
packagecom.my.repository; importjava.io.Serializable; importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean publicinterfaceBaseRepositoryextendsJpaRepository { }
实体类:与数据库字段相关,需要注意下父类中的注解@MappedSuperclass
packagecom.my.entity; importjava.util.ArrayList; importjava.util.List; importjavax.persistence.Entity; importjavax.persistence.ManyToMany; importorg.hibernate.annotations.DynamicInsert; importorg.hibernate.annotations.DynamicUpdate; importorg.hibernate.validator.constraints.Email; @Entity(name="db_user") @DynamicInsert @DynamicUpdate publicclassUserextendsBaseUnit{ /** *账户状态 */ publicstaticenumAccountStatus{ /** *正常 */ Enable,// /** *停用 */ Disable } privatestaticfinallongserialVersionUID=-3101319619397064425L; privateStringpassword; privateStringsalt; /**账户状态*/ privateAccountStatusstatus; /**认证邮箱*/ @Email(message="User.email属性必须符合邮箱格式") privateStringemail; /**移动电话号码*/ privateStringmobileNo; /**身份证号码*/ privateStringcardId; @ManyToMany(targetEntity=Role.class) privateListroleIds; /**昵称。可选。*/ privateStringnickName; publicStringgetCardId(){ returncardId; } publicStringgetEmail(){ returnemail; } publicStringgetMobileNo(){ returnmobileNo; } publicStringgetNickName(){ returnnickName; } publicStringgetPassword(){ returnpassword; } publicList getRoleIds(){ if(roleIds==null){ roleIds=newArrayList<>(); } returnroleIds; } publicStringgetSalt(){ returnsalt; } publicAccountStatusgetStatus(){ returnstatus; } publicvoidsetCardId(StringcardId){ this.cardId=cardId; } publicvoidsetEmail(Stringemail){ this.email=email; } publicvoidsetMobileNo(StringmobileNo){ this.mobileNo=mobileNo; } publicvoidsetNickName(StringnickName){ this.nickName=nickName; } publicvoidsetPassword(Stringpassword){ this.password=password; } publicvoidsetRoleIds(List roleIds){ this.roleIds=roleIds; } publicvoidsetSalt(Stringsalt){ this.salt=salt; } publicvoidsetStatus(AccountStatusstatus){ this.status=status; } }
packagecom.my.entity; importjava.io.Serializable; importjava.util.Date; importjavax.persistence.Id; importjavax.persistence.MappedSuperclass; importjavax.validation.constraints.NotNull; importjavax.validation.constraints.Size; importorg.springframework.data.annotation.CreatedBy; importorg.springframework.data.annotation.CreatedDate; importorg.springframework.data.annotation.LastModifiedBy; importorg.springframework.data.annotation.LastModifiedDate; @MappedSuperclass publicclassBaseUnitimplementsSerializable{ @Id @NotNull publicStringid; /** *父单元ID */ @Size(max=32,message="BaseUnit.parentId属性长度不能大于32") publicStringparentId; /**父单元的类型*/ publicParentTypeparentType; /** *单元的名称 */ @NotNull(message="BaseUnit.name属性不能为空") publicStringname; @CreatedBy publicStringcreateBy; @CreatedDate publicDatecreateDate; @LastModifiedBy publicStringlastModifiedBy; /** *最后更新日期 */ @LastModifiedDate publicDatelastModifiedDate; publicStringgetId(){ returnid; } publicvoidsetId(Stringid){ this.id=id; } /** *获取单元的名称 * *@return必填 */ publicStringgetName(){ returnname; } /** * * *@returnUUID,不含{}和- */ publicStringgetParentId(){ returnparentId; } publicParentTypegetParentType(){ returnparentType; } publicStringgetStationId(){ returnstationId; } publicStringgetThumbnailId(){ returnthumbnailId; } publicStringgetCreateBy(){ returncreateBy; } publicvoidsetCreateBy(StringcreateBy){ this.createBy=createBy; } publicDategetCreateDate(){ returncreateDate; } publicvoidsetCreateDate(DatecreateDate){ this.createDate=createDate; } /** *设置单元的名称 * *@paramname *必填 */ publicvoidsetName(Stringname){ this.name=name; } /** *设置父单元ID * *@paramparentId *UUID,不含{}和- */ publicvoidsetParentId(StringparentId){ this.parentId=parentId; } publicStringgetLastModifiedBy(){ returnlastModifiedBy; } publicvoidsetLastModifiedBy(StringlastModifiedBy){ this.lastModifiedBy=lastModifiedBy; } publicDategetLastModifiedDate(){ returnlastModifiedDate; } publicvoidsetLastModifiedDate(DatelastModifiedDate){ 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字符串
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。