1. Add dependencies to pom
<!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> org.springframework.bootspring-boot-starter-data-jpamysqlmysql-connector-java5.1.42
2. Add data source configuration (DataSource or something, a series of objects spring boot will inject to you, configuration Just configure it! )
spring.datasource.url=jdbc:mysql:spring.datasource.username==123456--name=-wait=10000-active=300-on-borrow=-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. Create a new entity
@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 Layer
public interface UserDao{ User getById(int id); User getByNumber(String number);int addUser(User user);void deleteUserById(int id); User updateUser(User user); }
@Repositorypublic class UserDaoImpl implements UserDao { @PersistenceContextprivate EntityManager entityManager; @Overridepublic User getById(int id) {//find by primary keyreturn this.entityManager.find(User.class,id); } @Overridepublic 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; } @Overridepublic int addUser(User user) {this.entityManager.persist(user);//print the id System.out.println(user.getId());return user.getId(); } @Overridepublic void deleteUserById(int id) { User user = this.entityManager.find(User.class,id); //关联到记录,方可删除this.entityManager.remove(user); } @Overridepublic User updateUser(User user) { User userNew = this.entityManager.merge(user);return userNew; } }
5.service layer
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 @Transactionalpublic class UserServiceImpl implements UserService { @Autowiredprivate 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); } @Overridepublic int addUser(User user,boolean throwEx) {int id= this.userDao.addUser(user);if(throwEx){throw new RuntimeException("throw a ex"); }return id; } @Overridepublic void deleteUserById(int id) {this.userDao.deleteUserById(id); } @Overridepublic User updateUser(User user) {return this.userDao.updateUser(user); } }
6.controller layer
@Controller("user1") @RequestMapping("/jpa/user")public class UserController {/** * 日志(slf4j->logback) */private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowiredprivate UserService userService;/** * 返回text格式数据 * @param id 主键id * @return 用户json字符串 */@RequestMapping("/get/id/{id}") @ResponseBodypublic 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}") @ResponseBodypublic User getUserByNumber(@PathVariable("number")String number){ User user = userService.getByNumber(number);return user; } @RequestMapping("/add/{number}/{name}") @ResponseBodypublic 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}") @ResponseBodypublic void getUserById(@PathVariable("id")int id){this.userService.deleteUserById(id); } @RequestMapping("/update/{id}/{number}/{name}") @ResponseBodypublic 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. New way to use spring data jpa, more advanced
1.dao @Repositorypublic interface UserRepository extends JpaRepository<user> {/** * 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.servicepublic 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 @Transactionalpublic class UserServiceImpl implements UserService { @Autowiredprivate UserRepository userRepository; @Overridepublic User findById(int id) {return this.userRepository.findOne(id); } @Overridepublic User findByNumber(String number) {return this.userRepository.findByNumber(number); } @Overridepublic List<user> findAllUserByPage(int page,int size) { Pageable pageable = new PageRequest(page, size); Page<user> users = this.userRepository.findAll(pageable);return users.getContent(); } @Overridepublic User updateUser(User user,boolean throwEx) { User userNew = this.userRepository.save(user);if(throwEx){throw new RuntimeException("throw a ex"); }return userNew; } @Overridepublic 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); @Autowiredprivate UserService userService;/** * 返回text格式数据 * @param id 主键id * @return 用户json字符串 */@RequestMapping("/get/id/{id}") @ResponseBodypublic 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}") @ResponseBodypublic User getUserByNumber(@PathVariable("number")String number){ User user = userService.findByNumber(number);return user; } @RequestMapping("/get/all/{page}/{size}") @ResponseBodypublic List<user> getAllUserByPage(@PathVariable("page")int page,@PathVariable("size")int size){return this.userService.findAllUserByPage(page,size); } @RequestMapping("/update/{id}/{number}/{name}") @ResponseBodypublic 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}") @ResponseBodypublic void getUserById(@PathVariable("id")int id){this.userService.deleteUser(id); } }</user></user></user></user></user>
8. Inject jdbcTemplate and transactionTemplate, use the traditional way to operate the database, more flexible, the method is as follows
@Autowiredprivate JdbcTemplate jdbcTemplate; @Autowiredprivate TransactionTemplate transactionTemplate;/** * 手动控制事物测试 * @param throwEx */@Overridepublic void testTransactionManually(boolean throwEx) {try { transactionTemplate.execute(new TransactionCallback<boolean>() {/** * 事物代码 * * @param transactionStatus 事物状态 * @return 是否成功 */@Overridepublic Boolean doInTransaction(TransactionStatus transactionStatus) { User user = new User(); user.setId(1);int a = new Random().nextInt(10); //0-9user.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测试 */@Overridepublic void testJdbcTemplate() { User user = new User();int a = new Random().nextInt(10); //0-9user.setNumber("10000i"+ a ); user.setName("name"+a);this.jdbcTemplate.update("INSERT into USER(NUMBER,NAME )VALUES (?,?)",user.getNumber(),user.getName()); }</boolean>
So far, I have talked about how to operate the database in three ways (two jpa + jdbcTemplate). You can use it however you like. The above codes are all proven feasible in practice!
The above is the detailed content of spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate. For more information, please follow other related articles on the PHP Chinese website!

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

spring设计模式有:1、依赖注入和控制反转;2、工厂模式;3、模板模式;4、观察者模式;5、装饰者模式;6、单例模式;7、策略模式和适配器模式等。详细介绍:1、依赖注入和控制反转: 这两个设计模式是Spring框架的核心。通过依赖注入,Spring负责管理和注入组件之间的依赖关系,降低了组件之间的耦合度。控制反转则是指将对象的创建和依赖关系的管理交给Spring容器等等。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version
