基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(详解)
1.pom添加依赖
org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java 5.1.42
2.添加数据源配置(DataSource啥的,一系列对象springboot都会给你注入的,配置配置即可!)
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 #databasepoolconfig #Numberofmstowaitbeforethrowinganexceptionifnoconnectionisavailable. spring.datasource.tomcat.max-wait=10000 #Maximumnumberofactiveconnectionsthatcanbeallocatedfromthispoolatthesametime. spring.datasource.tomcat.max-active=300 #Validatetheconnectionbeforeborrowingitfromthepool. spring.datasource.tomcat.test-on-borrow=true #initialpoolsize spring.datasource.tomcat.initial-size=20 #=====================jpaconfig================================ #实体类维护数据库表结构的具体行为: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") publicclassUser{ @Id @Column(name="id") @GeneratedValue(strategy=GenerationType.IDENTITY) privateIntegerid; @Column(name="number") privateStringnumber; @Column(name="name") privateStringname; publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetNumber(){ returnnumber; } publicvoidsetNumber(Stringnumber){ this.number=number; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } }
4.dao层
publicinterfaceUserDao{ UsergetById(intid); UsergetByNumber(Stringnumber); intaddUser(Useruser); voiddeleteUserById(intid); UserupdateUser(Useruser); }
@Repository publicclassUserDaoImplimplementsUserDao{ @PersistenceContext privateEntityManagerentityManager; @Override publicUsergetById(intid){ //findbyprimarykey returnthis.entityManager.find(User.class,id); } @Override publicUsergetByNumber(Stringnumber){ Queryquery=this.entityManager.createQuery("fromUseruwhereu.number=:number",User.class); query.setParameter("number",number); Useruser=(User)query.getSingleResult(); returnuser; } @Override publicintaddUser(Useruser){ this.entityManager.persist(user); //printtheid System.out.println(user.getId()); returnuser.getId(); } @Override publicvoiddeleteUserById(intid){ Useruser=this.entityManager.find(User.class,id);//关联到记录,方可删除 this.entityManager.remove(user); } @Override publicUserupdateUser(Useruser){ UseruserNew=this.entityManager.merge(user); returnuserNew; } }
5.service层
publicinterfaceUserService{ UsergetById(intid); UsergetByNumber(Stringnumber); intaddUser(Useruser,booleanthrowEx); voiddeleteUserById(intid); UserupdateUser(Useruser); }
@Service @Transactional publicclassUserServiceImplimplementsUserService{ @Autowired privateUserDaouserDao; @Override @Transactional(readOnly=true) publicUsergetById(intid){ returnuserDao.getById(id); } @Override @Transactional(readOnly=true) publicUsergetByNumber(Stringnumber){ returnuserDao.getByNumber(number); } @Override publicintaddUser(Useruser,booleanthrowEx){ intid=this.userDao.addUser(user); if(throwEx){ thrownewRuntimeException("throwaex"); } returnid; } @Override publicvoiddeleteUserById(intid){ this.userDao.deleteUserById(id); } @Override publicUserupdateUser(Useruser){ returnthis.userDao.updateUser(user); } }
6.controller层
@Controller("user1") @RequestMapping("/jpa/user") publicclassUserController{ /** *日志(slf4j->logback) */ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(UserController.class); @Autowired privateUserServiceuserService; /** *返回text格式数据 *@paramid主键id *@return用户json字符串 */ @RequestMapping("/get/id/{id}") @ResponseBody publicStringgetUserById(@PathVariable("id")Stringid){ logger.info("request/user/get/id/{id},parameteris"+id); Useruser=userService.getById(Integer.parseInt(id)); returnJSONObject.toJSONString(user); } /** *返回json格式数据 *@paramnumber编号 *@return用户 */ @RequestMapping("/get/number/{number}") @ResponseBody publicUsergetUserByNumber(@PathVariable("number")Stringnumber){ Useruser=userService.getByNumber(number); returnuser; } @RequestMapping("/add/{number}/{name}") @ResponseBody publicStringaddUser(@PathVariable("number")Stringnumber,@PathVariable("name")Stringname,booleanthrowEx){ Useruser=newUser(); user.setNumber(number); user.setName(name); intid=-1; try{ id=userService.addUser(user,throwEx); }catch(RuntimeExceptionex){ System.out.println(ex.getMessage()); } returnString.valueOf(id); } @RequestMapping("/delete/{id}") @ResponseBody publicvoidgetUserById(@PathVariable("id")intid){ this.userService.deleteUserById(id); } @RequestMapping("/update/{id}/{number}/{name}") @ResponseBody publicUseraddUser(@PathVariable("id")intid,@PathVariable("number")Stringnumber,@PathVariable("name")Stringname){ Useruser=newUser(); user.setId(id); user.setNumber(number); user.setName(name); returnuserService.updateUser(user); } }
7.springdatajpa新使用方式,更高级
1.dao @Repository publicinterfaceUserRepositoryextendsJpaRepository{ /** *springdatajpa会自动注入实现(根据方法命名规范) *@return */ UserfindByNumber(Stringnumber); @Modifying @Query("deletefromUseruwhereu.id=:id") voiddeleteUser(@Param("id")intid); } 2.service publicinterfaceUserService{ UserfindById(intid); UserfindByNumber(Stringnumber); List findAllUserByPage(intpage,intsize); UserupdateUser(Useruser,booleanthrowEx); voiddeleteUser(intid); } @Service @Transactional publicclassUserServiceImplimplementsUserService{ @Autowired privateUserRepositoryuserRepository; @Override publicUserfindById(intid){ returnthis.userRepository.findOne(id); } @Override publicUserfindByNumber(Stringnumber){ returnthis.userRepository.findByNumber(number); } @Override publicList findAllUserByPage(intpage,intsize){ Pageablepageable=newPageRequest(page,size); Page users=this.userRepository.findAll(pageable); returnusers.getContent(); } @Override publicUserupdateUser(Useruser,booleanthrowEx){ UseruserNew=this.userRepository.save(user); if(throwEx){ thrownewRuntimeException("throwaex"); } returnuserNew; } @Override publicvoiddeleteUser(intid){ this.userRepository.deleteUser(id); } } 3.controller @Controller("user2") @RequestMapping("/datajpa/user") publicclassUserController{ /** *日志(slf4j->logback) */ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(UserController.class); @Autowired privateUserServiceuserService; /** *返回text格式数据 *@paramid主键id *@return用户json字符串 */ @RequestMapping("/get/id/{id}") @ResponseBody publicStringgetUserById(@PathVariable("id")Stringid){ logger.info("request/user/get/id/{id},parameteris"+id); Useruser=userService.findById(Integer.parseInt(id)); returnJSONObject.toJSONString(user); } /** *返回json格式数据 *@paramnumber编号 *@return用户 */ @RequestMapping("/get/number/{number}") @ResponseBody publicUsergetUserByNumber(@PathVariable("number")Stringnumber){ Useruser=userService.findByNumber(number); returnuser; } @RequestMapping("/get/all/{page}/{size}") @ResponseBody publicList getAllUserByPage(@PathVariable("page")intpage,@PathVariable("size")intsize){ returnthis.userService.findAllUserByPage(page,size); } @RequestMapping("/update/{id}/{number}/{name}") @ResponseBody publicUseraddUser(@PathVariable("id")intid,@PathVariable("number")Stringnumber,@PathVariable("name")Stringname,booleanthrowEx){ Useruser=newUser(); user.setId(id); user.setNumber(number); user.setName(name); UseruserNew=null; try{ userService.updateUser(user,throwEx); }catch(RuntimeExceptionex){ System.out.println(ex.getMessage()); } returnuserNew; } @RequestMapping("/delete/{id}") @ResponseBody publicvoidgetUserById(@PathVariable("id")intid){ this.userService.deleteUser(id); } }
8.注入jdbcTemplate和transactionTemplate,使用传统方式操作数据库,更加灵活,方法如下
@Autowired privateJdbcTemplatejdbcTemplate; @Autowired privateTransactionTemplatetransactionTemplate; /** *手动控制事物测试 *@paramthrowEx */ @Override publicvoidtestTransactionManually(booleanthrowEx){ try{ transactionTemplate.execute(newTransactionCallback(){ /** *事物代码 * *@paramtransactionStatus事物状态 *@return是否成功 */ @Override publicBooleandoInTransaction(TransactionStatustransactionStatus){ Useruser=newUser(); user.setId(1); inta=newRandom().nextInt(10);//0-9 user.setNumber("10000u"+a); jdbcTemplate.update("UPDATEUSERSETNUMBER=?WHEREID=?",newObject[]{user.getNumber(),user.getId()},newint[]{Types.VARCHAR,Types.INTEGER}); if(throwEx){ thrownewRuntimeException("trythrowexception");//看看会不会回滚 } returntrue; } }); }catch(RuntimeExceptionex){ System.out.println(ex.getMessage()); } } /** *手动执行jdbc测试 */ @Override publicvoidtestJdbcTemplate(){ Useruser=newUser(); inta=newRandom().nextInt(10);//0-9 user.setNumber("10000i"+a); user.setName("name"+a); this.jdbcTemplate.update("INSERTintoUSER(NUMBER,NAME)VALUES(?,?)",user.getNumber(),user.getName()); }
至此,我已经讲了三种方式(jpa两种+jdbcTemplate)如何操作数据库了,你爱怎么用就怎么用,上述代码均是实践证明可行的!
以上这篇基于springboot1.5.4集成jpa+hibernate+jdbcTemplate(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。