SpringBoot_JPA

   日期:2020-05-03     浏览:86    评论:0    
核心提示:SpringBoot_JPA创建SpringBoot工程:springboot_jpa生成项目的pojava

SpringBoot_JPA

  1. 创建SpringBoot工程:springboot_jpa

  2. 生成项目的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>springboot_jpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot_jpa</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
  1. 添加lombok依赖
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<scope>provided</scope>
</dependency>
  1. 把application.properties改成application.yml,添加配置内容:
#数据库连接
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true #在控制台中打印sql
  1. 数据库表employee表结构和内容:

表结构:

主键id自动递增

表内容:

6. 数据库表department表结构和内容:

表结构:

表内容:

7. Employee实体类

package com.example.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.ToString;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Entity		//告诉JPA这是一个要和数据库表映射的实体类
@Table(name="employee")		//用于指定和数据库中的哪个表映射
public class Employee {
	
	@Id		//标识主键
	@GeneratedValue(strategy = GenerationType.IDENTITY)		//设置主键增长类型
	private Integer id;
	
	@Column(name = "last_name")		//指定属性和数据库中的哪个字段映射
	private String lastName;
	
	@Column
	private String email;
	
	@Column
	private Integer gender;
	
	@Column(name = "d_id")
	private Integer departmentId;
}
  1. EmployeeRepository接口
package com.example.demo.repos;

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

import com.example.demo.entity.Employee;


public interface EmployeeRepository extends JpaRepository<Employee, Integer>{

}
  1. 测试类SpringbootJpaApplicationTests
package com.example.demo;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.example.demo.entity.Employee;
import com.example.demo.repos.EmployeeRepository;

@SpringBootTest
class SpringbootJpaApplicationTests {

	@Autowired
	EmployeeRepository er;
	
	@Test
	public void test_findbyId() {
		Optional<Employee> optional = er.findById(3);
		System.out.println(optional);
	}

}
  1. 运行test_findbyId(),控制台打印:
Hibernate: select employee0_.id as id1_0_0_, employee0_.d_id as d_id2_0_0_, employee0_.email as email3_0_0_, employee0_.gender as gender4_0_0_, employee0_.last_name as last_nam5_0_0_ from employee employee0_ where employee0_.id=?
Optional[Employee(id=3, lastName=BLU, email=blu@qq.com, gender=1, departmentId=1)]
  1. 保存单个数据
@Test
public void test_save1() {
	Employee e = new Employee(null, "amy", "amy@gmail.com", 2, 1);
	er.save(e);
}

控制台打印:

Hibernate: insert into employee (d_id, email, gender, last_name) values (?, ?, ?, ?)

数据库增加了一条记录:

12. 保存多个数据

@Test
public void test_save2() {
	Employee e1 = new Employee(null, "amy1", "amy@gmail.com", 2, 1);
	Employee e2 = new Employee(null, "amy2", "amy@gmail.com", 2, 1);
	Employee e3 = new Employee(null, "amy3", "amy@gmail.com", 2, 1);
	er.saveAll(Arrays.asList(e1,e2,e3));
}

控制台打印:

Hibernate: insert into employee (d_id, email, gender, last_name) values (?, ?, ?, ?)
Hibernate: insert into employee (d_id, email, gender, last_name) values (?, ?, ?, ?)
Hibernate: insert into employee (d_id, email, gender, last_name) values (?, ?, ?, ?)

数据库增加了3条记录:

13. 修改数据
注:添加和修改调用的都是save方法,区别是添加方法传入的id为空,修改方法传入的id为要修改的记录的id

@Test
public void test_modify() {
	Employee e = new Employee(1, "zs", "zs@qq.com", 2, 1);
	er.save(e);
}

控制台打印:

Hibernate: select employee0_.id as id1_0_0_, employee0_.d_id as d_id2_0_0_, employee0_.email as email3_0_0_, employee0_.gender as gender4_0_0_, employee0_.last_name as last_nam5_0_0_ from employee employee0_ where employee0_.id=?
Hibernate: update employee set d_id=?, email=?, gender=?, last_name=? where id=?

