SpringBoot持久化层操作支持技巧
springboot的持久化层可以是spring内置的轻量级jdbctemplate、也可以是hibernate或mybatis等等,只需要在在工程pom.xml文件中添加对应的依赖就可以了。
新建工程我们能发现,springboot对操作的支持有以下几种:
可见springboot对各种的支持还是挺多的。
入正题。看看对sql的支持。主要选了比较传统/流行/有前景的4个进行操作:
均是采用mysql。
所以应该添加对mysql操作的依赖:
<!--mysql--> <dependency> <groupid>mysql</groupid> mysql-connector-java</artifactid> <scope>runtime</scope> </dependency>
同时,需要对web进行支持,添加web相关依赖
<!--web支持--> <dependency> <groupid>org.springframework.boot</groupid> spring-boot-starter-web</artifactid> </dependency>
需要在application.properties中配置mysql相关信息(也可以使用*.yml)。配置如下:
spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url= jdbc:mysql://localhost:3306/springboottest?useunicode=true&characterencoding=utf-8 spring.datasource.username=root spring.datasource.password=root
实际应用的时候,需要添加数据库连接池,为了方便,就暂时不添加了。
1. springboot用jdbctemplates访问mysql
首先需要添加对jdbctemplates的依赖,可以在新建工程中点击添加,或手动添加
<!--jdbc支持--> <dependency> <groupid>org.springframework.boot</groupid> spring-boot-starter-jdbc</artifactid> </dependency>
目录结构如上,代码如下:
@data public class account { private int id ; private string name ; private double money; }
这里是安装了一个插件,然后只需要添加如下依赖,添加@data注解,就会帮我们自动生成getter和setter,也可以用@getter或@setter注解进行标注。
<dependency> <groupid>org.projectlombok</groupid> lombok</artifactid> </dependency>
public interface iaccountdao { int add(account account); int update(account account); int delete(int id); account findaccountbyid(int id); account selectaccountbyid(int id); list findaccountlist(); }</account>
实现类:
@repository public class accountdaoimpl implements iaccountdao{ @autowired private jdbctemplate jdbctemplate; @override public int add(account account) { return jdbctemplate.update("insert into account(name,money) values(?,?)", account.getname(),account.getmoney()); } @override public int update(account account) { return jdbctemplate.update("update account set name=?,money=? where id=?", account.getname(),account.getmoney(),account.getid()); } @override public int delete(int id) { return jdbctemplate.update("delete from table account where id=?", id); } @override public account findaccountbyid(int id) { list list = jdbctemplate.query("select * from account where id = ?", new object[]{id}, new beanpropertyrowmapper(account.class)); if(list!=null && list.size()>0){ account account = list.get(0); return account; }else{ return null; } } @override public account selectaccountbyid(int id){ return jdbctemplate.queryforobject("select * from account where id = ?", new rowmapper() { @override public account maprow(resultset resultset, int i) throws sqlexception { account account = new account(); account.setid(resultset.getint("id")); account.setname(resultset.getstring("name")); account.setmoney(resultset.getdouble("money")); return account; } },id); } @override public list findaccountlist() { list list = jdbctemplate.query("select * from account", new object[]{}, new beanpropertyrowmapper(account.class)); if(list!=null && list.size()>0) return list; else return null; } }</account></account></account></account>
后续也可以添加更多的操作,包括分页等等。这里主要就是jdbctemplate的操作了,详情也可以查相关资料
service层:
public interface iaccountservice { int add(account account); int update(account account); int delete(int id); account findaccountbyid(int id); account selectaccountbyid(int id); list findaccountlist(); }</account>
实现
@service public class jdbcaccountservice implements iaccountservice { @autowired private iaccountdao accountdao; @override public int add(account account) { return accountdao.add(account); } @override public int update(account account) { return accountdao.update(account); } @override public int delete(int id) { return accountdao.delete(id); } @override public account findaccountbyid(int id) { return accountdao.findaccountbyid(id); } @override public account selectaccountbyid(int id) { return accountdao.selectaccountbyid(id); } @override public list findaccountlist() { return accountdao.findaccountlist(); } } </account>
controller:
@restcontroller @requestmapping("/jdbc/account") public class jdbcaccountcontroller { @autowired private iaccountservice accountservice; @requestmapping(value = "/list",method = requestmethod.<em>get</em>) public list getaccounts(){ return accountservice.findaccountlist(); } @requestmapping(value = "/{id}",method = requestmethod.<em>get</em>) public account getaccountbyid(@pathvariable("id") int id){ // return accountservice.findaccountbyid(id); return accountservice.selectaccountbyid(id); } @requestmapping(value = "/{id}",method = requestmethod.<em>put</em>) public string updateaccount(@pathvariable("id")int id , @requestparam(value = "name",required = true)string name, @requestparam(value = "money",required = true)double money){ account account=new account(); account.setmoney(money); account.setname(name); account.setid(id); int t=accountservice.update(account); if(t==1){ return account.tostring(); }else { return "fail"; } } @requestmapping(value = ""/*,method = requestmethod.post*/) public string postaccount( @requestparam(value = "name")string name, @requestparam(value = "money")double money){ account account=new account(); account.setmoney(money); account.setname(name); int t= accountservice.add(account); if(t==1){ return account.tostring(); }else { return "fail"; } } }</account>
难度不大,只是简单的对数据库进行访问和修改,注意注解不要忘记标注了。
2.springboot 整合jpa
jpa算是比较方便的,用起来只需注意相关规则就可以了,不管jpa还是mybatis,都是有各自优点的,在那里使用方便,就采用哪个,没好坏之分。
首先,也是需要添加相关的依赖
<!--jpa支持--> <dependency> <groupid>org.springframework.boot</groupid> spring-boot-starter-data-jpa</artifactid> </dependency>
创建实体(注意注解)
dao层:这里只做了简单的演示,所以没有添加特殊的操作,直接继承jpa给我们提供的接口,就可以了,后续需要添加一些东西的话,可以添加对应的方法
public interface accountdao extends jparepository { }</account,integer>
controller层:
@restcontroller @requestmapping("/jpa/account") public class jpaaccountcontroller { @autowired private accountdao accountdao; @requestmapping(value = "/list",method = requestmethod.<em>get</em>) public list getaccounts(){ return accountdao.findall(); } @requestmapping(value = "/{id}",method = requestmethod.<em>get</em>) public account getaccountbyid(@pathvariable("id") int id){ return accountdao.findone(id); } @requestmapping(value = "/{id}",method = requestmethod.<em>put</em>) public string updateaccount(@pathvariable("id")int id , @requestparam(value = "name",required = true)string name, @requestparam(value = "money",required = true)double money){ account account=new account(); account.setmoney(money); account.setname(name); account.setid(id); account account1 = accountdao.saveandflush(account); return account1.tostring(); } @requestmapping(value = ""/*,method = requestmethod.post*/) public string postaccount( @requestparam(value = "name")string name, @requestparam(value = "money")double money){ account account=new account(); account.setmoney(money); account.setname(name); account account1 = accountdao.save(account); return account1.tostring(); } }</account>
总体来说,jpa代码很简洁,也很强大,能够实现一些常规的操作,对于开发者来说还是挺高效的,对于一些特殊的需求,也可以看官方给我们的文档,3.springboot整合mybatismybatis在现在也是一个非常流行的持久化层框架了,和hibernate比起来,可以自己编写sql语句,从而利用高效的sql语句制作好的产品。但缺点也是在编写sql语句,这方面有点花时间,相比jpa来说。入正题:
添加依赖:
<!--mybatis支持--> <dependency> <groupid>org.mybatis.spring.boot</groupid> mybatis-spring-boot-starter</artifactid> <version>1.2.0</version> </dependency>
mybatis可以采用两种方式进行编写,一种是基于xml的配置方式,一种是基于注解的方式,选择何种方式,当然是萝卜白菜啦,选最合适自己的。
实体还是上一个例子的实体,这里就不添加了,dao层设计我们先来说一下用注解的方式:注解的方式相比下还是挺方便的,
@mapper public interface accountmapper { @insert("insert info account(name,money) values(#{name},#{money})") int add(@param("name")string name, @param("money")double money); @update("update account set name = #{name}, money = #{money} where id = #{id}") int update(@param("name") string name, @param("money") double money, @param("id") int id); @delete("delete from account where id = #{id}") int delete(int id); @select("select id, name as name, money as money from account where id = #{id}") account findaccount(@param("id") int id); @select("select id, name as name, money as money from account") list findaccountlist(); } </account>
注解单词简单明了,就不解释了,但要注意的是,方法名称也要适当的取好,不然以后对数据库操作多了,有可能会乱,需要不断回来看代码。
service层:
@service public class mybatisaccountservice { @autowired private accountmapper accountmapper; public int add(string name, double money) { return accountmapper.add(name, money); } public int update(string name, double money, int id) { return accountmapper.update(name, money, id); } public int delete(int id) { return accountmapper.delete(id); } public account findaccount(int id) { return accountmapper.findaccount(id); } public list findaccountlist() { return accountmapper.findaccountlist(); } }</account>
对应的controller与上面的没有多大区别
@restcontroller @requestmapping("/mybatis/account") public class mybatisaccountcontroller { @autowired private mybatisaccountservice mybatisaccountservice; @requestmapping(value = "/list", method = requestmethod.<em>get</em>) public list getaccounts() { return mybatisaccountservice.findaccountlist(); } @requestmapping(value = "/{id}", method = requestmethod.<em>get</em>) public account getaccountbyid(@pathvariable("id") int id) { return mybatisaccountservice.findaccount(id); } @requestmapping(value = "/{id}", method = requestmethod.<em>put</em>) public string updateaccount(@pathvariable("id") int id, @requestparam(value = "name", required = true) string name, @requestparam(value = "money", required = true) double money) { int t= mybatisaccountservice.update(name,money,id); if(t==1) { return "success"; }else { return "fail"; } } @requestmapping(value = "/{id}", method = requestmethod.<em>delete</em>) public string delete(@pathvariable(value = "id")int id) { int t= mybatisaccountservice.delete(id); if(t==1) { return "success"; }else { return "fail"; } } @requestmapping(value = "", method = requestmethod.<em>post</em>) public string postaccount(@requestparam(value = "name") string name, @requestparam(value = "money") double money) { int t= mybatisaccountservice.add(name,money); if(t==1) { return "success"; }else { return "fail"; } } }</account>
对比之下,我们再来看看基于xml的配置方式。(偷懒就只做一个了)
public interface accountmapper1 { int update(@param("money") double money, @param("id") int id); }
首先需要写一个接口,然后在application中添加配置
mybatis.mapper-locations=classpath*:mybatis/*mapper.xml mybatis.type-aliases-package=com.jinwen.www.mybatis.bean
很简单,然后编写主要的sql语句了,由于我们的配置,后缀名必须为mapper.xml才可以被扫描到
需要在resources下创建一个mybaits文件夹,并添加xml,这里我们明明为accountmapper.xml.,代码如下
<!--?xml version="1.0" encoding="utf-8"?--> <mapper namespace="com.jinwen.www.mybatis.dao.accountmapper1"> <update id="update"> update account set money=#{money} where id=#{id} </update> </mapper>
注意,命名空间那里,需要填自己的,简单的一个update,做完这几步,就可以了
service层:
@service public class mybatisaccountservice1 { @autowired accountmapper1 accountmapper1; @transactional public void transfer() throws runtimeexception{ accountmapper1.update(90,1);//用户1减10块 用户2加10块 // int i=1/0;//测试事务回滚 accountmapper1.update(110,2); } }
@transactional注解可以实现事务回滚,当发生异常的时候,同样,对于jpa,jdbctemplate也可以添加此注解进行事务处理。
controller层(这里注意的是@mapperscan的注解,是实体的路径)
@restcontroller @requestmapping("/mybatis/account") @mapperscan("com.jinwen.www.mybatis.dao") public class mybatisaccountcontroller1 { @autowired private mybatisaccountservice1 accountservice; @requestmapping(value = "/transfer", method = requestmethod.<em>get</em>) public void transfer(){ accountservice.transfer(); } }
mybatis更多复杂的操作可以想见相关的mybatis资料。4.springboot整合 beetlsql
beetlsql 特点
beetsql是一个全功能dao工具, 同时具有hibernate 优点 & mybatis优点功能,适用于承认以sql为中心,同时又需求工具能自动能生成大量常用的sql的应用。
开发效率无需注解,自动使用大量内置sql,轻易完成增删改查功能,节省50%的开发工作量数据模型支持pojo,也支持map/list这种快速模型,也支持混合模型sql 模板基于beetl实现,更容易写和调试,以及扩展可以针对单个表(或者视图)代码生成pojo类和sql模版,甚至是整个数据库。能减少代码编写工作量维护性sql 以更简洁的方式,markdown方式集中管理,同时方便和数据库sql调试。可以自动将sql文件映射为dao接口类灵活直观的支持支持一对一,一对多,多对多关系映射而不引入复杂的or mapping概念和技术。具备interceptor功能,可以调试,性能诊断sql,以及扩展其他功能其他内置支持主从数据库支持的开源工具支持跨数据库平台,开发者所需工作减少到最小,目前跨数据库支持mysql,postgres,oracle,sqlserver,h2,sqllite,db2. 以上来自beatlsql官网文档。网址:https://ibeetl.com/guide/#beetlsql
总体指标比起来,比mybatis更具备优势,或将成为未来的主流、
首先需要添加依赖
<!--beetlsql支持--> <groupid>com.ibeetl</groupid> beetlsql</artifactid> <version>2.9.5</version>
然后要在主方法类下进行配置(很关键,不然会报一些找不到的错误,或者一些奇怪的错误)
@springbootapplication public class springbootpersistenceapplication { public static void main(string[] args) { springapplication.run(springbootpersistenceapplication.class, args); } //配置包扫描 @bean(name = "beetlsqlscannerconfigurer") public beetlsqlscannerconfigurer getbeetlsqlscannerconfigurer() { beetlsqlscannerconfigurer conf = new beetlsqlscannerconfigurer(); conf.setbasepackage("com.jinwen.www.beetlsql.dao"); conf.setdaosuffix("dao"); conf.setsqlmanagerfactorybeanname("sqlmanagerfactorybean"); return conf; } @bean(name = "sqlmanagerfactorybean") @primary public sqlmanagerfactorybean getsqlmanagerfactorybean(@qualifier("datasource") datasource datasource) { sqlmanagerfactorybean factory = new sqlmanagerfactorybean(); beetlsqldatasource source = new beetlsqldatasource(); source.setmastersource(datasource); factory.setcs(source); factory.setdbstyle(new mysqlstyle()); factory.setinterceptors(new interceptor[]{new debuginterceptor()}); factory.setnc(new underlinednameconversion());//开启驼峰 factory.setsqlloader(new classpathloader("/sql"));//sql文件路径 return factory; } //配置数据库 @bean(name = "datasource") public datasource getdatasource() { return datasourcebuilder.create().url("jdbc:mysql://localhost:3306/springboottest").username("root").password("root").build(); } // //开启事务 // @bean(name = "txmanager") // public datasourcetransactionmanager getdatasourcetransactionmanager(@qualifier("datasource") datasource datasource) { // datasourcetransactionmanager dsm = new datasourcetransactionmanager(); // dsm.setdatasource(datasource); // return dsm; // } }
注意这里的配置包扫描,需要扫描自己的包,不然会包no find
根据配置,编写的“sql”代码将在sql路径下,需要在resources下创建这个文件夹
编写相关操作
实体:
@data public class account { private int id ; private string name ; private double money; }
dao层:
@sqlresource("account") public interface beetlsqlaccountdao extends basemapper { // @sqlstatement(params = "name") account selectaccountbyname(string name); } </account>
@sqlresource注解就是在sql目录下对应的.md文件。如果是java.account则对应是sql目录下的java目录下的account.md文件。这个文件写有相关的对数据库的操作。
注意,这里继承的basemapper是由beetlsql提供的。
account.md 编写
<em>selectaccountbyname </em><em>=== </em>*根据name获account select * from account where name= #name#
controller层:
@restcontroller @requestmapping("/beetlsql/account") public class beetlsqlaccountcontroller { @autowired private beetlsqlaccountdao beetlsqlaccountdao; @requestmapping(value = "/list",method = requestmethod.<em>get</em>) public list getaccounts(){ return beetlsqlaccountdao.all(); } @requestmapping(value = "/{id}",method = requestmethod.<em>get</em>) public account getaccountbyid(@pathvariable("id") int id){ return beetlsqlaccountdao.unique(id); } @requestmapping(value = "",method = requestmethod.<em>get</em>) public account getaccountbyid(@requestparam("name") string name){ return beetlsqlaccountdao.selectaccountbyname(name); } @requestmapping(value = "/{id}",method = requestmethod.<em>put</em>) public string updateaccount(@pathvariable("id")int id , @requestparam(value = "name",required = true)string name, @requestparam(value = "money" ,required = true)double money){ account account=new account(); account.setmoney(money); account.setname(name); account.setid(id); int t= beetlsqlaccountdao.updatebyid(account); if(t==1){ return account.tostring(); }else { return "fail"; } } @requestmapping(value = "",method = requestmethod.<em>post</em>) public string postaccount( @requestparam(value = "name")string name, @requestparam(value = "money" )double money) { account account = new account(); account.setmoney(money); account.setname(name); keyholder t = beetlsqlaccountdao.insertreturnkey(account); if (t.getint() > 0) { return account.tostring(); } else { return "fail"; } } }</account>
注意:springboot没有提供beetlsql的@transactional支持,需要自己添加事务的支持,上面被注释的代码中有编写到