今天学习了在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的更多相关文章

  1. SpringBoot入门基础

    目录 SpringBoot入门 (一) HelloWorld. 2 一 什么是springboot 1 二 入门实例... 1 SpringBoot入门 (二) 属性文件读取... 16 一 自定义属 ...

  2. SpringBoot整合StringData JPA

    目录 SpringBoot整合StringData JPA application.yml User.class UserRepository.java UserController SpringBo ...

  3. springBoot入门教程(图文+源码+sql)

    springBoot入门 1   springBoot 1.1 SpringBoot简介 Spring Boot让我们的Spring应用变的更轻量化.比如:你可以仅仅依靠一个Java类来运行一个Spr ...

  4. SpringBoot 入门实战篇

    SpringBoot入门 使用SpringBoot + mysql + Jpa 快速搭建一个spring项目 Spring Boot 2 + Spring Data JPA + MySQL 8 簡單範 ...

  5. SpringBoot入门学习看这一篇就够了

    1.SpringBoot是什么? SpringBoot是一套基于Spring框架的微服务框架. 2.为什么需要SpringBoot 由于Spring是一个轻量级的企业开发框架,主要的功能就是用于整合和 ...

  6. Springboot 入门及Demo

    一:SpringBoot入门1.1:SpringBoot简介Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的 ...

  7. SpringBoot入门教程(二)CentOS部署SpringBoot项目从0到1

    在之前的博文<详解intellij idea搭建SpringBoot>介绍了idea搭建SpringBoot的详细过程, 并在<CentOS安装Tomcat>中介绍了Tomca ...

  8. SpringBoot入门示例

    SpringBoot入门Demo SpringBoot可以说是Spring的简化版.配置简单.使用方便.主要有以下几种特点: 创建独立的Spring应用程序 嵌入的Tomcat,无需部署WAR文件 简 ...

  9. Spring全家桶系列–[SpringBoot入门到跑路]

    //本文作者:cuifuan Spring全家桶————[SpringBoot入门到跑路] 对于之前的Spring框架的使用,各种配置文件XML.properties一旦出错之后错误难寻,这也是为什么 ...

  10. Springboot spring data jpa 多数据源的配置01

    Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库   global 数据库 ...

随机推荐

  1. 高质量JAVA代码编写规范

    1. Java 命名约定 除了以下几个特例之外,命名时应始终采用完整的英文描述符.此外,一般应采用小写字母,但类名.接口名以及任何非初始单词的第一个字母要大写. 1.1 一般概念 * 尽量使用完整的英 ...

  2. Django_xadmin_应用外键搜索功能错误

    问题: 当我在给某一张表加上外键搜索的时候,会出现 TypeError: Related Field got invalid lookup: icontains 问题原因: a 表关联 b表,也就是说 ...

  3. Storm集群安装与部署

    准备 1.三台虚拟机 192.168.1.128 Nimbus 192.168.1.131 Supervisor 192.168.1.132 Supervisor 2.JDK1.8 3.Zookeep ...

  4. IDEA2017.3.3创建第一个javaweb项目及tomcat部署实战

    一.创建简单web项目 1. 选择jdk(这里有点小问题不是很理解,通过java -verbose查找出来的jdk路径在C盘,这里并不能识别,而我jdk安装的时候有自己的路径在D盘,导入后就是图中的j ...

  5. 【Java SE】如何安装JDK以及配置Java运行环境

    摘要:不管是作为苦逼的Java码农,还是高端大气的Java系统架构师,如果不会安装JDK以及配置Java运行环境,那就巧妇难为无米之炊,不能进行Java后续的代码编写.当然如果你是Myeclipse编 ...

  6. 汉诺塔python3函数编写和过程分析

    !/usr/bin/env python3 -- coding: utf-8 -- 利用递归函数计算阶乘 N! = 1 * 2 * 3 * ... * N def fact(n): if n == 1 ...

  7. zabbix监控-部署(一)

    zabbix之自动化监控-部署篇(一) 标签(空格分隔): linux 笔者Q:972581034 交流群:605799367.有任何疑问可与笔者或加群交流 浅谈监控 监控命令 查看硬件的温度/风扇转 ...

  8. opencv学习手稿(01开篇-显示一张图片)

    使用python36 源码: #-*- coding:utf-8 -*- import cv2 from PIL import Image, ImageTk import numpy as np # ...

  9. mysql主从延迟高的原因

    1.1.1故障1:从库数据与主库冲突 1 2 3 4 5 6 show slave status; 报错:且show slave status\G Slave_I/O_Running:Yes Slav ...

  10. js判断是pc端还是移动端

    function checkMobile() { var pda_user_agent_list = new Array("2.0 MMP", "240320" ...