06拓展 springboot+jpa

拷贝demo-web1 另存为demo-jpa
学习参考:
https://blog.csdn.net/wujiaqi0921/article/details/78789087
https://blog.csdn.net/trntaken/article/details/77870803
注意:
DemoApplication所在的包要能访问到其他类,包括实体、service、dao

step 1:添加依赖

   
        org.springframework.boot
        spring-boot-starter-data-jpa
    
     
        mysql
        mysql-connector-java
        5.1.41


step 2 配置mysql数据源以及JPA

配置数据源,依次为地址、用户名、密码、驱动、最大连接数

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = mysql
spring.datasource.tomcat.max-active=20

配置JPA

从上往下依次数据源mysql、显示ddl语句、自动执行ddl语句(更新、创建或者销毁、创建)

最后两句表示自动在数据库创建实体的表

spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

配置说明

ddl-auto:create----每次运行该程序,没有表格会新建表格,表内有数据会清空
ddl-auto:create-drop----每次程序结束的时候会清空表
ddl-auto:update----每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
ddl-auto:validate----运行程序会校验数据与数据库的字段类型是否相同,不同会报错

step 3编写实体

@GenericGenerator注解配合@GeneratedValue一起使用,@GeneratedValue注解中的"generator"属性要与@GenericGenerator注解中name属性一致,strategy属性表示hibernate的主键生成策略

package com.neuedu.demo.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="t_person")
@GenericGenerator(name = "jpa-uuid", strategy = "uuid")
public class Person {
    @Id
@GeneratedValue(generator = "jpa-uuid")
@Column(length = 32)
private String id;

@Column(name = "name", nullable = true, length = 20)
private String name;

@Column(name = "age", nullable = true, length = 4)
private int age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

step 4 创建接口

package com.neuedu.demo.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.neuedu.demo.domain.Person;

public interface PersonRepository extends JpaRepository {

}

step 5然后写一个rest接口以供测试使用。##

package com.neuedu.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.neuedu.demo.dao.PersonRepository;
import com.neuedu.demo.domain.Person;

@RestController
@RequestMapping(value = "/person")
public class PerconController {
    @Autowired
private PersonRepository personRepository;
    @RequestMapping(path = "/addPerson")
public String addPerson(Person person) {
personRepository.save(person);
    return "success";

}

    @RequestMapping(path = "/deletePerson")
public String deletePerson(String id) {
personRepository.deleteById(id);
return "success";
}
}

运行:
http://localhost/haha/person/addPerson?name=test1&age=18
http://localhost/haha/person/deletePerson?id=4028a681682607d40168260a45ae0000

自动建表,插入删除成功。

修改和查询所有##

修改和添加的区别是修改的请求参数里带有主键id.

PersonRepository personRepository;
public void add(Person p) {

    Person dbp=personRepository.getOne(p.getId);
    System.out.println(dbp.getId);
    personRepository.save(dbp);
    List plist=personRepository.findAll();
    for(Person item:plist){
        System.out.println(item.getName());
    }
    System.out.println("--------------->"+p.getId());
}

分页排序

PageRequest(page,size)
PageRequest(page,size,Sort)

package com.neuedu.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.neuedu.demo.dao.PersonRepository;
import com.neuedu.demo.domain.Person;

             @RequestMapping(path = "/findPage")
 public Page findPage(int curpage,int size){
       //带排序的分页   构建Sort对象 ASC表示正序 desc表示降序
        Sort request_sort=new Sort(Sort.Direction.ASC,"name");
        //把排序对象传给PageRequest(当前页,每页几条,排序规则)
        Pageable page=new PageRequest(0, 2,request_sort);
        /*
         * 不带排序的分页
         * Pageable page=new PageRequest(curpage, size);*/
        Page plist= personRepository.findAll(page);
        for(Person item:plist){
            System.out.println(item.getName());
        } 

        return plist;
 }

页面打印结果:###

{"content":[{"id":"8a99b189687d9fbb01687da201ea0000","name":"wangqj","age":18},{"id":"8a99b189687d9fbb01687da22a680001","name":"zhanghs","age":28}],"pageable":{"sort":{"sorted":false,"unsorted":true,"empty":true},"offset":0,"pageSize":2,"pageNumber":0,"unpaged":false,"paged":true},"totalPages":2,"totalElements":3,"last":false,"number":0,"size":2,"sort":{"sorted":false,"unsorted":true,"empty":true},"numberOfElements":2,"first":true,"empty":false}

查询规范

默认方法如果不能满足,可以通过扩展接口里的方法实现特定查询。接口中名如果满足以下规范,只需要写接口,无须写实现类。这种是约定编程

https://blog.csdn.net/weixin_40344177/article/details/78469815
如service中调用如下方法:

List plist=personRepository.findByNameLike("%wa%");
for(Person item:plist){
System.out.println(item.getName());
}
接口中增加如下方法定义
public interface PersonRepository extends JpaRepository {
List findByNameLike(String string);
}

掌握上面技术已经可以满足大部分查询。复杂查询如何解决?

复杂查询@Query

https://blog.csdn.net/u010775025/article/details/80510596
例子:

controller

@RequestMapping("/query.do")
public String findQuery(String name) {
    List users=personService.query(name);
    for(Object u:users){
        System.out.println(u);
    }
 return "Hello World";
}

 
 

PersonService.java

public List query(String name) {
    return personRepository.findUserAndRole("%"+name+"%");
}

 
 

PersonRepository.java

@Query(value="select a.userid,a.username,a.userpwd,a.email,b.rolename from t_user a,t_roles b"+
 " where a.roleid=b.roleid "+
 " and a.username like ?1 ",nativeQuery=true)
    List findUserAndRole(@Param("username") String username);

 
 

jquery测试页面




复杂表关系,关联映射

请学习hibernate实体类映射知识
如果@Query注解加上nativeQuery=true 则查询语句使用原生sql,不加则使用HQL
https://blog.csdn.net/shuixiou1/article/details/80086013

你可能感兴趣的:(06拓展 springboot+jpa)