Maven工程搭建spring boot+spring mvc+JPA的示例
程序员文章站
2023-12-13 21:51:46
本文介绍了maven工程搭建spring boot+spring mvc+jpa的示例,分享给大家,具体如下:
添加spring boot支持,引入相关包:
1、mav...
本文介绍了maven工程搭建spring boot+spring mvc+jpa的示例,分享给大家,具体如下:
添加spring boot支持,引入相关包:
1、maven工程,少不了pom.xml,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><!-- 编译需要而发布不需要的jar包 --> </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包 ,操作数据库的--> <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驱动--> <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。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("/**") // .addresourcelocations("classpath:/meta-inf/resources/**"); }
编写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); //无参数分页查询 @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); }
以上采用了分层模式,有点繁琐,但是对之后修改每层的业务逻辑比较方便
jpa相关的类如下:
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; /** * 一些共有的方法放这里 * */ @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>{ }
实体类:与数据库字段相关,需要注意下父类中的注解@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<string> 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<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; @mappedsuperclass public class baseunit implements serializable { @id @notnull public string id; /** * 父单元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; } /** * 获取单元的名称 * * @return 必填 */ public string getname() { return name; } /** * * * @return uuid,不含{}和- */ 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; } /** * 设置单元的名称 * * @param name * 必填 */ public void setname(string name) { this.name = name; } /** * 设置父单元id * * @param parentid * uuid,不含{}和- */ 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字符串
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。