精华内容
下载资源
问答
  • JPA操作数据库

    2021-12-06 15:43:57
    1.继承JpaRepository口后操作数据库 public interface BaseReposittory <T,ID extends Serializable> extends JpaRepository<T,ID>{ } 2.@Query注解查询 public interface BaseReposittory <T,...

    1.继承JpaRepository口后操作数据库

    public interface BaseReposittory <T,ID extends Serializable> extends JpaRepository<T,ID>{ }

    2.@Query注解查询

    public interface BaseReposittory <T,ID extends Serializable> extends JpaRepository<T,ID>{

    如果想用原生sql操作数据库只需在注解@Query中加nativeQuery =true 

     //查询所有 
    2 @Query(nativeQuery =true,value = "select * from employee where username=?;") 
    3 Employee query04(String name);

    3.继承接口JpaSpecificationExecutor

        JpaSpecificationExecutor的认识  

        JpaSpecificationExecutor(JPA规则执行者)是JPA2.0提供的Criteria API的使用封装,可以用于动态生成Query来满足我们业务中的各种复杂场景。

    Spring Data JPA为我们提供了JpaSpecificationExecutor接口,只要简单实现toPredicate方法就可以实现复杂的查询。所有查询都要求传入一个Specification对象

    @NoRepositoryBean 
    //告诉JPA不要创建对应接口的bean对象 
    public interface BaseReposittory <T,ID extends Serializable> extends JpaRepository<T,ID>,JpaSpecificationExecutor<T> { }
    1 /**
     2      * 根据相应的规则(Specification) 查询对应数据
     3      *  Predicate: where username=? and email =?
     4      *      root : 根 -> 可以获取到类中的属性(username,email)
     5      *      criteriaQuery: 如select,from,where,group by ,order by 等
     6      *      criteriaBuilder:解决 username=? / username like ? / age > ?
     7      *                      多个条件结合 username=?  and/or  age > ?
     8      */
     9     @Test//多条件查询+分页+排序
    10     public void testJpaSpecificationExecutor() throws Exception{
    11         //先定义规范
    12         Specification spec= new Specification<Employee>() {
    13             @Override
    14             public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cd) {
    15                 Path usernamePath = root.get("username");
    16                 Predicate p1 = cd.like(usernamePath, "%1%");
    17                 Path emailPath = root.get("email");
    18                 Predicate p2 = cd.like(emailPath, "%2%");
    19                 Path agePath = root.get("age");
    20                 Predicate p3 = cd.ge(agePath, 18);//le 表示小于 ge表示大于
    21                 //多个条件连接起来
    22                 Predicate p = cd.and(p1, p2, p3);
    23                 return p;
    24             }
    25         };
    26         //进行排序
    27         Sort sort = new Sort(Sort.Direction.ASC,"username");
    28         //进行分页
    29         Pageable page=new PageRequest(0,10,sort);
    30         //查询数据库
    31         Page p = employeeRepository.findAll(spec, page);
    32         p.forEach(e->{
    33             System.out.println(e);
    34         });
    35     }

    Root:查询哪个表(定位到表和字段-> 用于拿到表中的字段)

    * 可以查询和操作的实体的根

    * Root接口:代表Criteria查询的根对象,Criteria查询的查询根定义了实体类型,能为将来导航获得想要的结果,它与SQL查询中的FROM子句类似

    * Root 相当于 from Employee

    * Root 相当于 from Product

    *    CriteriaQuery:查询哪些字段,排序是什么(主要是把多个查询的条件连系起来)

    *   CriteriaBuilder:字段之间是什么关系,如何生成一个查询条件,每一个查询条件都是什么方式

    * 主要判断关系(和这个字段是相等,大于,小于like等)

    *    Predicate(Expression):单独每一条查询条件的详细描述 整个 where xxx=xx and yyy=yy ...

    4.

    @Autowired
    private  EntityManager entityManager;
    
    
     String orgnaizationProfilesql = "select * from orgnaization_profile t where t.pay_status= "
                + CBSBankInterfaceEnumInte.ERAGNOPR.APPAYSAVX_BUSSTATUS_4.getNodeName() + " or (t.pay_status= "
                + CBSBankInterfaceEnumInte.ERAGNOPR.APPAYSAVX_BUSSTATUS_3.getNodeName() + " and t.auditStatus = "
                + CBSBankInterfaceEnumInte.CBS_INTERFACE_RESULT_APSALSAVZ.ERAGNSTA_STATUS_INCOMPLETE.getCode() + ")";
    // 待处理:使用别名方式转化DTO
            List<OrgnaizationProfileEntity> resultList = new ArrayList<OrgnaizationProfileEntity>();
            resultList = entityManager.createNativeQuery(orgnaizationProfilesql, OrgnaizationProfileEntity.class)
                .getResultList();
    
    

    展开全文
  • 第七章 使用JPA操作数据库本章主要介绍如何在Spring Boot的Web应用中使用Mysq数据库,也充分展示Spring Boot的优势(尽可能少的代码和配置).数据访问层我们将使用Spring Data JPA和Hibernate(JPA的实现之一).Maven ...

    第七章 使用JPA操作数据库

    本章主要介绍如何在Spring Boot的Web应用中使用Mysq数据库,也充分展示Spring Boot的优势(尽可能少的代码和配置).

    数据访问层我们将使用Spring Data JPA和Hibernate(JPA的实现之一).

    Maven pom.xml文件

    lightsword/pom.xml

    在项目中增加如下依赖文件

    org.springframework.boot

    spring-boot-starter-web

    org.springframework.boot

    spring-boot-starter-data-jpa

    mysql

    mysql-connector-java

    配置文件application.properties

    在src/main/resources/application.properties中设置数据源和jpa配置:

    #mysql

    spring.datasource.url = jdbc:mysql://localhost:3306/lightsword?useUnicode=true&characterEncoding=UTF8

    spring.datasource.username = root

    #root@localhost ::TZaMojg3ntd

    spring.datasource.password = root

    spring.datasource.driverClassName = com.mysql.jdbc.Driver

    spring.datasource.max-active=0

    spring.datasource.max-idle=0

    spring.datasource.min-idle=0

    spring.datasource.max-wait=10000

    spring.datasource.max-wait-millis=31536000

    # Specify the DBMS

    spring.jpa.database = MYSQL

    # Show or not log for each sql query

    spring.jpa.show-sql = true

    # Hibernate ddl auto (create, create-drop, update)

    spring.jpa.hibernate.ddl-auto = update

    # Naming strategy

    spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

    # stripped before adding them to the entity manager)

    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

    全部的配置都在如上的文件中了,不需要另外的XML配置和Java配置。

    上文中的数据库配置,你需要换成你的数据库的地址和用户名密码。

    hibernate的ddl-auto=update配置表名,数据库的表和列会自动创建(根据Java实体类,在scala中,只要在实体类上标注@Entity,成员变量上标注@BeanProperty),这里 可以看到更多得hibernate配置。

    实体类

    创建一个HttpApi实体类,实体和Mysql数据库的http_api表相对应(这个表字段会在应用启动的时候,自动生成)。

    package com.springboot.in.action.entity

    import java.util.Date

    import javax.persistence.{ Entity, GeneratedValue, GenerationType, Id }

    import scala.language.implicitConversions

    import scala.beans.BeanProperty

    @Entity

    class HttpApi {

    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    @BeanProperty

    var id: Integer = _

    @BeanProperty

    var httpSuiteId: Integer = _

    //用例名称

    @BeanProperty

    var name: String = _

    //用例状态: -1未执行 0失败 1成功

    @BeanProperty

    var state: Integer = _

    //接口

    @BeanProperty

    var url: String = _

    //方法GET,POST

    @BeanProperty

    var method: String = _

    //post参数json string

    @BeanProperty

    var paramJsonStr: String = _

    //期望输出

    @BeanProperty

    var expectOutput: String = _

    //实际输出

    @BeanProperty

    var actualOutput: String = _

    @BeanProperty

    var runTimes: Integer = _

    @BeanProperty

    var owner: String = _

    @BeanProperty

    var gmtCreate: Date = _

    @BeanProperty

    var gmtModify: Date = _

    }

    实体的数据访问层HttpApiDao

    实体的数据访问层HttpApiDao非常简单,只需要继承CrudRespositroy即可,CrudRespositroy已经实现了save,delete,deleteAll,findOne和findAll.

    (比较神奇的时这些方法其实CrudRespositroy中其实并没有实现,并且通过对dao层的方法的命名还可以实现新的方法).

    当然,如果基本的CRUD方法满足不了我们稍微复杂一些的sql查询,我们可以直接定义sql查询语句,绑定dao层的方法.实例在如下代码中可以看到:

    package com.springboot.in.action.dao

    import java.util.List

    import com.springboot.in.action.entity.HttpApi

    import org.springframework.data.jpa.repository.Query

    import org.springframework.data.repository.CrudRepository

    import scala.language.implicitConversions

    trait HttpApiDao extends CrudRepository[HttpApi, Integer] {

    def findAll(): List[HttpApi] // JavaConversions

    def save(t: HttpApi): HttpApi

    def findOne(id: Integer): HttpApi

    @Query(value = "SELECT * FROM http_api where http_suite_id = ?1", nativeQuery = true)

    def listByHttpSuiteId(id: Integer): List[HttpApi]

    @Query(value = "SELECT id FROM http_api where http_suite_id = ?1", nativeQuery = true)

    def listTestCaseId(httpSuiteId: Integer): List[Integer] // 隐式转换,直接用scala的List会报错:javax.persistence.NonUniqueResultException: result returns more than one elements] with root cause

    @Query(value = "SELECT * FROM http_api where name like %?1% ", nativeQuery = true) // like '%?%'

    def findByName(name: String): List[HttpApi]

    @Query(value = "select count(*) from http_api where http_suite_id = ?1 and state = 1", nativeQuery = true)

    def countPass(httpSuiteId: Integer): Int

    @Query(value = "select count(*) from http_api where http_suite_id = ?1 and state = 0", nativeQuery = true)

    def countFail(httpSuiteId: Integer): Int

    }

    重点看一下

    @Query注解里面的value和nativeQuery=true,意思是使用原生的sql查询语句.

    sql模糊查询like语法,我们在写sql的时候是这样写的

    like '%?%'

    但是在@Query的value字符串中, 这样写

    SELECT * FROM http_api where name like %?1%

    在Springboot跟scala集成开发过程中,集合类需要使用java里面的api,直接用scala的List会报错:

    javax.persistence.NonUniqueResultException: result returns more than one elements] with root cause.

    可以显示声明:

    import java.util.List

    也可以使用隐式转换:

    import scala.collection.JavaConversions._

    控制器HttpApiController

    新建控制器HttpApiController.scala代码

    package com.springboot.in.action.controller

    import java.util.Date

    import java.util.concurrent.CountDownLatch

    import com.alibaba.fastjson.JSON

    import com.springboot.in.action.dao.{HttpApiDao, HttpReportDao, HttpSuiteDao}

    import com.springboot.in.action.engine.OkHttp

    import com.springboot.in.action.entity.{HttpApi, HttpReport}

    import org.springframework.beans.factory.annotation.Autowired

    import org.springframework.ui.Model

    import org.springframework.web.bind.annotation.{PathVariable, RequestMapping, RequestMethod, RequestParam, ResponseBody, RestController}

    import org.springframework.web.servlet.ModelAndView

    import scala.collection.JavaConversions._

    @RestController

    @RequestMapping(Array("/httpapi"))

    class HttpApiController @Autowired() (

    val HttpSuiteDao: HttpSuiteDao,

    val HttpApiDao: HttpApiDao,

    val HttpReportDao: HttpReportDao) {

    @RequestMapping(value = {

    Array("", "/")

    }, method = Array(RequestMethod.GET))

    def list(model: Model) = {

    model.addAttribute("httpapis", HttpApiDao.findAll())

    new ModelAndView("/httpapi/list")

    }

    @RequestMapping(value = {

    Array("/json")

    }, method = Array(RequestMethod.GET))

    def listJson() = HttpApiDao.findAll()

    @RequestMapping(value = {

    Array("/listHttpSuiteTestCase")

    }, method = Array(RequestMethod.GET))

    def listHttpSuiteTestCase(model: Model, @RequestParam(value = "httpSuiteId") httpSuiteId: Integer) = {

    var httpapis = HttpApiDao.listByHttpSuiteId(httpSuiteId)

    model.addAttribute("httpapis", httpapis)

    model.addAttribute("httpSuiteId", httpSuiteId)

    model.addAttribute("httpSuiteName", HttpSuiteDao.findOne(httpSuiteId).name)

    new ModelAndView("/httpapi/listHttpSuiteTestCase")

    }

    @RequestMapping(value = {

    Array("/listHttpSuiteTestCaseJson")

    },

    method = Array(RequestMethod.GET))

    @ResponseBody

    def listHttpSuiteTestCaseJson(model: Model, @RequestParam(value = "httpSuiteId") httpSuiteId: Integer) = {

    HttpApiDao.listByHttpSuiteId(httpSuiteId)

    }

    @RequestMapping(Array("/newPage/{httpSuiteId}"))

    def goNewPage(@PathVariable(value = "httpSuiteId") httpSuiteId: Integer, model: Model) = {

    model.addAttribute("httpSuiteId", httpSuiteId)

    model.addAttribute("httpSuiteName", HttpSuiteDao.findOne(httpSuiteId).name)

    new ModelAndView("/httpapi/new")

    }

    /**

    * 项目下面的用例编辑

    */

    @RequestMapping(Array("/editPage/{caseId}"))

    def goEditPage(model: Model, @PathVariable(value = "caseId") caseId: Integer, @RequestParam(value = "httpSuiteId") httpSuiteId: Integer) = {

    val httpapi = HttpApiDao.findOne(caseId)

    model.addAttribute("httpapi", httpapi)

    model.addAttribute("httpSuiteId", httpSuiteId)

    model.addAttribute("httpSuiteName", HttpSuiteDao.findOne(httpSuiteId).name)

    new ModelAndView("/httpapi/edit")

    }

    @RequestMapping(Array("/copyPage/{caseId}"))

    def goCopyPage(model: Model, @PathVariable(value = "caseId") caseId: Integer, @RequestParam(value = "httpSuiteId") httpSuiteId: Integer) = {

    val httpapi = HttpApiDao.findOne(caseId)

    model.addAttribute("httpapi", httpapi)

    model.addAttribute("httpSuiteId", httpSuiteId)

    model.addAttribute("httpSuiteName", HttpSuiteDao.findOne(httpSuiteId).name)

    new ModelAndView("/httpapi/copy")

    }

    @RequestMapping(Array("/detailPage/{id}"))

    def goDetailPage(model: Model, @PathVariable(value = "id") id: Integer) = {

    val httpapi = HttpApiDao.findOne(id)

    model.addAttribute("httpapi", httpapi)

    new ModelAndView("/httpapi/detail")

    }

    @RequestMapping(value = Array("/postnew"),

    method = Array(RequestMethod.POST))

    @ResponseBody

    def newOne(@RequestParam(value = "httpSuiteId") httpSuiteId: Integer,

    @RequestParam(value = "name") name: String,

    @RequestParam(value = "url") url: String,

    @RequestParam(value = "method") method: String,

    @RequestParam(value = "paramJsonStr") paramJsonStr: String,

    @RequestParam(value = "expectOutput") expectOutput: String,

    @RequestParam(value = "actualOutput") actualOutput: String,

    @RequestParam(value = "owner") owner: String) = {

    val httpapi = new HttpApi()

    httpapi.httpSuiteId = httpSuiteId

    httpapi.name = name

    httpapi.url = url

    httpapi.method = method

    httpapi.paramJsonStr = paramJsonStr

    httpapi.expectOutput = expectOutput

    httpapi.actualOutput = actualOutput

    httpapi.runTimes = 0

    httpapi.state = -1

    httpapi.owner = owner

    httpapi.gmtCreate = new Date()

    httpapi.gmtModify = new Date()

    HttpApiDao.save(httpapi)

    }

    @RequestMapping(value = Array("/postedit"),

    method = Array(RequestMethod.POST))

    @ResponseBody

    def editOne(@RequestParam(value = "id") id: Integer,

    @RequestParam(value = "name") name: String,

    @RequestParam(value = "url") url: String,

    @RequestParam(value = "method") method: String,

    @RequestParam(value = "paramJsonStr") paramJsonStr: String,

    @RequestParam(value = "expectOutput") expectOutput: String) = {

    val httpapi = HttpApiDao.findOne(id)

    httpapi.name = name

    httpapi.url = url

    httpapi.method = method

    httpapi.paramJsonStr = paramJsonStr

    httpapi.expectOutput = expectOutput

    httpapi.gmtModify = new Date()

    HttpApiDao.save(httpapi)

    }

    /**

    * 在新建用例页面,调试用例用

    */

    @RequestMapping(value = Array("/debugTest"),

    method = Array(RequestMethod.GET))

    @ResponseBody

    def debugTest(@RequestParam(value = "url") url: String,

    @RequestParam(value = "method") method: String,

    @RequestParam(value = "paramJsonStr") paramJsonStr: String) = {

    OkHttp.run(url, method, paramJsonStr)

    }

    /**

    * 执行用例

    */

    @RequestMapping(value = Array("/runTest"),

    method = Array(RequestMethod.GET))

    @ResponseBody

    def debugTest(@RequestParam(value = "id") id: Integer) = { runTestCase(id) }

    /**

    * 回归项目全部用例,每个用例单独起一个线程跑

    */

    @RequestMapping(value = Array("/testHttpSuite"),

    method = Array(RequestMethod.GET))

    @ResponseBody

    def testProject(@RequestParam(value = "httpSuiteId") httpSuiteId: Integer) = {

    val caseIds = HttpApiDao.listTestCaseId(httpSuiteId)

    val threads = caseIds.size

    val countDownLatch = new CountDownLatch(threads)

    for (cid

    val t = new TestCaseRunner(cid, countDownLatch)

    t.start

    }

    println("回归测试开始......")

    countDownLatch.await // now waiting sub thread done.

    println("回归测试结束!")

    val HttpReport = getHttpReport(httpSuiteId)

    // 保存测试结果

    HttpReportDao.save(HttpReport)

    HttpReport

    }

    def getHttpReport(httpSuiteId: Integer) = {

    println("自动化回归测试报告:")

    val p = HttpSuiteDao.findOne(httpSuiteId)

    val httpSuiteName = p.name

    val pass = HttpApiDao.countPass(httpSuiteId)

    val fail = HttpApiDao.countFail(httpSuiteId)

    val HttpReport = new HttpReport

    HttpReport.httpSuiteId = httpSuiteId

    HttpReport.httpSuiteName = httpSuiteName

    HttpReport.pass = pass

    HttpReport.fail = fail

    HttpReport.time = new Date

    println(JSON.toJSONString(HttpReport, true))

    HttpReport

    }

    /**

    * 执行caseId这个用例

    */

    def runTestCase(id: Integer) = {

    val tc = HttpApiDao.findOne(id)

    val url = tc.url

    val method = tc.method

    val paramJsonStr = tc.paramJsonStr

    println("接口url:" + url)

    println("方法:" + method)

    println("输入参数:" + paramJsonStr)

    val result = OkHttp.run(url, method, paramJsonStr)

    //执行次数+1

    tc.runTimes = tc.runTimes + 1

    println("实际输出:" + result)

    tc.actualOutput = result

    // 结果断言

    val expectOutput = tc.expectOutput

    val contains = result.contains(expectOutput)

    tc.state = if (contains) 1 else 0

    // 执行事件

    tc.gmtModify = new Date

    HttpApiDao.save(tc)

    }

    /**

    * TestCaseRunner

    */

    class TestCaseRunner(val caseId: Integer, val countDownLatch: CountDownLatch) extends Thread {

    override def run() {

    runTestCase(caseId)

    countDownLatch.countDown

    }

    }

    }

    自动装配@Autowired Dao层代码,在Controller实现业务逻辑.

    运行测试

    启动脚本lightsword/run.sh

    mvn clean scala:compile scala:run -Dlauncher=app

    运行lightsword/run.sh,启动应用.

    新建用例集,然后在此用例集中新建一个测试用例,如图所示:

    5b6846ea6d0d33649a7558f567aa19bb.png

    可以直接运行,可以看到测试结果.

    也可以浏览器访问:

    看到Restful接口的json返回:

    [{"id":1,"httpSuiteId":1,"name":"HelloSB测试","state":1,"url":"http://localhost:8888/hello","method":"GET","paramJsonStr":"{}","expectOutput":"LightSword","actualOutput":"{\"conent\":\"Hello, LightSword! Now is: Mon Jun 27 13:23:20 CST 2016\"}","runTimes":1,"owner":"陈光剑","gmtCreate":1467004998000,"gmtModify":1467005001000}]

    展开全文
  • 1、链接数据库的方法 配置application.yml文件即可;内容如下: spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/library username: root password: root...

    初始化工程的目录结构:

    1、链接数据库的方法

              配置application.yml文件即可;内容如下:

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/library
        username: root
        password: root
      jpa:
        hibernate:
          ddl-auto: update #使用create可以自动创建一个表,且每次运行都会重新创建。所以第一次运行用create,后面就要改成update
        show-sql: true #让sql语句在控制台中打印出来,方便我们调试
    
    server:
      port: 8088

    2、spring data jpa 查询数据库

    1、创建实体类:

    package com.supermu.springboot.entity;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    @Entity
    public class Book {
        @Id
        @GeneratedValue
        private Integer id;
    
        private String name;
    
        private String author;
    
        private String publish;
    
        private Integer pages;
    
        private Float price;
    
        private Integer bookcaseid;
    
        private Integer abled;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        public String getPublish() {
            return publish;
        }
    
        public void setPublish(String publish) {
            this.publish = publish;
        }
    
        public Integer getPages() {
            return pages;
        }
    
        public void setPages(Integer pages) {
            this.pages = pages;
        }
    
        public Float getPrice() {
            return price;
        }
    
        public void setPrice(Float price) {
            this.price = price;
        }
    
        public Integer getBookcaseid() {
            return bookcaseid;
        }
    
        public void setBookcaseid(Integer bookcaseid) {
            this.bookcaseid = bookcaseid;
        }
    
        public Integer getAbled() {
            return abled;
        }
    
        public void setAbled(Integer abled) {
            this.abled = abled;
        }
    }
    

    2、创建实体操作的repository

    package com.supermu.springboot.repository;
    
    import com.supermu.springboot.entity.Book;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import java.util.List;
    
    public interface BookRepository extends JpaRepository<Book, Integer> {
    
        List<Book> findByName(String name);
    
        List<Book> findByNameAndAuthor(String name, String author);
    }
    

    3、创建逻辑层service

    package com.supermu.springboot.service;
    
    import com.supermu.springboot.entity.Book;
    
    import java.util.List;
    
    public interface BookService {
        public List<Book> findAll();
    
        public List<Book> findByName(String name);
    
        List<Book> findByNameAndAuthor(String name, String author);
    }
    
    package com.supermu.springboot.service.impl;
    
    import com.supermu.springboot.entity.Book;
    import com.supermu.springboot.repository.BookRepository;
    import com.supermu.springboot.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service("bookService")
    public class BookServiceImpl implements BookService {
    
        @Autowired
        private BookRepository bookRepository;
    
        @Override
        public List<Book> findAll() {
            return bookRepository.findAll();
        }
    
        @Override
        public List<Book> findByName(String name) {
            return bookRepository.findByName(name);
        }
    
        @Override
        public List<Book> findByNameAndAuthor(String name, String author) {
            return bookRepository.findByNameAndAuthor(name, author);
        }
    }
    

    4、实现控制层

    package com.supermu.springboot.controller;
    
    import com.supermu.springboot.entity.Book;
    import com.supermu.springboot.repository.BookRepository;
    import com.supermu.springboot.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    import java.util.Optional;
    
    @RestController
    @RequestMapping("/book")
    public class BookController {
    
        @Autowired
        private BookRepository bookRepository;
    
        @Autowired
        private BookService bookService;
    
        @GetMapping("/list")
        public List<Book> list() {
            return bookRepository.findAll();
        }
    
        @GetMapping("/id")
        public Optional<Book> getid(@RequestParam("id") Integer id) {
            return bookRepository.findById(id);
        }
    
        @GetMapping("/name")
        public List<Book> getByName(@RequestParam("name") String name) {
            return bookService.findByName(name);
        }
    
        @GetMapping("/two")
        public List<Book> getByNameAndAuthor(@RequestParam("name") String name, @RequestParam("author") String author) {
            return bookService.findByNameAndAuthor(name, author);
        }
    }
    

    5、接口测试:http://127.0.0.1:8088/book/two?name=%E6%88%91%E4%BB%AC%E4%BB%A8&author=%E6%9D%A8%E7%BB%9B

    展开全文
  • jpa操作数据库

    2021-11-19 14:59:19
    首先创建一些普通对象,用来与数据库的表建立映射关系,在此我们只定义了员工和部门两个实体来进行示例。 @Entity @Table(name = "tbl_employee") // 指定关联的数据库的表名 public class Employee implements ...

    首先创建一些普通对象,用来与数据库的表建立映射关系,在此我们只定义了员工和部门两个实体来进行示例。 

     

    @Entity
    @Table(name = "tbl_employee") // 指定关联的数据库的表名
    public class Employee implements Serializable {
     
        private static final long serialVersionUID = 1L;
     
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id; // 主键ID
     
        private String name; // 姓名
     
        @ManyToOne
        @JoinColumn(name = "department_id")
        private Department department; // 部门
     
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        public String getName() {
            return name;
        }
     
        public void setName(String name) {
            this.name = name;
        }
     
        public Department getDepartment() {
            return department;
        }
     
        public void setDepartment(Department department) {
            this.department = department;
        }
     
    }
    @Entity
    @Table(name = "tbl_department")
    public class Department  implements Serializable{
     
        private static final long serialVersionUID = 1L;
     
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id; // 主键ID
     
        private String name; // 部门名称
     
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        public String getName() {
            return name;
        }
     
        public void setName(String name) {
            this.name = name;
        }
     
    }
    其中,注解@Entity用来标记该类是一个JPA实体类,并使用了注解@Table指定关联的数据库的表名;注解@Id用来定义记录的唯一标识,并结合注解@GeneratedValue将其设置为自动生成。  

    在entity层定义数据库的实体类

    public class Demo {
    
        /**
         * 主键ID
         */
        @Id
        @GenericGenerator(name = "system-uuid", strategy = "uuid")
        @GeneratedValue(generator = "system-uuid")
        @Column(name = "ID", nullable = false, length = 50)
        private String id;
    
        @NotNull(message = "数据类型不能为空")
        @Length(max = 25, message = "数据类型最长25个字符")
        @Column(name = "DATA_TYPE", length = 50, nullable = false)
        private String dataType;
    
        @NotNull(message = "身份证号不能为空")
        @Length(max = 18, message = "身份证号最长18个字符")
        @Column(name = "ID_CARD", length = 18)
        private String idCard;
    
        @NotNull(message = "姓名不能为空")
        @Length(max = 25, message = "姓名最长25个字符")
        @Column(name = "NAME", length = 50)
        private String name;
    
    
        /**
         * 日期
         */
        @Column(name = "DATE_TIME")
        private Timestamp dateTime;
    
    
        /**
         * 创建人、创建部门、创建时间
         */
        @Length(max = 32, message = "创建人单位最长32个字符")
        @Column(name = "CREATE_UNIT_ID", length = 32)
        private String createUnitId;
        @Length(max = 25, message = "创建人单位最长25个字符")
        @Column(name = "CREATE_UNIT_NAME", length = 50)
        private String createUnitName;
        @Length(max = 32, message = "创建人部门最长32个字符")
        @Column(name = "CREATE_ORG_ID", length = 32)
        private String createOrgId;
        @Length(max = 25, message = "创建人部门最长25个字符")
        @Column(name = "CREATE_ORG_NAME", length = 50)
        private String createOrgName;
        @Length(max = 32, message = "创建人最长32个字符")
        @Column(name = "CREATE_USER_ID", length = 32)
        private String createUserId;
        @Length(max = 25, message = "创建人最长25个字符")
        @Column(name = "CREATE_USER_NAME", length = 50)
        private String createUserName;
        @Column(name = "CREATE_TIME")
        private Timestamp createTime;
        /**
         * 更新人、更新部门、更新时间
         */
        @Length(max = 32, message = "更新人最长32个字符")
        @Column(name = "UPDATE_USER_ID", length = 32)
        private String updateUserId;
        @Length(max = 32, message = "更新人部门最长32个字符")
        @Column(name = "UPDATE_ORG_ID", length = 32)
        private String updateOrgId;
        @Column(name = "UPDATE_TIME")
        private Timestamp updateTime;
    
    
        /**
         * 无需入库,在回显时需要处理的字段
         */
        @Transient
        private String dataTypeName;
        @Transient
        private String createTimeFormated;
    }
    上面的  ID主键定义

    代码生成器

    实体类中使用了@Table注解后,想要添加表中不存在的字段,就要使用@Transient这个注解了

    代码生成器CodeGenerator(目前只支持SpringBoot/SpringDataJpa)


    0、为什么使用代码生成器?
    ①、节约创建目录和文件的时间

    ②、节约重复工作时间(增删改查、分页)

    1、背景
    前段时间写了SSM的代码生成器,调用了Mybatis逆向工程API生成Pojo和Mapper,然后生成Controller、Service模板和一大堆资源文件,代码非常繁杂。SSM的确不太适合自动生成,为什么呢?

    ①、繁重的配置,拥有大量的资源文件。

    ②、引入了大量的第三方API,不利于维护升级。

    ③、Service模板依赖于逆向工程的规则。

    2、想法
    基于以上几点,发现SpringBoot+SpringDataJpa能完美解决以上几点问题。原因如下:

    ①、springboot几乎零配置。

    ②、springboot引入的第三方API较少。

    ③、SpringDataJpa是“正向工程”,用代码生成数据库。

    3、使用
    BB了一大堆没用的,等不及的直接看这里。

    ①首先从github下载

    git clone https://github.com/1316151417/CodeGenerator.git

    ②运行jar包

    java -cp CodeGenerator/target/CodeGenerator-0.0.1-SNAPSHOT.jar com.swust.zj.sss.main.SSSGenerator

    然后输入>>>基目录、项目名、自定义包名、实体类名,如图:

    然后就可以看到项目已经生成好了,如图:


    ③运行项目

    此步需注意:

    1、需要查看application.yml中的配置信息是否正确(mysql密码默认123456,等其他信息)

    2、需自己添加实体类的字段(除id)

    自动生成是只包含id的,如图:

    package com.swust.zj.model;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import com.fasterxml.jackson.annotation.JsonGetter;
    @Entity
    public class User {
        private Integer id;
        @Id
        @GeneratedValue
        @JsonGetter
        private Integer getId(){
            return id;
        }
        private void setId(Integer id){
            this.id = id;
        }
    }


    然后我们自己添加一个字段
    package com.swust.zj.model;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import com.fasterxml.jackson.annotation.JsonGetter;
    @Entity
    public class User {
        private Integer id;
        private String name;
        @Id
        @GeneratedValue
        @JsonGetter
        private Integer getId(){
            return id;
        }
        private void setId(Integer id){
            this.id = id;
        }
        private String getName(){
            return name;
        }
        private void setName(String name){
            this.name = name;
        }
    }

    代码生成器

     一、先用idea自带的数据库连接,连接到orcle或者mysql

    二、选中你要代码生成的那个表,然后选择代码生成的目录,就可以进行代码自动生成了

    展开全文
  • 今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作。今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作。步骤一:在pom.xml文件中添加MYSQl和...
  • 在使用jpa操作数据库时,发现新对象无法被save,出现以下两种情况: 一、未set自增主键id的值,只set了对象的其他属性,以为save时会自动配置主键。(实际上数据库确实会帮助我们配置自增主键,前提是数据库创建时...
  • 操作mysql数据库 1.依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <...
  • 1,什么是 JPA JPA 是 Java Persistence API 的简称,中文名 Java 持久层 API。 我们都知道 Hibernate 框架是一个 ORM 框架,而 JPA 则是一种 ORM 规范。JPA 和 Hibernate 的关系就像是 JDBC 与 JDBC 驱动的关系,即...
  • 利用JPA和Mybatis进行数据库访问 配置SpringBoot 打开IDEA File-New-Project-Spring Initializr 4. Springboot配置完成! 利用JPA查询数据 添加一个实体类User,在建立的同时会在数据库中建立表use.
  • jpa创建数据库表 一对多关系 1、创建实体类user以及department,一个department里面有多个user,代码如下 package com.example.springbootjpatest.entity; import ...
  • jpa 查询数据库 视图

    2021-01-19 10:17:40
    补习系列(19)-springboot JPA + PostGreSQLSpringBoot 整合 PostGreSQL一、PostGreSQL简介PostGreSQL是一个功能强大的开源对象关系数据库管理系统(ORDBMS),号称世界上最先进的开源关系型数据库经过长达15年以上的...
  • 简单的来说,Jpa就是一个和mybatis-plus功能类似的一个持久层框架,也是将所有基本的CRUD操作封装好了,下面来介绍一下自动生成数据库表的操作JPA常用注解 1、常用基本注解 @Entity @Table @Basic @Column...
  • 首先,我们在model类里面为column设置数据库default值,以前使用Hibernate的时候的做法是添加sql-type,例如:在JPA里面使用columnDefinition代替sql-type:@Column(columnDefinition="datetime default getdate()")...
  • (4)使用JPA添加CRUD操作:(5)根据测试结果修改代码,再测试,直到被测试的代码完全正确。Questions:1.What is persistent class?持久化类:在应用程序中,用来实现业务问题实体的类(如,在电子...
  • spring.jpa.database=MySQL spring.jpa.show-sql=truespring.jpa.generate-ddl=truespring.jpa.hibernate.ddl-auto=update #spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa....
  • 配置文件、依赖、实体类的创建方法在上一篇博客《使用jpa数据库进行添加数据》的博客中写的有一、查询操作@Test//根据id查找public void find(){EntityManagerFactory factory = Persistence....
  • 1:SpringDataJPAJPA规范的再次封装抽象,底层还是使用了Hibernate的JPA技术实现,是属于Spring的生成体系中的一部分2:SpringData的结构(七个接口)操作数据库的方式一:继承JpaRepository口后操作数据库1:在...
  • JPA概念jpa是Java Persistence API的简称,即为java持久层api,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中,简单来说就是将数据库中的关系表映射为java中的一个类,然后...
  • SQL的读写分离方案,是一种通用的设计,通常可以较好的提升数据库集群的整体负载能力,当一个mysql实例无法支撑客户端的读写负载时,我们首先会想到对数据库进行“读写分离”1)在数据库的架构层面,我们使用M-S架构...
  • jpa与多个数据库

    2021-01-27 02:36:05
    yml 配置server:port: 8081 #设置端口号spring:datasource:primary: #mysql 数据库jdbc-url: jdbc:mysql://localhost:3306/logapi?&characterEncoding=utf-8&serverTimezone=UTCusername: usernamepassword:...
  • 该楼层疑似违规已被系统折叠隐藏此楼查看此楼缓存队列:public class TaskPool {//任务计数private int size;//最大线程数private int maxCount;//剩余线程数private int surCount;//初始化线程数private int max_...
  • 本篇文章主要介绍SpringBoot框架实现Jpa多源数据库的配置,本次使用国产数据库达梦数据库做为数据源。1.准备工作在pom.xml文件中引入Spring Data Jpa依赖:org.springframework.bootspring-boot-starter-data-jpa在...
  • 文章目录pojo层mybatis-plusjpa:service层mybatis-plus:jpa:repository层mybatis-plusjpa:总结 总觉得二者在写法上有相似之处,遂今日想总结一下两个项目中的写法对比。 拿评论功能举例: pojo层 mybatis-plus @...
  • Spring Data JPA底层是使用的 ...-- 数据库相关 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId>
  • 使用JPA规范的DataNucleus框架实现DAO层,如果一直保持连接,两天之后,会抛出异常,下面是配置:<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/book_store?...
  • 1、Spring Data JPA概述 SpringData:Spring 的一个子项目。用于简化数据库访问,支持NoSQL 和 关系数据存储。其主要目标 是使数据库的访问变得方便快 捷。 JPAJPA(Java Persistence API,Java持久化API),定义了...
  • 学完本节,你会感慨springboot结合jpa操作数据库是如此的简单。好了,话不多说,我们开始在springboot中使用jpa。一,创建springboot项目1,创建一个新项目2,定义项目名称,点击next3,勾选Spr...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 50,045
精华内容 20,018
关键字:

jpa操作数据库