springboot入门_data-jpa
今天学习了在springboot项目中访问数据库,做下笔记,以备后期查看。
Spring Data JPA 是 Spring 基于 ORM 框架和JPA 规范 封装的一套应用框架,包含了增删改查等常用功能,可以让用户用较少的代码实现对数据的访问和操作进而提高开发效率!
目前我在web开发中,访问数据库的常用ORM框架是hibernate和mybatis,而springboot默认提供的是使用Hibernate操作数据库,下面分别看看在springboot中如何使用hibernate和mybatis。
一 data jpa,springboot-data-jpa帮我们定义了一些简单的接口实现了一些简单的功能,如CURD。我们要使用这些功能,只需要继承接口CrudRepository。
创建建maven的springboot项目,引入所需要的jar,pom.xml文件如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.allen.springboot.learn</groupId>
<artifactId>springboot_data-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent> <dependencies>
<!-- data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> </project>
创建启动类:
/**
*
*/
package com.allen.springboot.learn; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* @author admin
*
*/
@SpringBootApplication
public class Application { /**
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }
创建application.properties属性文件:
##datasource config
#开启包的自动扫描
entitymanager.packagesToScan=com.allen.springboot.learn.entity
#数据库链接
spring.datasource.url=jdbc:mysql://localhost:3306/test
#用户
spring.datasource.username=root
#密码
spring.datasource.password=123456
#自动更新表
spring.jpa.hibernate.ddl-auto=update
#数据库访问方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
#显示sql
spring.jpa.properties.hibernate.show_sql=true
创建实体类:
/**
*
*/
package com.allen.springboot.learn.entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; /**
* @author admin
*
*/
@Entity
@Table(name="t_customer")
public class Customer { @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private int age; protected Customer() {} public Customer(String name, int age){
this.name = name;
this.age = age;
} public Customer(Long id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
} @Override
public String toString(){
return String.format("Customer[id=%d, name='%s', age=%d]", id, name, age);
} 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 int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} }
创建一个CRUD的接口,来实现对象的增删改查,通过继承CrudRepository,使用data jpa提供的简单的CRUD方法,代码如下:
/**
*
*/
package com.allen.springboot.learn.repository; import org.springframework.data.repository.CrudRepository; import com.allen.springboot.learn.entity.Customer; /**
* @author admin
*
*/
public interface CustomerCrudRepository extends CrudRepository<Customer, Long>{ }
下来写个测试类,测试以上方法的执行结果,使用JUnit测试,代码如下:
/**
*
*/
package com.allen.springboot.learn.repository.test; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.allen.springboot.learn.entity.Customer;
import com.allen.springboot.learn.repository.CustomerCrudRepository; /**
* @author admin
*
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class CustomerCrudRepositoryTest { @Autowired
private CustomerCrudRepository customerCrudRepository; @Test
public void testAdd(){
Customer customer = new Customer("smith", 8);
customerCrudRepository.save(customer);
} //@Test
public void testAddList(){
Customer customer = new Customer("kb", 3);
Customer customer1 = new Customer("kg", 4);
List<Customer> list = new ArrayList<Customer>();
list.add(customer);
list.add(customer1);
customerCrudRepository.save(list);
} //@Test
public void exists(){
boolean flag = customerCrudRepository.exists(Long.valueOf(3));
System.out.println(flag);
} //@Test
public void testFindById(){
Customer c = customerCrudRepository.findOne(Long.valueOf(1));
System.out.println(c.toString());
} //@Test
public void testFindAll(){
Iterable<Customer> customers = customerCrudRepository.findAll();
Iterator<Customer> its = customers.iterator();
while(its.hasNext()){
System.out.println(its.next().toString());
}
} //@Test
public void testFindAllByParams(){
List<Long> ids = new ArrayList<Long>();
ids.add(Long.valueOf(2));
ids.add(Long.valueOf(4));
Iterable<Customer> customers = customerCrudRepository.findAll(ids);
Iterator<Customer> its = customers.iterator();
while(its.hasNext()){
System.out.println(its.next().toString());
}
} //@Test
public void testDelete(){
//根据ID删
//customerCrudRepository.delete(Long.valueOf(2));
//通过对象删
//Customer customer = new Customer(Long.valueOf(3), "kg", 4);
//customerCrudRepository.delete(customer);
//通过对象集合删
//List<Customer> list = new ArrayList<Customer>();
//Customer customer1 = new Customer(Long.valueOf(5), "wd", 5);
//list.add(customer1);
//Customer customer2 = new Customer(Long.valueOf(4), "kd", 5);
//list.add(customer2);
//customerCrudRepository.delete(list);
//删除所有
//customerCrudRepository.deleteAll();
} }
一般我们在使用中,还会用到分页,排序查询,对于这种查询,springboot也提供了接口支持。实现很简单,我们只需要继承对应的接口就可以了。代码如下:
创建接口类,并继承PagingAndSortingRepository
/**
*
*/
package com.allen.springboot.learn.repository; import org.springframework.data.repository.PagingAndSortingRepository; import com.allen.springboot.learn.entity.Customer; /**
* @author admin
*
*/
public interface CustomerPagingAndSortingRepository extends PagingAndSortingRepository<Customer, Long> { }
接下来写个测试类,测试排序和分页查询,代码如下:
/**
*
*/
package com.allen.springboot.learn.repository.test; import java.util.Iterator;
import java.util.List; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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.data.domain.Sort.Direction;
import org.springframework.test.context.junit4.SpringRunner; import com.allen.springboot.learn.entity.Customer;
import com.allen.springboot.learn.repository.CustomerPagingAndSortingRepository; /**
* @author admin
*
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class CustomerPagingAndSortingRepositoryTest { @Autowired
private CustomerPagingAndSortingRepository customerPagingAndSortingRepository; //排序查询
//@Test
public void testQueryWithSort(){
Sort sort = new Sort(Direction.DESC, "age");//排序方式和排序字段
Iterable<Customer> customers = customerPagingAndSortingRepository.findAll(sort);
Iterator<Customer> its = customers.iterator();
while(its.hasNext()){
System.out.println(its.next());
}
} //分页查询
//@Test
public void testQueryWithPage(){
Pageable pageable = new PageRequest(2, 3);//页号和页面数据量
Page<Customer> customers = customerPagingAndSortingRepository.findAll(pageable);
List<Customer> list = customers.getContent();
if(list != null && list.size()>0){
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
} //分页 排序
@Test
public void testQueryWithPageAndSort(){
Sort sort = new Sort(Direction.DESC, "age");
Pageable pageable = new PageRequest(1, 3, sort);
Page<Customer> customers = customerPagingAndSortingRepository.findAll(pageable);
List<Customer> list = customers.getContent();
if(list != null && list.size()>0){
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
} }
尽管springboot提供了很多接口方法供我们使用,但有时我们仍然需要根据业务需要来写自己的SQL,这种springboot也是支持的,我们需要继承JpaRepository,然后书写自己的查询,代码如下:
/**
*
*/
package com.allen.springboot.learn.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional; import com.allen.springboot.learn.entity.Customer; /**
* @author admin
*
*/
public interface CustomerSQLRepository extends JpaRepository<Customer, Long> { @Query("select customer from Customer customer where customer.name = ?1 and customer.age = ?2")
List<Customer> selectByNameAndAge(String name, int age); @Transactional
@Modifying// 非 只读,执行修改操作(增、删、改)时需要指定
@Query("update Customer set age = ?2 where name = ?1")
int updateByNameAndAge(String name, int age); }
测试类:
/**
*
*/
package com.allen.springboot.learn.repository.test; import java.util.List; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.allen.springboot.learn.entity.Customer;
import com.allen.springboot.learn.repository.CustomerSQLRepository; /**
* @author admin
*
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class CustomerSQLRepositoryTest { @Autowired
private CustomerSQLRepository customerSQLRepository; //@Test
public void test1(){
List<Customer> customerList = customerSQLRepository.selectByNameAndAge("kobe", 6);
if(customerList != null && customerList.size()>0){
for(Customer customer : customerList){
System.out.println(customer);
}
}else{
System.out.println("没有查询到数据!");
}
} @Test
public void test2(){
customerSQLRepository.updateByNameAndAge("kobe", 38);
} }
下来看看如何使用mybatis。使用mybatis时的配置方式有2种,一种是XML配置方式,一种是annotation注解方法,本文我们使用annotation方式。
创建工程,实体类,启动类和上文一样,我们只需要的启动类上加入注解扫描mybatis接口,通过注解@MapperScan指定要扫描的mapper接口
@MapperScan("com.allen.springboot.learn.mapper") //指定扫描包(com.allen.springboot.learn.mapper)下的接口文件
在pom.xml文件中引入mybatis相关jar文件,依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
创建属性配置文件application.properties
## dataSource
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/springboot
spring.datasource.username = root
spring.datasource.password = 123456 ## mybatis
# 指定xml文件地址
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
在resources目录下创建application.properties配置文件中指定路径下的xml文件,如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.allen.springboot.learn.mapper.CustomerMapper" >
<resultMap id="BaseResultMap" type="com.allen.springboot.learn.entity.Customer" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, name, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select <include refid="Base_Column_List" />
from customer where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from customer
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.allen.springboot.learn.entity.Customer" >
insert into customer (id, name, age)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.allen.springboot.learn.entity.Customer" >
update customer
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.allen.springboot.learn.entity.Customer" >
update customer
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="getAllCustomer" resultMap="BaseResultMap">
select <include refid="Base_Column_List" /> from customer
</select>
</mapper>
下来写个测试类,测试mybatis的方法,代码如下:
/**
*
*/
package com.allen.springboot.learn.mapper.test; import java.util.List; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.allen.springboot.learn.entity.Customer;
import com.allen.springboot.learn.mapper.CustomerMapper; /**
* @author admin
*
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class CustomerMapperTest { @Autowired
private CustomerMapper customerMapper; //@Test
public void testAdd(){
Customer customer = new Customer("kobe", 6);
int result = customerMapper.insert(customer);
System.out.println("添加结果:"+result);
} @Test
public void testQuery(){
Customer customer = customerMapper.selectByPrimaryKey(2);
System.out.println(customer);
} //@Test
public void testList(){
List<Customer> customerList = customerMapper.getAllCustomer();
if(customerList != null && customerList.size()>0){
for(Customer customer : customerList){
System.out.println(customer);
}
}
} //@Test
public void testUpdate(){
Customer customer = new Customer(Long.valueOf(1), "smith", 5);
customerMapper.updateByPrimaryKeySelective(customer);
} //@Test
public void testDelete(){
customerMapper.deleteByPrimaryKey(3);
} }
以上是在springboot中访问数据库的两种方式,有不正确的地方,希望朋友们可以指正。
springboot入门_data-jpa的更多相关文章
- SpringBoot入门基础
目录 SpringBoot入门 (一) HelloWorld. 2 一 什么是springboot 1 二 入门实例... 1 SpringBoot入门 (二) 属性文件读取... 16 一 自定义属 ...
- SpringBoot整合StringData JPA
目录 SpringBoot整合StringData JPA application.yml User.class UserRepository.java UserController SpringBo ...
- springBoot入门教程(图文+源码+sql)
springBoot入门 1 springBoot 1.1 SpringBoot简介 Spring Boot让我们的Spring应用变的更轻量化.比如:你可以仅仅依靠一个Java类来运行一个Spr ...
- SpringBoot 入门实战篇
SpringBoot入门 使用SpringBoot + mysql + Jpa 快速搭建一个spring项目 Spring Boot 2 + Spring Data JPA + MySQL 8 簡單範 ...
- SpringBoot入门学习看这一篇就够了
1.SpringBoot是什么? SpringBoot是一套基于Spring框架的微服务框架. 2.为什么需要SpringBoot 由于Spring是一个轻量级的企业开发框架,主要的功能就是用于整合和 ...
- Springboot 入门及Demo
一:SpringBoot入门1.1:SpringBoot简介Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的 ...
- SpringBoot入门教程(二)CentOS部署SpringBoot项目从0到1
在之前的博文<详解intellij idea搭建SpringBoot>介绍了idea搭建SpringBoot的详细过程, 并在<CentOS安装Tomcat>中介绍了Tomca ...
- SpringBoot入门示例
SpringBoot入门Demo SpringBoot可以说是Spring的简化版.配置简单.使用方便.主要有以下几种特点: 创建独立的Spring应用程序 嵌入的Tomcat,无需部署WAR文件 简 ...
- Spring全家桶系列–[SpringBoot入门到跑路]
//本文作者:cuifuan Spring全家桶————[SpringBoot入门到跑路] 对于之前的Spring框架的使用,各种配置文件XML.properties一旦出错之后错误难寻,这也是为什么 ...
- Springboot spring data jpa 多数据源的配置01
Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库 global 数据库 ...
随机推荐
- MyBatis动态传入表名,字段名参数的解决办法
原文:http://blog.csdn.net/xichenguan/article/details/50393748 要实现动态传入表名.列名,需要做如下修改 添加属性statementType=& ...
- redux学习日志:关于react-redux
首先先强调一句:一定要多读官方文档,而且要精读,否则你会忽略掉很多东西! 一,Provider 刚开始看的时候,大致浏览了一下,知道了这个组件是能够接收store作为它的属性,然后它里面的子组件就可以 ...
- JVM内存划分简介
参考:深入理解JAVA虚拟机(第二版)
- Cacti在selinux开启的情况下使用
# chcon -R -t httpd_sys_content_t /var/www/html/cacti
- GlusterFS最佳实践
标签(linux): glusterfs 笔者Q:972581034 交流群:605799367.有任何疑问可与笔者或加群交流 今天我们来从实战中学习glusterfs 环境准备: gluster-s ...
- git常用命令,学git代码管理
下面是我整理的常用 Git 命令清单.几个专用名词的译名如下. Workspace:工作区 Index / Stage:暂存区 Repository:仓库区(或本地仓库) Remote:远程仓库 一. ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](九)
前言 童鞋们,大家好 我是专注.NET开发者社区建设的实践者Rector. 首先,为自己间隔了两个星期五再更新本系列文章找个不充分的理由:Rector最近工作,家庭的各种事务所致,希望大家谅解. 本文 ...
- 奇怪的问题0xc000007b
自己的程序运行debug版本正常,运行release版本main函数还未进入就弹出异常. 令我感觉很奇怪. 觉得应该就是动态库哪里有问题. 仔细检查,发现并没有缺什么动态库.也不存在版本问题. 最后我 ...
- Django中不返回QuerySets的API -- Django从入门到精通系列教程
该系列教程系个人原创,并完整发布在个人官网刘江的博客和教程 所有转载本文者,需在顶部显著位置注明原作者及www.liujiangblog.com官网地址. Python及Django学习QQ群:453 ...
- 前端开发-DOM
文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口.它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式.我们最为关心的是,DOM把 ...