基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(详解)
程序员文章站
2023-12-14 16:12:10
1.pom添加依赖
<...
1.pom添加依赖
<!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-jpa</artifactid> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.42</version> </dependency>
2.添加数据源配置(datasource啥的,一系列对象spring boot 都会给你注入的,配置配置即可!)
spring.datasource.url=jdbc:mysql://localhost/test?characterencoding=utf8&usessl=true spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.driver #database pool config # number of ms to wait before throwing an exception if no connection is available. spring.datasource.tomcat.max-wait=10000 # maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active=300 # validate the connection before borrowing it from the pool. spring.datasource.tomcat.test-on-borrow=true # initial pool size spring.datasource.tomcat.initial-size=20 #=====================jpa config================================ #实体类维护数据库表结构的具体行为:update/create/create-drop/validate/none spring.jpa.hibernate.ddl-auto=none #打印sql语句 spring.jpa.show-sql=true #格式化输出的json字符串 spring.jackson.serialization.indent_output=true
3.新建实体
@entity @table(name="user") public class user { @id @column(name="id") @generatedvalue(strategy = generationtype.identity) private integer id; @column(name="number") private string number; @column(name="name") private string name; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getnumber() { return number; } public void setnumber(string number) { this.number = number; } public string getname() { return name; } public void setname(string name) { this.name = name; } }
4.dao层
public interface userdao{ user getbyid(int id); user getbynumber(string number); int adduser(user user); void deleteuserbyid(int id); user updateuser(user user); }
@repository public class userdaoimpl implements userdao { @persistencecontext private entitymanager entitymanager; @override public user getbyid(int id) { //find by primary key return this.entitymanager.find(user.class,id); } @override public user getbynumber(string number) { query query = this.entitymanager.createquery("from user u where u.number=:number",user.class); query.setparameter("number",number); user user = (user)query.getsingleresult(); return user; } @override public int adduser(user user) { this.entitymanager.persist(user); //print the id system.out.println(user.getid()); return user.getid(); } @override public void deleteuserbyid(int id) { user user = this.entitymanager.find(user.class,id); //关联到记录,方可删除 this.entitymanager.remove(user); } @override public user updateuser(user user) { user usernew = this.entitymanager.merge(user); return usernew; } }
5.service层
public interface userservice { user getbyid(int id); user getbynumber(string number); int adduser(user user,boolean throwex); void deleteuserbyid(int id); user updateuser(user user); }
@service @transactional public class userserviceimpl implements userservice { @autowired private userdao userdao; @override @transactional(readonly = true) public user getbyid(int id) { return userdao.getbyid(id); } @override @transactional(readonly = true) public user getbynumber(string number) { return userdao.getbynumber(number); } @override public int adduser(user user,boolean throwex) { int id= this.userdao.adduser(user); if(throwex){ throw new runtimeexception("throw a ex"); } return id; } @override public void deleteuserbyid(int id) { this.userdao.deleteuserbyid(id); } @override public user updateuser(user user) { return this.userdao.updateuser(user); } }
6.controller层
@controller("user1") @requestmapping("/jpa/user") public class usercontroller { /** * 日志(slf4j->logback) */ private static final logger logger = loggerfactory.getlogger(usercontroller.class); @autowired private userservice userservice; /** * 返回text格式数据 * @param id 主键id * @return 用户json字符串 */ @requestmapping("/get/id/{id}") @responsebody public string getuserbyid(@pathvariable("id")string id){ logger.info("request /user/get/id/{id}, parameter is "+id); user user = userservice.getbyid(integer.parseint(id)); return jsonobject.tojsonstring(user); } /** * 返回json格式数据 * @param number 编号 * @return 用户 */ @requestmapping("/get/number/{number}") @responsebody public user getuserbynumber(@pathvariable("number")string number){ user user = userservice.getbynumber(number); return user; } @requestmapping("/add/{number}/{name}") @responsebody public string adduser(@pathvariable("number")string number,@pathvariable("name")string name,boolean throwex){ user user = new user(); user.setnumber(number); user.setname(name); int id = -1; try{ id = userservice.adduser(user,throwex); }catch (runtimeexception ex){ system.out.println(ex.getmessage()); } return string.valueof(id); } @requestmapping("/delete/{id}") @responsebody public void getuserbyid(@pathvariable("id")int id){ this.userservice.deleteuserbyid(id); } @requestmapping("/update/{id}/{number}/{name}") @responsebody public user adduser(@pathvariable("id")int id, @pathvariable("number")string number, @pathvariable("name")string name){ user user = new user(); user.setid(id); user.setnumber(number); user.setname(name); return userservice.updateuser(user); } }
7. spring data jpa新使用方式,更高级
1.dao @repository public interface userrepository extends jparepository<user, integer> { /** * spring data jpa 会自动注入实现(根据方法命名规范) * @return */ user findbynumber(string number); @modifying @query("delete from user u where u.id = :id") void deleteuser(@param("id")int id); } 2.service public interface userservice { user findbyid(int id); user findbynumber(string number); list<user> findalluserbypage(int page,int size); user updateuser(user user,boolean throwex); void deleteuser(int id); } @service @transactional public class userserviceimpl implements userservice { @autowired private userrepository userrepository; @override public user findbyid(int id) { return this.userrepository.findone(id); } @override public user findbynumber(string number) { return this.userrepository.findbynumber(number); } @override public list<user> findalluserbypage(int page,int size) { pageable pageable = new pagerequest(page, size); page<user> users = this.userrepository.findall(pageable); return users.getcontent(); } @override public user updateuser(user user,boolean throwex) { user usernew = this.userrepository.save(user); if(throwex){ throw new runtimeexception("throw a ex"); } return usernew; } @override public void deleteuser(int id) { this.userrepository.deleteuser(id); } } 3.controller @controller("user2") @requestmapping("/datajpa/user") public class usercontroller { /** * 日志(slf4j->logback) */ private static final logger logger = loggerfactory.getlogger(usercontroller.class); @autowired private userservice userservice; /** * 返回text格式数据 * @param id 主键id * @return 用户json字符串 */ @requestmapping("/get/id/{id}") @responsebody public string getuserbyid(@pathvariable("id")string id){ logger.info("request /user/get/id/{id}, parameter is "+id); user user = userservice.findbyid(integer.parseint(id)); return jsonobject.tojsonstring(user); } /** * 返回json格式数据 * @param number 编号 * @return 用户 */ @requestmapping("/get/number/{number}") @responsebody public user getuserbynumber(@pathvariable("number")string number){ user user = userservice.findbynumber(number); return user; } @requestmapping("/get/all/{page}/{size}") @responsebody public list<user> getalluserbypage(@pathvariable("page")int page,@pathvariable("size")int size){ return this.userservice.findalluserbypage(page,size); } @requestmapping("/update/{id}/{number}/{name}") @responsebody public user adduser(@pathvariable("id")int id, @pathvariable("number")string number, @pathvariable("name")string name,boolean throwex){ user user = new user(); user.setid(id); user.setnumber(number); user.setname(name); user usernew = null; try{ userservice.updateuser(user,throwex); }catch (runtimeexception ex){ system.out.println(ex.getmessage()); } return usernew; } @requestmapping("/delete/{id}") @responsebody public void getuserbyid(@pathvariable("id")int id){ this.userservice.deleteuser(id); } }
8.注入jdbctemplate和transactiontemplate,使用传统方式操作数据库,更加灵活,方法如下
@autowired private jdbctemplate jdbctemplate; @autowired private transactiontemplate transactiontemplate; /** * 手动控制事物测试 * @param throwex */ @override public void testtransactionmanually(boolean throwex) { try { transactiontemplate.execute(new transactioncallback<boolean>() { /** * 事物代码 * * @param transactionstatus 事物状态 * @return 是否成功 */ @override public boolean dointransaction(transactionstatus transactionstatus) { user user = new user(); user.setid(1); int a = new random().nextint(10); //0-9 user.setnumber("10000u" + a); jdbctemplate.update("update user set number=? where id=?", new object[]{user.getnumber(), user.getid()}, new int[]{types.varchar, types.integer}); if (throwex) { throw new runtimeexception("try throw exception"); //看看会不会回滚 } return true; } }); }catch (runtimeexception ex){ system.out.println(ex.getmessage()); } } /** * 手动执行jdbc测试 */ @override public void testjdbctemplate() { user user = new user(); int a = new random().nextint(10); //0-9 user.setnumber("10000i"+ a ); user.setname("name"+a); this.jdbctemplate.update("insert into user(number,name )values (?,?)",user.getnumber(),user.getname()); }
至此,我已经讲了三种方式(jpa两种+jdbctemplate)如何操作数据库了,你爱怎么用就怎么用,上述代码均是实践证明可行的!
以上这篇基于spring boot 1.5.4 集成 jpa+hibernate+jdbctemplate(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
推荐阅读
-
基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(详解)
-
Spring Boot集成Shiro并利用MongoDB做Session存储的方法详解
-
spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制
-
Spring boot 集成 Druid 数据源过程详解
-
spring boot2集成ES详解
-
Spring boot 集成 Druid 数据源过程详解
-
Spring Boot 项目集成Redis的方式详解
-
spring boot如何基于JWT实现单点登录详解
-
spring boot2集成ES详解
-
spring boot 1.5.4入门实例详解