spring boot 系列之四:spring boot 整合JPA[通俗易懂]

上一篇我们讲了springboot整合JdbcTemplate来进行数据的持久化,这篇我们来说下怎么通过springboot整合JPA来实现数据的持久化。一、代码实现二、知识点引申关于

大家好,又见面了,我是全栈君。

上一篇我们讲了spring boot 整合JdbcTemplate来进行数据的持久化,

这篇我们来说下怎么通过spring boot 整合JPA来实现数据的持久化。

一、代码实现 

  1. 修改pom,引入依赖
      <!-- 引入jpa 依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>

  2. 修改application.properties,配置相关信息
    #修改tomcat默认端口号
    server.port=8090
    #修改context path
    server.context-path=/test
    
    #配置数据源信息
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=root
    spring.datasource.password=root
    #配置jpa
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    spring.jackson.serialization.indent_output=true

  3. 创建实体类
    package com.study.entity;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="t_user")
    public class User {
    
        @Id @GeneratedValue(strategy=GenerationType.AUTO)
        private Integer id;
        private String userName;
        private String password;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
    }

  4. 创建repository接口并继承CrudRepository
    package com.study.repository;
    
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.data.repository.query.Param;
    
    import com.study.entity.User;
    
    /**
     * 注意:
     * 1.这里这里是interface,不是class
     * 
     * 2.CrudRepository里面的泛型,第一个是实体类,第二个是主键的类型
     * 
     * 3.由于crudRepository 里面已经有一些接口了,如deleteAll,findOne等, 我们直接调用即可
     * 
     * 4.当然,我们也可以根据自己的情况来实现自己的接口,如下面的getUser()方法,jpql语句和hql语句差不多
     * 
     * */
    public interface UserRepository extends CrudRepository<User, Integer> {
    
        /**
         * 我们这里只需要写接口,不需要写实现,spring boot会帮忙自动实现
         * 
         * */
        
        @Query("from User where id =:id ")
        public User getUser(@Param("id") Integer id);
    }

  5. 创建service
    1. 接口
      package com.study.service;
      
      import com.study.entity.User;
      
      
      public interface UserService {
          public User getUser(Integer id);
      }

    2. 实现
      package com.study.service.impl;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      
      import com.study.entity.User;
      import com.study.repository.UserRepository;
      import com.study.service.UserService;
      
      @Service
      public class UserServiceImpl implements UserService {
      
          @Autowired
          UserRepository repository;
          
          @Override
          public User getUser(Integer id) {
              //有两种方式:
              //1.调用crudRepository的接口
      //        return repository.findOne(id);
              //2.调用我们自己写的接口
              return repository.getUser(id);
          }
      
          
      }

  6. 创建controller
    package com.study.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.study.entity.User;
    import com.study.service.UserService;
    
    @RestController
    public class UserController {
        @Autowired
        UserService service;
        
        @RequestMapping("/getUser/{id}")
        public User getUser(@PathVariable("id") Integer id){
            
            return service.getUser(id);
        }
    }

  7. 测试,页面以json格式显示数据库值

    spring boot 系列之四:spring boot 整合JPA[通俗易懂]

二、知识点引申

关于Repository知识点,可以去看下下面这篇文章

https://segmentfault.com/a/1190000012346333

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/120913.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • jsp 和 servlet 有什么区别?

    jsp 和 servlet 有什么区别?jsp和servlet有什么区别?Servlet一种服务器端的Java应用程序 由Web容器加载和管理 用于生成动态Web内容 负责处理客户端请求Jsp是Servlet的扩展,本质上还是Servlet 每个Jsp页面就是一个Servlet实例 Jsp页面会被Web容器编译成Servlet,Servlet再负责响…

    2022年6月15日
    25
  • GiD 自定义 简介

    GiD 自定义 简介目录BlogLinks一、前言二、GiD的程序架构六、参考文献BlogLinksDalNur|博客总目录GiD实用教程GiD前处理实例GiD自定义简介GiD后处理实例一、前言  随着计算机技术的发展,有限元法已成为非常强大的数值模拟工具,广泛应用于各个领域。目前,比较常用的大型商用有限元程序有ANSYS,ABAQUS,MARC,ADINA等,由于它们是通用有限元程序,在某些领域的特殊方面(如对于应力场、渗流场、温度场的耦合问

    2025年8月10日
    3
  • flutter byte(Unit8List) 转 ios Uint8[] 转 c语言char*

    flutter byte(Unit8List) 转 ios Uint8[] 转 c语言char*最近用flutter写ios线上项目,有一个功能让把设备传来的数据加密,而这个坑爹的加密的方法是c语言写的,用flutter各种尝试,始终不能还原c的加密过程,只能调用ios原生代码,然后用原生代码调用c语言加密,然后将加密的数据返回过程是这么个过程,但是3种语言的类型各不相同,所以中间就出现来各种转换,本人一个安卓屌丝,碰到swift和c语言也是一脸懵逼,很简单的东西我搞了2天,先看…

    2022年9月16日
    2
  • Lefse本地运行并更换颜色

    Lefse本地运行并更换颜色首先是lefse的安装由于lefse使用的环境比较早,建议使用conda虚拟环境的方式安装,可以省掉不少麻烦condacreate-nlefsepython=2.7python=2.7#python这里选成2.7否则会卡住环境安装完成后,进入环境安装lefsesourceactivatelefsecondainstalllefse…

    2022年5月9日
    47
  • php实现微信小程序消息通知「建议收藏」

    php实现微信小程序消息通知「建议收藏」接入消息通知指引地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/callback_help.html文档地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#%E6%A8%A1%E7%89%88%E6%B6%88%E6%81%AF%E7%AE%A1%E7%9…

    2022年9月15日
    5
  • HDU-1498-50years,50colors(最大匹配, 枚举)

    HDU-1498-50years,50colors(最大匹配, 枚举)

    2021年7月6日
    86

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号