数据库中的第一条记录被修改了:

14. 删除记录

@Test
public void test_delete() {
	er.deleteById(9);
}

控制台打印:

Hibernate: select employee0_.id as id1_0_0_, employee0_.d_id as d_id2_0_0_, employee0_.email as email3_0_0_, employee0_.gender as gender4_0_0_, employee0_.last_name as last_nam5_0_0_ from employee employee0_ where employee0_.id=?
Hibernate: delete from employee where id=?

数据库中的第9条记录被删除了

15. 查询全部数据

@Test
public void test_findAll() {
	List<Employee> list = er.findAll();
	for(Employee e : list) {
		System.out.println(e);
	}
}

控制台打印:

Hibernate: select employee0_.id as id1_0_, employee0_.d_id as d_id2_0_, employee0_.email as email3_0_, employee0_.gender as gender4_0_, employee0_.last_name as last_nam5_0_ from employee employee0_
Employee(id=1, lastName=zs, email=zs@qq.com, gender=2, departmentId=1)
Employee(id=2, lastName=lisi, email=lisi@163.com, gender=1, departmentId=1)
Employee(id=3, lastName=BLU, email=blu@qq.com, gender=1, departmentId=1)
Employee(id=4, lastName=linda, email=linda.qq.com, gender=2, departmentId=1)
Employee(id=5, lastName=ruby, email=ruby@qq.com, gender=2, departmentId=1)
Employee(id=6, lastName=amy, email=amy@gmail.com, gender=2, departmentId=1)
Employee(id=7, lastName=amy1, email=amy@gmail.com, gender=2, departmentId=1)
Employee(id=8, lastName=amy2, email=amy@gmail.com, gender=2, departmentId=1)
  1. 查询多个数据
@Test
public void test_findAllById() {
	List<Employee> list = er.findAllById(Arrays.asList(2,3,4));
	for(Employee e : list) {
		System.out.println(e);
	}
}

控制台打印:

Hibernate: select employee0_.id as id1_0_, employee0_.d_id as d_id2_0_, employee0_.email as email3_0_, employee0_.gender as gender4_0_, employee0_.last_name as last_nam5_0_ from employee employee0_ where employee0_.id in (? , ? , ?)
Employee(id=2, lastName=lisi, email=lisi@163.com, gender=1, departmentId=1)
Employee(id=3, lastName=BLU, email=blu@qq.com, gender=1, departmentId=1)
Employee(id=4, lastName=linda, email=linda.qq.com, gender=2, departmentId=1)
  1. 分页查询
@Test
public void test_page() {
	PageRequest pageRequest = PageRequest.of(0, 3);
	Page<Employee> page = er.findAll(pageRequest);
	System.out.println("totalpages"+page.getTotalPages());
	List<Employee> list = page.getContent();
	for(Employee e : list) {
		System.out.println(e);
	}
}

控制台打印:

Hibernate: select employee0_.id as id1_0_, employee0_.d_id as d_id2_0_, employee0_.email as email3_0_, employee0_.gender as gender4_0_, employee0_.last_name as last_nam5_0_ from employee employee0_ limit ?
Hibernate: select count(employee0_.id) as col_0_0_ from employee employee0_
totalpages3
Employee(id=1, lastName=zs, email=zs@qq.com, gender=2, departmentId=1)
Employee(id=2, lastName=lisi, email=lisi@163.com, gender=1, departmentId=1)
Employee(id=3, lastName=BLU, email=blu@qq.com, gender=1, departmentId=1)
  1. 排序查询(按id和gender逆序排序)
    注:这里Order要导入的包为:import org.springframework.data.domain.Sort.Order;
