易思网站管理系统,wordpress固定链接显示404,公司网站推广方案模板,鹏牛网做网站怎么样什么是spring-data 为了简化程序与数据库交互的代码#xff0c;spring提供了一个现成的dao层框架#xff0c;spring家族提供的spring-data适用于关系型数据库和nosql数据库 什么是jpa JPA全称为Java持久性API#xff08;Java Persistence API#xff09;#xff0c;JPA是j… 什么是spring-data 为了简化程序与数据库交互的代码spring提供了一个现成的dao层框架spring家族提供的spring-data适用于关系型数据库和nosql数据库 什么是jpa JPA全称为Java持久性APIJava Persistence APIJPA是java EE 5标准之一是一个ORM规范由厂商来实现该规范目前有hibernate、OpenJPA、TopLink、EclipseJPA等实现。 如何使用JPA 查询 查询所有数据 findAll()分页查询 findAll(new PageRequest(0, 2))根据id查询 findOne()根据实体类属性查询 findByProperty (type Property); 例如findByAge(int age);排序 findAll(sort )Sort sort new Sort(Sort.Direction.DESC, age).and (new Sort(Sort.Direction.DESC, id));条件查询 and/or/findByAgeLessThan/LessThanEqual 等例如 findByUsernameAndPassword(String username , String password)总数 查询 count() 或者 根据某个属性的值查询总数countByAge(int age);是否存在某个id exists()修改删除新增 新增直接使用 save(T) 方法删除 delete() 或者 deleteByProperty 例如deleteByAge(int age) ;更新Modifying Query(update Customer u set u.age ?1 where u.id ?2)int update(int age1 , long id);项目结构 相关配置 pom.xml(部分代码详见源码) dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId
/dependency application.properties # 项目contextPath
server.context-path/jpa
# 服务端口
server.port8080
# session最大超时时间(分钟)默认为30
server.session-timeout60
# 该服务绑定IP地址启动服务器时如本机不是该IP地址则抛出异常启动失败只有特殊需求的情况下才配置
#server.address192.168.1.66# tomcat最大线程数默认为200
server.tomcat.max-threads100
# tomcat的URI编码
server.tomcat.uri-encodingUTF-8#注意中文乱码
spring.datasource.urljdbc:mysql://localhost:3306/test?characterEncodingutf-8
spring.datasource.usernameroot
spring.datasource.password123
spring.datasource.driver-class-namecom.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database MYSQL
# Show or not log for each sql query
spring.jpa.show-sql true
# DDL mode. This is actually a shortcut for the hibernate.hbm2ddl.auto property. Default to create-drop when using an embedded database, none otherwise.
spring.jpa.hibernate.ddl-auto update
# Hibernate 4 naming strategy fully qualified name. Not supported with Hibernate 5.
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 spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性其主要作用是自动创建、更新、验证数据库表结构。该参数的几种配置如下 create每次加载hibernate时都会删除上一次的生成的表然后根据你的model类再重新来生成新表哪怕两次没有任何改变也要这样执行这就是导致数据库表数据丢失的一个重要原因。create-drop每次加载hibernate时根据model类生成表但是sessionFactory一关闭,表就自动删除。update最常用的属性第一次加载hibernate时根据model类会自动建立起表的结构前提是先建立好数据库以后加载hibernate时根据model类自动更新表结构即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后表结构是不会被马上建立起来的是要等应用第一次运行起来后才会。validate每次加载hibernate时验证创建数据库表结构只会和数据库中的表进行比较不会创建新表但是会插入新值。实体类 User.java: package com.itstyle.jpa.model;
import java.io.Serializable;
import javax.persistence.*;
/*** 用户实体(此处注意引用的注解包为javax.persistence*下面的)* 创建者 科帮网* 创建时间 2017年7月25日**/
Entity
Table(name sys_user)
public class User implements Serializable{private static final long serialVersionUID 1L;IdGeneratedValue(strategy GenerationType.AUTO)Column(name id, nullable false)private Long id;Column(nullable false, name name)private String name;Column(nullable false, name age)private Integer age;--- 省略 get set 方法
} 数据操作UserRepository.java: /*** 数据操作层* 创建者 科帮网* 创建时间 2017年7月25日**/
public interface UserRepository extends JpaRepositoryUser, Long {User findByName(String name);User findByAge(Integer age);User findByNameAndAge(String name, Integer age);ListUser findByNameLike(String name);Query(from User u where u.name:name)User findUser(Param(name) String name);} 小伙伴没有没有发现我们只是定义了一个方法而已怎么就这么奇妙的实现的对应功能其实这是Spring-data-jpa的新特性通过解析方法名创建查询。更多解析说明如下 And 等价于 SQL 中的 and 关键字 例如findByUsernameAndPassword(String user, Striang pwd)Or 等价于 SQL 中的 or 关键字例如findByUsernameOrAddress(String user, String addr)Between 等价于 SQL 中的 between 关键字例如SalaryBetween(int max, int min)LessThan 等价于 SQL 中的 例如 findBySalaryLessThan(int max)GreaterThan 等价于 SQL 中的例如 findBySalaryGreaterThan(int min)IsNull 等价于 SQL 中的 is null例如 findByUsernameIsNull()IsNotNull 等价于 SQL 中的 is not null例如 findByUsernameIsNotNull()NotNull 与 IsNotNull 等价Like 等价于 SQL 中的 like例如 findByUsernameLike(String user)NotLike 等价于 SQL 中的 not like例如 findByUsernameNotLike(String user)OrderBy 等价于 SQL 中的 order by例如 findByUsernameOrderBySalaryAsc(String user)Not 等价于 SQL 中的 例如 findByUsernameNot(String user)In 等价于 SQL 中的 in例如 findByUsernameIn(Collection userList) 方法的参数可以是 Collection 类型也可以是数组或者不定长参数NotIn 等价于 SQL 中的 not in例如 findByUsernameNotIn(Collection userList) 方法的参数可以是 Collection 类型也可以是数组或者不定长参数创建一个按单字段排序的Sort对象: new Sort(Sort.Direction.DESC, description).and(new Sort(Sort.Direction.ASC, id)) 最终测试类SpringbootJpaApplication.java: package com.itstyle.jpa;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;import com.itstyle.jpa.model.User;
import com.itstyle.jpa.repository.UserRepository;SpringBootApplication
public class SpringbootJpaApplication implements CommandLineRunner {Autowiredprivate UserRepository userRepository;public static void main(String[] args) {SpringApplication.run(SpringbootJpaApplication.class, args);}Overridepublic void run(String... args) throws Exception {try {User user new User();user.setName(张三);user.setAge(20);userRepository.save(user);ListUser u userRepository.findByNameLike(%张三%);System.out.println(u.size());User us userRepository.findByAge(20);System.out.println(us.getAge());us userRepository.findByName(这是你干);} catch (Exception e) {e.printStackTrace();}}
} 偶遇问题 No identifier specified for entity: 检查一下包是否引入正确引入一下 import javax.persistence.*; 中文乱码问题 spring.datasource.urljdbc:mysql://localhost:3306/test?characterEncodingutf-8 在高版本mysql中需要指定是否进行SSL连接 spring.datasource.urljdbc:mysql://localhost:3306/test?characterEncodingutf-8useSSLfalse 代码https://git.oschina.net/52itstyle/spring-data-jpa 作者 小柒 出处 https://blog.52itstyle.com 转载于:https://www.cnblogs.com/walblog/articles/9483296.html