@Test
public void test_sort() {
	Order o_id = new Order(Direction.DESC,"id");
	Order o_gender = new Order(Direction.DESC,"gender");
	Sort sort = Sort.by(o_id,o_gender);
	List<Employee> list = er.findAll(sort);
	for(Employee e : list) {
		System.out.println(e);
	}
}

控制台打印:

Hibernate: select employee0_.id as id1_0_, employee0_.d_id as d_id2_0_, employee0_.email as email3_0_, employee0_.gender as gender4_0_, employee0_.last_name as last_nam5_0_ from employee employee0_ order by employee0_.id desc, employee0_.gender desc
Employee(id=8, lastName=amy2, email=amy@gmail.com, gender=2, departmentId=1)
Employee(id=7, lastName=amy1, email=amy@gmail.com, gender=2, departmentId=1)
Employee(id=6, lastName=amy, email=amy@gmail.com, gender=2, departmentId=1)
Employee(id=5, lastName=ruby, email=ruby@qq.com, gender=2, departmentId=1)
Employee(id=4, lastName=linda, email=linda.qq.com, gender=2, departmentId=1)
Employee(id=3, lastName=BLU, email=blu@qq.com, gender=1, departmentId=1)
Employee(id=2, lastName=lisi, email=lisi@163.com, gender=1, departmentId=1)
Employee(id=1, lastName=zs, email=zs@qq.com, gender=2, departmentId=1)
  1. 自定义接口EmployeeDao继承Repository
package com.example.demo.repos;

import org.springframework.data.repository.Repository;
import com.example.demo.entity.Employee;


public interface EmployeeDao extends Repository<Employee, Integer>{

}
  1. 在测试类中注入EmployeeDao
@Autowired
EmployeeDao eDao;
  1. 在EmployeeDao接口中添加方法:
//根据id查询
Employee findById(Integer id);
//根据lastName查询
Employee findByLastName(String uname);
  1. findById测试方法:
@Test
public void test_eDao_findById() {
	Employee e = eDao.findById(3);
	System.out.println(e);
}

控制台打印:

Hibernate: select employee0_.id as id1_0_0_, employee0_.d_id as d_id2_0_0_, employee0_.email as email3_0_0_, employee0_.gender as gender4_0_0_, employee0_.last_name as last_nam5_0_0_ from employee employee0_ where employee0_.id=?
Employee(id=3, lastName=BLU, email=blu@qq.com, gender=1, departmentId=1)
  1. findByLastName方法:
@Test
public void test_eDao_findByLastName() {
	Employee e = eDao.findByLastName("linda");
	System.out.println(e);
}

控制台打印:

Hibernate: select employee0_.id as id1_0_, employee0_.d_id as d_id2_0_, employee0_.email as email3_0_, employee0_.gender as gender4_0_, employee0_.last_name as last_nam5_0_ from employee employee0_ where employee0_.last_name=?
Employee(id=4, lastName=linda, email=linda.qq.com, gender=2, departmentId=1)
  1. 符合SpringData方法定义规范的写法示例:
findByLastName
...where x.lastname = ?1

findByLastnameAndFirstname
...where x.lastname = ?1 and x.firstname = ?2

findByLastnameOrFirstname
...where x.lastname = ?1 or x.firstname = ?2 

findByIdBetween
...where x.id between ?1 and ?2

findByAgeLessThan
...where x.age < ?1

findByAgeLessThanEqual
...where x.age <= ?1

findByAgeGreaterThan
...where x.age > ?1

findByAgeGreaterThanEqual
...where x.age >= ?1

findByAgeIsNull
...where x.age is null

findByAgeIsNotNull
...where x.age not null

findByLastNameLike
...where x.lastname like ?1

findByLastNameNotLike
...where x.lastname not like ?1

findByAgeOrderByLastnameDesc
...where x.age = ?1 order by x.lastname desc

findByLastNameNot
...where x.lastname <> ?1

findByAgeIn
...where x.age in ?1

findByAgeNotIn
...where x.age not in ?1

findByActiveTrue
...where x.active = true

findByActiveFalse
...where x.active = false
 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服